18 /* uncomment this for packet level debugging */
19 /* #define DUMP_PACKETS */
21 #define logevent(s) { logevent(s); \
22 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
23 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
25 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
26 (s ? sk_close(s), s = NULL : 0), \
27 connection_fatal msg )
29 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
30 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
31 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
32 #define SSH1_CMSG_USER 4 /* 0x4 */
33 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
34 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
35 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
36 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
37 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
38 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
39 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
40 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
41 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
42 #define SSH1_SMSG_FAILURE 15 /* 0xf */
43 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
44 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
45 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
46 #define SSH1_CMSG_EOF 19 /* 0x13 */
47 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
48 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
49 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
50 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
51 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
52 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
53 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
54 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
55 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
56 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
57 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
58 #define SSH1_MSG_IGNORE 32 /* 0x20 */
59 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
60 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
61 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
62 #define SSH1_MSG_DEBUG 36 /* 0x24 */
63 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
64 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
65 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
66 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
67 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
68 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
69 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
71 #define SSH1_AUTH_TIS 5 /* 0x5 */
72 #define SSH1_AUTH_CCARD 16 /* 0x10 */
74 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
75 /* Mask for protoflags we will echo back to server if seen */
76 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
78 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
79 #define SSH2_MSG_IGNORE 2 /* 0x2 */
80 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
81 #define SSH2_MSG_DEBUG 4 /* 0x4 */
82 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
83 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
84 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
85 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
86 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
87 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
88 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
89 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
90 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
91 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
92 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
93 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
94 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
95 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
96 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
97 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
98 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
99 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
100 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
101 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
102 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
103 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
104 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
105 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
106 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
107 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
108 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
109 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
110 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
111 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
112 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
113 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
115 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
116 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
117 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
118 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
119 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
120 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
121 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
122 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
123 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
124 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
125 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
126 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
127 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
128 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
129 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
131 static const char *const ssh2_disconnect_reasons
[] = {
133 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
134 "SSH_DISCONNECT_PROTOCOL_ERROR",
135 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
136 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
137 "SSH_DISCONNECT_MAC_ERROR",
138 "SSH_DISCONNECT_COMPRESSION_ERROR",
139 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
140 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
141 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
142 "SSH_DISCONNECT_CONNECTION_LOST",
143 "SSH_DISCONNECT_BY_APPLICATION",
144 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
145 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
146 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
147 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
150 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
151 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
152 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
153 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
155 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
158 * Various remote-bug flags.
160 #define BUG_CHOKES_ON_SSH1_IGNORE 1
161 #define BUG_SSH2_HMAC 2
163 #define GET_32BIT(cp) \
164 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
165 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
166 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
167 ((unsigned long)(unsigned char)(cp)[3]))
169 #define PUT_32BIT(cp, value) { \
170 (cp)[0] = (unsigned char)((value) >> 24); \
171 (cp)[1] = (unsigned char)((value) >> 16); \
172 (cp)[2] = (unsigned char)((value) >> 8); \
173 (cp)[3] = (unsigned char)(value); }
175 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
177 /* Coroutine mechanics for the sillier bits of the code */
178 #define crBegin1 static int crLine = 0;
179 #define crBegin2 switch(crLine) { case 0:;
180 #define crBegin crBegin1; crBegin2;
181 #define crFinish(z) } crLine = 0; return (z)
182 #define crFinishV } crLine = 0; return
183 #define crReturn(z) \
185 crLine=__LINE__; return (z); case __LINE__:;\
189 crLine=__LINE__; return; case __LINE__:;\
191 #define crStop(z) do{ crLine = 0; return (z); }while(0)
192 #define crStopV do{ crLine = 0; return; }while(0)
193 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
194 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
196 extern char *x11_init(Socket
*, char *, void *);
197 extern void x11_close(Socket
);
198 extern int x11_send(Socket
, char *, int);
199 extern void x11_invent_auth(char *, int, char *, int);
200 extern void x11_unthrottle(Socket s
);
201 extern void x11_override_throttle(Socket s
, int enable
);
203 extern char *pfd_newconnect(Socket
* s
, char *hostname
, int port
, void *c
);
204 extern char *pfd_addforward(char *desthost
, int destport
, int port
);
205 extern void pfd_close(Socket s
);
206 extern int pfd_send(Socket s
, char *data
, int len
);
207 extern void pfd_confirm(Socket s
);
208 extern void pfd_unthrottle(Socket s
);
209 extern void pfd_override_throttle(Socket s
, int enable
);
212 * Buffer management constants. There are several of these for
213 * various different purposes:
215 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
216 * on a local data stream before we throttle the whole SSH
217 * connection (in SSH1 only). Throttling the whole connection is
218 * pretty drastic so we set this high in the hope it won't
221 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
222 * on the SSH connection itself before we defensively throttle
223 * _all_ local data streams. This is pretty drastic too (though
224 * thankfully unlikely in SSH2 since the window mechanism should
225 * ensure that the server never has any need to throttle its end
226 * of the connection), so we set this high as well.
228 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
232 #define SSH1_BUFFER_LIMIT 32768
233 #define SSH_MAX_BACKLOG 32768
234 #define OUR_V2_WINSIZE 16384
237 * Ciphers for SSH2. We miss out single-DES because it isn't
238 * supported; also 3DES and Blowfish are both done differently from
239 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
240 * endianness and different-sized keys.)
242 const static struct ssh2_ciphers
*ciphers
[] = {
248 const static struct ssh_kex
*kex_algs
[] = {
249 &ssh_diffiehellman_gex
,
253 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
255 static void nullmac_key(unsigned char *key
)
258 static void nullmac_generate(unsigned char *blk
, int len
,
262 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
)
266 const static struct ssh_mac ssh_mac_none
= {
267 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
269 const static struct ssh_mac
*macs
[] = {
270 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
272 const static struct ssh_mac
*buggymacs
[] = {
273 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
276 static void ssh_comp_none_init(void)
279 static int ssh_comp_none_block(unsigned char *block
, int len
,
280 unsigned char **outblock
, int *outlen
)
284 static int ssh_comp_none_disable(void)
288 const static struct ssh_compress ssh_comp_none
= {
290 ssh_comp_none_init
, ssh_comp_none_block
,
291 ssh_comp_none_init
, ssh_comp_none_block
,
292 ssh_comp_none_disable
294 extern const struct ssh_compress ssh_zlib
;
295 const static struct ssh_compress
*compressions
[] = {
296 &ssh_zlib
, &ssh_comp_none
299 enum { /* channel types */
304 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
308 * 2-3-4 tree storing channels.
311 unsigned remoteid
, localid
;
315 struct ssh1_data_channel
{
318 struct ssh2_data_channel
{
320 unsigned remwindow
, remmaxpkt
;
325 struct ssh_agent_channel
{
326 unsigned char *message
;
327 unsigned char msglen
[4];
328 int lensofar
, totallen
;
330 struct ssh_x11_channel
{
333 struct ssh_pfd_channel
{
340 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
341 * 2 use this structure in different ways, reflecting SSH 2's
342 * altogether saner approach to port forwarding.
344 * In SSH 1, you arrange a remote forwarding by sending the server
345 * the remote port number, and the local destination host:port.
346 * When a connection comes in, the server sends you back that
347 * host:port pair, and you connect to it. This is a ready-made
348 * security hole if you're not on the ball: a malicious server
349 * could send you back _any_ host:port pair, so if you trustingly
350 * connect to the address it gives you then you've just opened the
351 * entire inside of your corporate network just by connecting
352 * through it to a dodgy SSH server. Hence, we must store a list of
353 * host:port pairs we _are_ trying to forward to, and reject a
354 * connection request from the server if it's not in the list.
356 * In SSH 2, each side of the connection minds its own business and
357 * doesn't send unnecessary information to the other. You arrange a
358 * remote forwarding by sending the server just the remote port
359 * number. When a connection comes in, the server tells you which
360 * of its ports was connected to; and _you_ have to remember what
361 * local host:port pair went with that port number.
363 * Hence: in SSH 1 this structure stores host:port pairs we intend
364 * to allow connections to, and is indexed by those host:port
365 * pairs. In SSH 2 it stores a mapping from source port to
366 * destination host:port pair, and is indexed by source port.
368 struct ssh_rportfwd
{
369 unsigned sport
, dport
;
382 static SHA_State exhash
, exhashbase
;
384 static Socket s
= NULL
;
386 static unsigned char session_key
[32];
387 static int ssh1_compressing
;
388 static int ssh1_remote_protoflags
;
389 static int ssh1_local_protoflags
;
390 static int ssh_agentfwd_enabled
;
391 static int ssh_X11_fwd_enabled
;
392 static int ssh_remote_bugs
;
393 static const struct ssh_cipher
*cipher
= NULL
;
394 static const struct ssh2_cipher
*cscipher
= NULL
;
395 static const struct ssh2_cipher
*sccipher
= NULL
;
396 static const struct ssh_mac
*csmac
= NULL
;
397 static const struct ssh_mac
*scmac
= NULL
;
398 static const struct ssh_compress
*cscomp
= NULL
;
399 static const struct ssh_compress
*sccomp
= NULL
;
400 static const struct ssh_kex
*kex
= NULL
;
401 static const struct ssh_signkey
*hostkey
= NULL
;
402 static unsigned char ssh2_session_id
[20];
403 int (*ssh_get_line
) (const char *prompt
, char *str
, int maxlen
,
406 static char *savedhost
;
407 static int savedport
;
408 static int ssh_send_ok
;
409 static int ssh_echoing
, ssh_editing
;
411 static tree234
*ssh_channels
; /* indexed by local id */
412 static struct ssh_channel
*mainchan
; /* primary session channel */
414 static tree234
*ssh_rportfwds
;
418 SSH_STATE_BEFORE_SIZE
,
422 } ssh_state
= SSH_STATE_PREPACKET
;
424 static int size_needed
= FALSE
, eof_needed
= FALSE
;
426 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
427 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
428 static unsigned char *deferred_send_data
= NULL
;
429 static int deferred_len
= 0, deferred_size
= 0;
431 static int ssh_version
;
432 static int ssh1_throttle_count
;
433 static int ssh_overall_bufsize
;
434 static int ssh_throttled_all
;
435 static int ssh1_stdout_throttling
;
436 static void (*ssh_protocol
) (unsigned char *in
, int inlen
, int ispkt
);
437 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
438 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
439 static void ssh_size(void);
440 static void ssh_special(Telnet_Special
);
441 static int ssh2_try_send(struct ssh_channel
*c
);
442 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
444 static void ssh_throttle_all(int enable
, int bufsize
);
445 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
446 static int (*s_rdpkt
) (unsigned char **data
, int *datalen
);
447 static int ssh_sendbuffer(void);
449 static struct rdpkt1_state_tag
{
450 long len
, pad
, biglen
, to_read
;
451 unsigned long realcrc
, gotcrc
;
457 static struct rdpkt2_state_tag
{
458 long len
, pad
, payload
, packetlen
, maclen
;
461 unsigned long incoming_sequence
;
464 static int ssh_channelcmp(void *av
, void *bv
)
466 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
467 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
468 if (a
->localid
< b
->localid
)
470 if (a
->localid
> b
->localid
)
474 static int ssh_channelfind(void *av
, void *bv
)
476 unsigned *a
= (unsigned *) av
;
477 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
485 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
487 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
488 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
490 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
491 return i
< 0 ?
-1 : +1;
492 if (a
->dport
> b
->dport
)
494 if (a
->dport
< b
->dport
)
499 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
501 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
502 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
504 if (a
->sport
> b
->sport
)
506 if (a
->sport
< b
->sport
)
511 static int alloc_channel_id(void)
513 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
514 unsigned low
, high
, mid
;
516 struct ssh_channel
*c
;
519 * First-fit allocation of channel numbers: always pick the
520 * lowest unused one. To do this, binary-search using the
521 * counted B-tree to find the largest channel ID which is in a
522 * contiguous sequence from the beginning. (Precisely
523 * everything in that sequence must have ID equal to its tree
524 * index plus CHANNEL_NUMBER_OFFSET.)
526 tsize
= count234(ssh_channels
);
530 while (high
- low
> 1) {
531 mid
= (high
+ low
) / 2;
532 c
= index234(ssh_channels
, mid
);
533 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
534 low
= mid
; /* this one is fine */
536 high
= mid
; /* this one is past it */
539 * Now low points to either -1, or the tree index of the
540 * largest ID in the initial sequence.
543 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
544 assert(NULL
== find234(ssh_channels
, &i
, ssh_channelfind
));
546 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
549 static void c_write(char *buf
, int len
)
551 if ((flags
& FLAG_STDERR
)) {
553 for (i
= 0; i
< len
; i
++)
555 fputc(buf
[i
], stderr
);
558 from_backend(1, buf
, len
);
561 static void c_write_untrusted(char *buf
, int len
)
564 for (i
= 0; i
< len
; i
++) {
567 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
572 static void c_write_str(char *buf
)
574 c_write(buf
, strlen(buf
));
578 * Collect incoming data in the incoming packet buffer.
579 * Decipher and verify the packet when it is completely read.
580 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
581 * Update the *data and *datalen variables.
582 * Return the additional nr of bytes needed, or 0 when
583 * a complete packet is available.
585 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
587 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
596 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
597 while ((*datalen
) == 0)
599 st
->len
= (st
->len
<< 8) + **data
;
600 (*data
)++, (*datalen
)--;
604 if (st
->len
== 0x52656d6f) { /* "Remo"te server has closed ... */
605 st
->len
= 0x300; /* big enough to carry to end */
609 st
->pad
= 8 - (st
->len
% 8);
610 st
->biglen
= st
->len
+ st
->pad
;
611 pktin
.length
= st
->len
- 5;
613 if (pktin
.maxlen
< st
->biglen
) {
614 pktin
.maxlen
= st
->biglen
;
615 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+ APIEXTRA
) :
616 srealloc(pktin
.data
, st
->biglen
+ APIEXTRA
));
618 fatalbox("Out of memory");
621 st
->to_read
= st
->biglen
;
623 while (st
->to_read
> 0) {
624 st
->chunk
= st
->to_read
;
625 while ((*datalen
) == 0)
626 crReturn(st
->to_read
);
627 if (st
->chunk
> (*datalen
))
628 st
->chunk
= (*datalen
);
629 memcpy(st
->p
, *data
, st
->chunk
);
631 *datalen
-= st
->chunk
;
633 st
->to_read
-= st
->chunk
;
637 cipher
->decrypt(pktin
.data
, st
->biglen
);
639 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
640 dmemdump(pktin
.data
, st
->biglen
);
643 st
->realcrc
= crc32(pktin
.data
, st
->biglen
- 4);
644 st
->gotcrc
= GET_32BIT(pktin
.data
+ st
->biglen
- 4);
645 if (st
->gotcrc
!= st
->realcrc
) {
646 bombout(("Incorrect CRC received on packet"));
650 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
652 if (ssh1_compressing
) {
653 unsigned char *decompblk
;
656 debug(("Packet payload pre-decompression:\n"));
657 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
659 zlib_decompress_block(pktin
.body
- 1, pktin
.length
+ 1,
660 &decompblk
, &decomplen
);
662 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
663 pktin
.maxlen
= st
->pad
+ decomplen
;
664 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+ APIEXTRA
);
665 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
667 fatalbox("Out of memory");
670 memcpy(pktin
.body
- 1, decompblk
, decomplen
);
672 pktin
.length
= decomplen
- 1;
674 debug(("Packet payload post-decompression:\n"));
675 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
679 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
680 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
681 pktin
.type
== SSH1_MSG_DEBUG
||
682 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
683 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
684 long strlen
= GET_32BIT(pktin
.body
);
685 if (strlen
+ 4 != pktin
.length
) {
686 bombout(("Received data packet with bogus string length"));
691 pktin
.type
= pktin
.body
[-1];
693 if (pktin
.type
== SSH1_MSG_DEBUG
) {
694 /* log debug message */
696 int strlen
= GET_32BIT(pktin
.body
);
697 strcpy(buf
, "Remote: ");
700 memcpy(buf
+ 8, pktin
.body
+ 4, strlen
);
701 buf
[8 + strlen
] = '\0';
704 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
709 if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
710 /* log reason code in disconnect message */
712 unsigned msglen
= GET_32BIT(pktin
.body
);
714 strcpy(buf
, "Remote sent disconnect: ");
715 nowlen
= strlen(buf
);
716 if (msglen
> sizeof(buf
) - nowlen
- 1)
717 msglen
= sizeof(buf
) - nowlen
- 1;
718 memcpy(buf
+ nowlen
, pktin
.body
+ 4, msglen
);
719 buf
[nowlen
+ msglen
] = '\0';
726 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
728 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
736 st
->cipherblk
= sccipher
->blksize
;
739 if (st
->cipherblk
< 8)
742 if (pktin
.maxlen
< st
->cipherblk
) {
743 pktin
.maxlen
= st
->cipherblk
;
746 NULL ?
smalloc(st
->cipherblk
+
747 APIEXTRA
) : srealloc(pktin
.data
,
751 fatalbox("Out of memory");
755 * Acquire and decrypt the first block of the packet. This will
756 * contain the length and padding details.
758 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
759 while ((*datalen
) == 0)
760 crReturn(st
->cipherblk
- st
->i
);
761 pktin
.data
[st
->i
] = *(*data
)++;
765 if (!memcmp(pktin
.data
, "Remo", 4)) { /* "Remo"te server has closed ... */
770 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
773 * Now get the length and padding figures.
775 st
->len
= GET_32BIT(pktin
.data
);
776 st
->pad
= pktin
.data
[4];
779 * This enables us to deduce the payload length.
781 st
->payload
= st
->len
- st
->pad
- 1;
783 pktin
.length
= st
->payload
+ 5;
786 * So now we can work out the total packet length.
788 st
->packetlen
= st
->len
+ 4;
789 st
->maclen
= scmac ? scmac
->len
: 0;
792 * Adjust memory allocation if packet is too big.
794 if (pktin
.maxlen
< st
->packetlen
+ st
->maclen
) {
795 pktin
.maxlen
= st
->packetlen
+ st
->maclen
;
798 NULL ?
smalloc(pktin
.maxlen
+ APIEXTRA
) : srealloc(pktin
.data
,
803 fatalbox("Out of memory");
807 * Read and decrypt the remainder of the packet.
809 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
811 while ((*datalen
) == 0)
812 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
813 pktin
.data
[st
->i
] = *(*data
)++;
816 /* Decrypt everything _except_ the MAC. */
818 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
819 st
->packetlen
- st
->cipherblk
);
822 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
823 dmemdump(pktin
.data
, st
->packetlen
);
830 && !scmac
->verify(pktin
.data
, st
->len
+ 4,
831 st
->incoming_sequence
)) {
832 bombout(("Incorrect MAC received on packet"));
835 st
->incoming_sequence
++; /* whether or not we MACed */
838 * Decompress packet payload.
841 unsigned char *newpayload
;
843 if (sccomp
&& sccomp
->decompress(pktin
.data
+ 5, pktin
.length
- 5,
844 &newpayload
, &newlen
)) {
845 if (pktin
.maxlen
< newlen
+ 5) {
846 pktin
.maxlen
= newlen
+ 5;
849 NULL ?
smalloc(pktin
.maxlen
+
850 APIEXTRA
) : srealloc(pktin
.data
,
854 fatalbox("Out of memory");
856 pktin
.length
= 5 + newlen
;
857 memcpy(pktin
.data
+ 5, newpayload
, newlen
);
859 debug(("Post-decompression payload:\n"));
860 dmemdump(pktin
.data
+ 5, newlen
);
868 pktin
.type
= pktin
.data
[5];
870 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
871 goto next_packet
; /* FIXME: print DEBUG message */
873 if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
874 /* log reason code in disconnect message */
876 int reason
= GET_32BIT(pktin
.data
+ 6);
877 unsigned msglen
= GET_32BIT(pktin
.data
+ 10);
879 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
880 sprintf(buf
, "Received disconnect message (%s)",
881 ssh2_disconnect_reasons
[reason
]);
883 sprintf(buf
, "Received disconnect message (unknown type %d)",
887 strcpy(buf
, "Disconnection message text: ");
888 nowlen
= strlen(buf
);
889 if (msglen
> sizeof(buf
) - nowlen
- 1)
890 msglen
= sizeof(buf
) - nowlen
- 1;
891 memcpy(buf
+ nowlen
, pktin
.data
+ 14, msglen
);
892 buf
[nowlen
+ msglen
] = '\0';
899 static void ssh1_pktout_size(int len
)
903 len
+= 5; /* type and CRC */
907 pktout
.length
= len
- 5;
908 if (pktout
.maxlen
< biglen
) {
909 pktout
.maxlen
= biglen
;
911 /* Allocate enough buffer space for extra block
912 * for MS CryptEncrypt() */
913 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 12) :
914 srealloc(pktout
.data
, biglen
+ 12));
916 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 4) :
917 srealloc(pktout
.data
, biglen
+ 4));
920 fatalbox("Out of memory");
922 pktout
.body
= pktout
.data
+ 4 + pad
+ 1;
925 static void s_wrpkt_start(int type
, int len
)
927 ssh1_pktout_size(len
);
931 static int s_wrpkt_prepare(void)
933 int pad
, len
, biglen
, i
;
936 pktout
.body
[-1] = pktout
.type
;
939 debug(("Packet payload pre-compression:\n"));
940 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
943 if (ssh1_compressing
) {
944 unsigned char *compblk
;
946 zlib_compress_block(pktout
.body
- 1, pktout
.length
+ 1,
948 ssh1_pktout_size(complen
- 1);
949 memcpy(pktout
.body
- 1, compblk
, complen
);
952 debug(("Packet payload post-compression:\n"));
953 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
957 len
= pktout
.length
+ 5; /* type and CRC */
961 for (i
= 0; i
< pad
; i
++)
962 pktout
.data
[i
+ 4] = random_byte();
963 crc
= crc32(pktout
.data
+ 4, biglen
- 4);
964 PUT_32BIT(pktout
.data
+ biglen
, crc
);
965 PUT_32BIT(pktout
.data
, len
);
968 debug(("Sending packet len=%d\n", biglen
+ 4));
969 dmemdump(pktout
.data
, biglen
+ 4);
972 cipher
->encrypt(pktout
.data
+ 4, biglen
);
977 static void s_wrpkt(void)
980 len
= s_wrpkt_prepare();
981 backlog
= sk_write(s
, pktout
.data
, len
);
982 if (backlog
> SSH_MAX_BACKLOG
)
983 ssh_throttle_all(1, backlog
);
986 static void s_wrpkt_defer(void)
989 len
= s_wrpkt_prepare();
990 if (deferred_len
+ len
> deferred_size
) {
991 deferred_size
= deferred_len
+ len
+ 128;
992 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
994 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
999 * Construct a packet with the specified contents.
1001 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
1003 unsigned char *p
, *argp
, argchar
;
1004 unsigned long argint
;
1005 int pktlen
, argtype
, arglen
;
1009 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1012 (void) va_arg(ap1
, int);
1016 (void) va_arg(ap1
, char);
1020 (void) va_arg(ap1
, unsigned char *);
1021 arglen
= va_arg(ap1
, int);
1025 argp
= va_arg(ap1
, unsigned char *);
1026 arglen
= strlen(argp
);
1027 pktlen
+= 4 + arglen
;
1030 bn
= va_arg(ap1
, Bignum
);
1031 pktlen
+= ssh1_bignum_length(bn
);
1038 s_wrpkt_start(pkttype
, pktlen
);
1041 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1044 argint
= va_arg(ap2
, int);
1045 PUT_32BIT(p
, argint
);
1049 argchar
= va_arg(ap2
, unsigned char);
1054 argp
= va_arg(ap2
, unsigned char *);
1055 arglen
= va_arg(ap2
, int);
1056 memcpy(p
, argp
, arglen
);
1060 argp
= va_arg(ap2
, unsigned char *);
1061 arglen
= strlen(argp
);
1062 PUT_32BIT(p
, arglen
);
1063 memcpy(p
+ 4, argp
, arglen
);
1067 bn
= va_arg(ap2
, Bignum
);
1068 p
+= ssh1_write_bignum(p
, bn
);
1074 static void send_packet(int pkttype
, ...)
1077 va_start(ap1
, pkttype
);
1078 va_start(ap2
, pkttype
);
1079 construct_packet(pkttype
, ap1
, ap2
);
1083 static void defer_packet(int pkttype
, ...)
1086 va_start(ap1
, pkttype
);
1087 va_start(ap2
, pkttype
);
1088 construct_packet(pkttype
, ap1
, ap2
);
1092 static int ssh_versioncmp(char *a
, char *b
)
1095 unsigned long av
, bv
;
1097 av
= strtoul(a
, &ae
, 10);
1098 bv
= strtoul(b
, &be
, 10);
1100 return (av
< bv ?
-1 : +1);
1105 av
= strtoul(ae
, &ae
, 10);
1106 bv
= strtoul(be
, &be
, 10);
1108 return (av
< bv ?
-1 : +1);
1114 * Utility routines for putting an SSH-protocol `string' and
1115 * `uint32' into a SHA state.
1118 static void sha_string(SHA_State
* s
, void *str
, int len
)
1120 unsigned char lenblk
[4];
1121 PUT_32BIT(lenblk
, len
);
1122 SHA_Bytes(s
, lenblk
, 4);
1123 SHA_Bytes(s
, str
, len
);
1126 static void sha_uint32(SHA_State
* s
, unsigned i
)
1128 unsigned char intblk
[4];
1129 PUT_32BIT(intblk
, i
);
1130 SHA_Bytes(s
, intblk
, 4);
1134 * SSH2 packet construction functions.
1136 static void ssh2_pkt_ensure(int length
)
1138 if (pktout
.maxlen
< length
) {
1139 pktout
.maxlen
= length
+ 256;
1142 NULL ?
smalloc(pktout
.maxlen
+
1143 APIEXTRA
) : srealloc(pktout
.data
,
1147 fatalbox("Out of memory");
1150 static void ssh2_pkt_adddata(void *data
, int len
)
1152 pktout
.length
+= len
;
1153 ssh2_pkt_ensure(pktout
.length
);
1154 memcpy(pktout
.data
+ pktout
.length
- len
, data
, len
);
1156 static void ssh2_pkt_addbyte(unsigned char byte
)
1158 ssh2_pkt_adddata(&byte
, 1);
1160 static void ssh2_pkt_init(int pkt_type
)
1163 ssh2_pkt_addbyte((unsigned char) pkt_type
);
1165 static void ssh2_pkt_addbool(unsigned char value
)
1167 ssh2_pkt_adddata(&value
, 1);
1169 static void ssh2_pkt_adduint32(unsigned long value
)
1172 PUT_32BIT(x
, value
);
1173 ssh2_pkt_adddata(x
, 4);
1175 static void ssh2_pkt_addstring_start(void)
1177 ssh2_pkt_adduint32(0);
1178 pktout
.savedpos
= pktout
.length
;
1180 static void ssh2_pkt_addstring_str(char *data
)
1182 ssh2_pkt_adddata(data
, strlen(data
));
1183 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1184 pktout
.length
- pktout
.savedpos
);
1186 static void ssh2_pkt_addstring_data(char *data
, int len
)
1188 ssh2_pkt_adddata(data
, len
);
1189 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1190 pktout
.length
- pktout
.savedpos
);
1192 static void ssh2_pkt_addstring(char *data
)
1194 ssh2_pkt_addstring_start();
1195 ssh2_pkt_addstring_str(data
);
1197 static char *ssh2_mpint_fmt(Bignum b
, int *len
)
1200 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1203 fatalbox("out of memory");
1205 for (i
= 1; i
<= n
; i
++)
1206 p
[i
] = bignum_byte(b
, n
- i
);
1208 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1210 memmove(p
, p
+ i
, n
+ 1 - i
);
1214 static void ssh2_pkt_addmp(Bignum b
)
1218 p
= ssh2_mpint_fmt(b
, &len
);
1219 ssh2_pkt_addstring_start();
1220 ssh2_pkt_addstring_data(p
, len
);
1225 * Construct an SSH2 final-form packet: compress it, encrypt it,
1226 * put the MAC on it. Final packet, ready to be sent, is stored in
1227 * pktout.data. Total length is returned.
1229 static int ssh2_pkt_construct(void)
1231 int cipherblk
, maclen
, padding
, i
;
1232 static unsigned long outgoing_sequence
= 0;
1235 * Compress packet payload.
1238 debug(("Pre-compression payload:\n"));
1239 dmemdump(pktout
.data
+ 5, pktout
.length
- 5);
1242 unsigned char *newpayload
;
1244 if (cscomp
&& cscomp
->compress(pktout
.data
+ 5, pktout
.length
- 5,
1245 &newpayload
, &newlen
)) {
1247 ssh2_pkt_adddata(newpayload
, newlen
);
1253 * Add padding. At least four bytes, and must also bring total
1254 * length (minus MAC) up to a multiple of the block size.
1256 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1257 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1260 (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1261 maclen
= csmac ? csmac
->len
: 0;
1262 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1263 pktout
.data
[4] = padding
;
1264 for (i
= 0; i
< padding
; i
++)
1265 pktout
.data
[pktout
.length
+ i
] = random_byte();
1266 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1268 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1270 outgoing_sequence
++; /* whether or not we MACed */
1273 debug(("Sending packet len=%d\n", pktout
.length
+ padding
));
1274 dmemdump(pktout
.data
, pktout
.length
+ padding
);
1278 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1280 /* Ready-to-send packet starts at pktout.data. We return length. */
1281 return pktout
.length
+ padding
+ maclen
;
1285 * Construct and send an SSH2 packet immediately.
1287 static void ssh2_pkt_send(void)
1291 len
= ssh2_pkt_construct();
1292 backlog
= sk_write(s
, pktout
.data
, len
);
1293 if (backlog
> SSH_MAX_BACKLOG
)
1294 ssh_throttle_all(1, backlog
);
1298 * Construct an SSH2 packet and add it to a deferred data block.
1299 * Useful for sending multiple packets in a single sk_write() call,
1300 * to prevent a traffic-analysing listener from being able to work
1301 * out the length of any particular packet (such as the password
1304 * Note that because SSH2 sequence-numbers its packets, this can
1305 * NOT be used as an m4-style `defer' allowing packets to be
1306 * constructed in one order and sent in another.
1308 static void ssh2_pkt_defer(void)
1310 int len
= ssh2_pkt_construct();
1311 if (deferred_len
+ len
> deferred_size
) {
1312 deferred_size
= deferred_len
+ len
+ 128;
1313 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1315 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1316 deferred_len
+= len
;
1320 * Send the whole deferred data block constructed by
1321 * ssh2_pkt_defer() or SSH1's defer_packet().
1323 static void ssh_pkt_defersend(void)
1326 backlog
= sk_write(s
, deferred_send_data
, deferred_len
);
1327 deferred_len
= deferred_size
= 0;
1328 sfree(deferred_send_data
);
1329 deferred_send_data
= NULL
;
1330 if (backlog
> SSH_MAX_BACKLOG
)
1331 ssh_throttle_all(1, backlog
);
1335 void bndebug(char *string
, Bignum b
)
1339 p
= ssh2_mpint_fmt(b
, &len
);
1340 debug(("%s", string
));
1341 for (i
= 0; i
< len
; i
++)
1342 debug((" %02x", p
[i
]));
1348 static void sha_mpint(SHA_State
* s
, Bignum b
)
1352 p
= ssh2_mpint_fmt(b
, &len
);
1353 sha_string(s
, p
, len
);
1358 * SSH2 packet decode functions.
1360 static unsigned long ssh2_pkt_getuint32(void)
1362 unsigned long value
;
1363 if (pktin
.length
- pktin
.savedpos
< 4)
1364 return 0; /* arrgh, no way to decline (FIXME?) */
1365 value
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1366 pktin
.savedpos
+= 4;
1369 static int ssh2_pkt_getbool(void)
1371 unsigned long value
;
1372 if (pktin
.length
- pktin
.savedpos
< 1)
1373 return 0; /* arrgh, no way to decline (FIXME?) */
1374 value
= pktin
.data
[pktin
.savedpos
] != 0;
1378 static void ssh2_pkt_getstring(char **p
, int *length
)
1381 if (pktin
.length
- pktin
.savedpos
< 4)
1383 *length
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1384 pktin
.savedpos
+= 4;
1385 if (pktin
.length
- pktin
.savedpos
< *length
)
1387 *p
= pktin
.data
+ pktin
.savedpos
;
1388 pktin
.savedpos
+= *length
;
1390 static Bignum
ssh2_pkt_getmp(void)
1396 ssh2_pkt_getstring(&p
, &length
);
1400 bombout(("internal error: Can't handle negative mpints"));
1403 b
= bignum_from_bytes(p
, length
);
1408 * Examine the remote side's version string and compare it against
1409 * a list of known buggy implementations.
1411 static void ssh_detect_bugs(char *vstring
)
1413 char *imp
; /* pointer to implementation part */
1415 imp
+= strcspn(imp
, "-");
1418 imp
+= strcspn(imp
, "-");
1422 ssh_remote_bugs
= 0;
1424 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1425 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1426 !strcmp(imp
, "1.2.22")) {
1428 * These versions don't support SSH1_MSG_IGNORE, so we have
1429 * to use a different defence against password length
1432 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1433 logevent("We believe remote version has SSH1 ignore bug");
1436 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1437 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1438 !strncmp(imp
, "2.1 ", 4)) {
1440 * These versions have the HMAC bug.
1442 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1443 logevent("We believe remote version has SSH2 HMAC bug");
1447 static int do_ssh_init(unsigned char c
)
1450 static char version
[10];
1451 static char *vstring
;
1452 static int vstrsize
;
1458 /* Search for the string "SSH-" in the input. */
1461 static const int transS
[] = { 1, 2, 2, 1 };
1462 static const int transH
[] = { 0, 0, 3, 0 };
1463 static const int transminus
[] = { 0, 0, 0, -1 };
1474 crReturn(1); /* get another character */
1477 vstring
= smalloc(16);
1479 strcpy(vstring
, "SSH-");
1483 crReturn(1); /* get another char */
1484 if (vslen
>= vstrsize
- 1) {
1486 vstring
= srealloc(vstring
, vstrsize
);
1488 vstring
[vslen
++] = c
;
1493 } else if (i
< sizeof(version
) - 1)
1495 } else if (c
== '\n')
1499 ssh_agentfwd_enabled
= FALSE
;
1500 rdpkt2_state
.incoming_sequence
= 0;
1503 vlog
= smalloc(20 + vslen
);
1504 sprintf(vlog
, "Server version: %s", vstring
);
1505 ssh_detect_bugs(vstring
);
1506 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1511 * Server version "1.99" means we can choose whether we use v1
1512 * or v2 protocol. Choice is based on cfg.sshprot.
1514 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1516 * This is a v2 server. Begin v2 protocol.
1518 char verstring
[80], vlog
[100];
1519 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1520 SHA_Init(&exhashbase
);
1522 * Hash our version string and their version string.
1524 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1525 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1526 sprintf(vlog
, "We claim version: %s", verstring
);
1528 strcat(verstring
, "\n");
1529 logevent("Using SSH protocol version 2");
1530 sk_write(s
, verstring
, strlen(verstring
));
1531 ssh_protocol
= ssh2_protocol
;
1533 s_rdpkt
= ssh2_rdpkt
;
1536 * This is a v1 server. Begin v1 protocol.
1538 char verstring
[80], vlog
[100];
1539 sprintf(verstring
, "SSH-%s-%s",
1540 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1542 sprintf(vlog
, "We claim version: %s", verstring
);
1544 strcat(verstring
, "\n");
1545 logevent("Using SSH protocol version 1");
1546 sk_write(s
, verstring
, strlen(verstring
));
1547 ssh_protocol
= ssh1_protocol
;
1549 s_rdpkt
= ssh1_rdpkt
;
1551 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1558 static void ssh_gotdata(unsigned char *data
, int datalen
)
1563 * To begin with, feed the characters one by one to the
1564 * protocol initialisation / selection function do_ssh_init().
1565 * When that returns 0, we're done with the initial greeting
1566 * exchange and can move on to packet discipline.
1571 crReturnV
; /* more data please */
1572 ret
= do_ssh_init(*data
);
1580 * We emerge from that loop when the initial negotiation is
1581 * over and we have selected an s_rdpkt function. Now pass
1582 * everything to s_rdpkt, and then pass the resulting packets
1583 * to the proper protocol handler.
1588 while (datalen
> 0) {
1589 if (s_rdpkt(&data
, &datalen
) == 0) {
1590 ssh_protocol(NULL
, 0, 1);
1591 if (ssh_state
== SSH_STATE_CLOSED
) {
1601 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
1604 ssh_state
= SSH_STATE_CLOSED
;
1610 /* A socket error has occurred. */
1611 connection_fatal(error_msg
);
1613 /* Otherwise, the remote side closed the connection normally. */
1618 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
1620 ssh_gotdata(data
, len
);
1621 if (ssh_state
== SSH_STATE_CLOSED
) {
1631 static void ssh_sent(Plug plug
, int bufsize
)
1634 * If the send backlog on the SSH socket itself clears, we
1635 * should unthrottle the whole world if it was throttled.
1637 if (bufsize
< SSH_MAX_BACKLOG
)
1638 ssh_throttle_all(0, bufsize
);
1642 * Connect to specified host and port.
1643 * Returns an error message, or NULL on success.
1644 * Also places the canonical host name into `realhost'. It must be
1645 * freed by the caller.
1647 static char *connect_to_host(char *host
, int port
, char **realhost
)
1649 static struct plug_function_table fn_table
= {
1654 }, *fn_table_ptr
= &fn_table
;
1663 savedhost
= smalloc(1 + strlen(host
));
1665 fatalbox("Out of memory");
1666 strcpy(savedhost
, host
);
1669 port
= 22; /* default ssh port */
1682 addr
= sk_namelookup(host
, realhost
);
1683 if ((err
= sk_addr_error(addr
)))
1687 *realhost
= strdup(FWhost
);
1693 s
= sk_new(addr
, port
, 0, 1, &fn_table_ptr
);
1694 if ((err
= sk_socket_error(s
)))
1698 sk_write(s
, "connect ", 8);
1699 sk_write(s
, FWhost
, strlen(FWhost
));
1702 sprintf(buf
, " %d\n", FWport
);
1703 sk_write(s
, buf
, strlen(buf
));
1711 * Throttle or unthrottle the SSH connection.
1713 static void ssh1_throttle(int adjust
)
1715 int old_count
= ssh1_throttle_count
;
1716 ssh1_throttle_count
+= adjust
;
1717 assert(ssh1_throttle_count
>= 0);
1718 if (ssh1_throttle_count
&& !old_count
) {
1719 sk_set_frozen(s
, 1);
1720 } else if (!ssh1_throttle_count
&& old_count
) {
1721 sk_set_frozen(s
, 0);
1726 * Throttle or unthrottle _all_ local data streams (for when sends
1727 * on the SSH connection itself back up).
1729 static void ssh_throttle_all(int enable
, int bufsize
)
1732 struct ssh_channel
*c
;
1734 if (enable
== ssh_throttled_all
)
1736 ssh_throttled_all
= enable
;
1737 ssh_overall_bufsize
= bufsize
;
1740 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
1742 case CHAN_MAINSESSION
:
1744 * This is treated separately, outside the switch.
1748 x11_override_throttle(c
->u
.x11
.s
, enable
);
1751 /* Agent channels require no buffer management. */
1754 pfd_override_throttle(c
->u
.x11
.s
, enable
);
1761 * Handle the key exchange and user authentication phases.
1763 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1767 static unsigned char *rsabuf
, *keystr1
, *keystr2
;
1768 unsigned char cookie
[8];
1769 struct RSAKey servkey
, hostkey
;
1770 struct MD5Context md5c
;
1771 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1772 static int tried_publickey
;
1773 static unsigned char session_id
[16];
1774 static int cipher_type
;
1775 static char username
[100];
1782 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1783 bombout(("Public key packet not received"));
1787 logevent("Received public keys");
1789 memcpy(cookie
, pktin
.body
, 8);
1791 i
= makekey(pktin
.body
+ 8, &servkey
, &keystr1
, 0);
1792 j
= makekey(pktin
.body
+ 8 + i
, &hostkey
, &keystr2
, 0);
1795 * Log the host key fingerprint.
1799 logevent("Host key fingerprint is:");
1800 strcpy(logmsg
, " ");
1801 hostkey
.comment
= NULL
;
1802 rsa_fingerprint(logmsg
+ strlen(logmsg
),
1803 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
1807 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+ 8 + i
+ j
);
1808 supported_ciphers_mask
= GET_32BIT(pktin
.body
+ 12 + i
+ j
);
1809 supported_auths_mask
= GET_32BIT(pktin
.body
+ 16 + i
+ j
);
1811 ssh1_local_protoflags
=
1812 ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
1813 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
1816 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1817 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1818 MD5Update(&md5c
, pktin
.body
, 8);
1819 MD5Final(session_id
, &md5c
);
1821 for (i
= 0; i
< 32; i
++)
1822 session_key
[i
] = random_byte();
1824 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1826 rsabuf
= smalloc(len
);
1828 fatalbox("Out of memory");
1831 * Verify the host key.
1835 * First format the key into a string.
1837 int len
= rsastr_len(&hostkey
);
1838 char fingerprint
[100];
1839 char *keystr
= smalloc(len
);
1841 fatalbox("Out of memory");
1842 rsastr_fmt(keystr
, &hostkey
);
1843 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1844 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
,
1849 for (i
= 0; i
< 32; i
++) {
1850 rsabuf
[i
] = session_key
[i
];
1852 rsabuf
[i
] ^= session_id
[i
];
1855 if (hostkey
.bytes
> servkey
.bytes
) {
1856 rsaencrypt(rsabuf
, 32, &servkey
);
1857 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1859 rsaencrypt(rsabuf
, 32, &hostkey
);
1860 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1863 logevent("Encrypted session key");
1866 int cipher_chosen
= 0, warn
= 0;
1867 char *cipher_string
= NULL
;
1868 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
1869 int next_cipher
= cfg
.ssh_cipherlist
[i
];
1870 if (next_cipher
== CIPHER_WARN
) {
1871 /* If/when we choose a cipher, warn about it */
1873 } else if (next_cipher
== CIPHER_AES
) {
1874 /* XXX Probably don't need to mention this. */
1875 logevent("AES not supported in SSH1, skipping");
1877 switch (next_cipher
) {
1878 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
;
1879 cipher_string
= "3DES"; break;
1880 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
;
1881 cipher_string
= "Blowfish"; break;
1882 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
;
1883 cipher_string
= "single-DES"; break;
1885 if (supported_ciphers_mask
& (1 << cipher_type
))
1889 if (!cipher_chosen
) {
1890 if ((supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
1891 bombout(("Server violates SSH 1 protocol by not "
1892 "supporting 3DES encryption"));
1894 /* shouldn't happen */
1895 bombout(("No supported ciphers found"));
1899 /* Warn about chosen cipher if necessary. */
1901 askcipher(cipher_string
, 0);
1904 switch (cipher_type
) {
1905 case SSH_CIPHER_3DES
:
1906 logevent("Using 3DES encryption");
1908 case SSH_CIPHER_DES
:
1909 logevent("Using single-DES encryption");
1911 case SSH_CIPHER_BLOWFISH
:
1912 logevent("Using Blowfish encryption");
1916 send_packet(SSH1_CMSG_SESSION_KEY
,
1917 PKT_CHAR
, cipher_type
,
1918 PKT_DATA
, cookie
, 8,
1919 PKT_CHAR
, (len
* 8) >> 8, PKT_CHAR
, (len
* 8) & 0xFF,
1920 PKT_DATA
, rsabuf
, len
,
1921 PKT_INT
, ssh1_local_protoflags
, PKT_END
);
1923 logevent("Trying to enable encryption...");
1927 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1928 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
: &ssh_3des
;
1929 cipher
->sesskey(session_key
);
1933 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1934 bombout(("Encryption not successfully enabled"));
1938 logevent("Successfully started encryption");
1944 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1946 if (!ssh_get_line("login as: ",
1947 username
, sizeof(username
), FALSE
)) {
1949 * get_line failed to get a username.
1952 logevent("No username provided. Abandoning session.");
1953 ssh_state
= SSH_STATE_CLOSED
;
1957 c_write_str("login as: ");
1960 crWaitUntil(!ispkt
);
1962 switch (c
= *in
++) {
1971 c_write_str("\b \b");
1978 c_write_str("\b \b");
1988 if (((c
>= ' ' && c
<= '~') ||
1989 ((unsigned char) c
>= 160))
1990 && pos
< sizeof(username
)-1) {
1991 username
[pos
++] = c
;
1997 c_write_str("\r\n");
1998 username
[strcspn(username
, "\n\r")] = '\0';
2001 strncpy(username
, cfg
.username
, 99);
2002 username
[99] = '\0';
2005 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
2007 char userlog
[22 + sizeof(username
)];
2008 sprintf(userlog
, "Sent username \"%s\"", username
);
2010 if (flags
& FLAG_INTERACTIVE
&&
2011 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
2012 strcat(userlog
, "\r\n");
2013 c_write_str(userlog
);
2020 tried_publickey
= 0;
2022 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
2023 static char password
[100];
2024 static char prompt
[200];
2027 static int pwpkt_type
;
2029 * Show password prompt, having first obtained it via a TIS
2030 * or CryptoCard exchange if we're doing TIS or CryptoCard
2033 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2034 if (agent_exists()) {
2036 * Attempt RSA authentication using Pageant.
2038 static unsigned char request
[5], *response
, *p
;
2039 static int responselen
;
2040 static int i
, nkeys
;
2041 static int authed
= FALSE
;
2044 logevent("Pageant is running. Requesting keys.");
2046 /* Request the keys held by the agent. */
2047 PUT_32BIT(request
, 1);
2048 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2049 agent_query(request
, 5, &r
, &responselen
);
2050 response
= (unsigned char *) r
;
2051 if (response
&& responselen
>= 5 &&
2052 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2054 nkeys
= GET_32BIT(p
);
2058 sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
2061 for (i
= 0; i
< nkeys
; i
++) {
2062 static struct RSAKey key
;
2063 static Bignum challenge
;
2064 static char *commentp
;
2065 static int commentlen
;
2069 sprintf(buf
, "Trying Pageant key #%d", i
);
2073 p
+= ssh1_read_bignum(p
, &key
.exponent
);
2074 p
+= ssh1_read_bignum(p
, &key
.modulus
);
2075 commentlen
= GET_32BIT(p
);
2079 send_packet(SSH1_CMSG_AUTH_RSA
,
2080 PKT_BIGNUM
, key
.modulus
, PKT_END
);
2082 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2083 logevent("Key refused");
2086 logevent("Received RSA challenge");
2087 ssh1_read_bignum(pktin
.body
, &challenge
);
2089 char *agentreq
, *q
, *ret
;
2092 len
= 1 + 4; /* message type, bit count */
2093 len
+= ssh1_bignum_length(key
.exponent
);
2094 len
+= ssh1_bignum_length(key
.modulus
);
2095 len
+= ssh1_bignum_length(challenge
);
2096 len
+= 16; /* session id */
2097 len
+= 4; /* response format */
2098 agentreq
= smalloc(4 + len
);
2099 PUT_32BIT(agentreq
, len
);
2101 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
2102 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
2104 q
+= ssh1_write_bignum(q
, key
.exponent
);
2105 q
+= ssh1_write_bignum(q
, key
.modulus
);
2106 q
+= ssh1_write_bignum(q
, challenge
);
2107 memcpy(q
, session_id
, 16);
2109 PUT_32BIT(q
, 1); /* response format */
2110 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
2114 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
2115 logevent("Sending Pageant's response");
2116 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2117 PKT_DATA
, ret
+ 5, 16,
2121 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2123 ("Pageant's response accepted");
2124 if (flags
& FLAG_VERBOSE
) {
2126 ("Authenticated using RSA key \"");
2127 c_write(commentp
, commentlen
);
2128 c_write_str("\" from agent\r\n");
2133 ("Pageant's response not accepted");
2136 ("Pageant failed to answer challenge");
2140 logevent("No reply received from Pageant");
2143 freebn(key
.exponent
);
2144 freebn(key
.modulus
);
2153 if (*cfg
.keyfile
&& !tried_publickey
)
2154 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
2156 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
2158 (supported_auths_mask
& (1 << SSH1_AUTH_TIS
))) {
2159 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
2160 logevent("Requested TIS authentication");
2161 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
2163 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2164 logevent("TIS authentication declined");
2165 if (flags
& FLAG_INTERACTIVE
)
2166 c_write_str("TIS authentication refused.\r\n");
2168 int challengelen
= ((pktin
.body
[0] << 24) |
2169 (pktin
.body
[1] << 16) |
2170 (pktin
.body
[2] << 8) |
2172 logevent("Received TIS challenge");
2173 if (challengelen
> sizeof(prompt
) - 1)
2174 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2175 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2176 prompt
[challengelen
] = '\0';
2179 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
2181 (supported_auths_mask
& (1 << SSH1_AUTH_CCARD
))) {
2182 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
2183 logevent("Requested CryptoCard authentication");
2184 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
2186 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
2187 logevent("CryptoCard authentication declined");
2188 c_write_str("CryptoCard authentication refused.\r\n");
2190 int challengelen
= ((pktin
.body
[0] << 24) |
2191 (pktin
.body
[1] << 16) |
2192 (pktin
.body
[2] << 8) |
2194 logevent("Received CryptoCard challenge");
2195 if (challengelen
> sizeof(prompt
) - 1)
2196 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2197 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2198 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
2199 sizeof(prompt
) - challengelen
);
2200 prompt
[sizeof(prompt
) - 1] = '\0';
2203 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2204 sprintf(prompt
, "%.90s@%.90s's password: ",
2205 username
, savedhost
);
2207 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2208 char *comment
= NULL
;
2209 if (flags
& FLAG_VERBOSE
)
2210 c_write_str("Trying public key authentication.\r\n");
2211 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
2212 if (flags
& FLAG_VERBOSE
)
2213 c_write_str("No passphrase required.\r\n");
2216 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
2221 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
2223 * get_line failed to get a password (for example
2224 * because one was supplied on the command line
2225 * which has already failed to work). Terminate.
2227 send_packet(SSH1_MSG_DISCONNECT
,
2228 PKT_STR
, "No more passwords available to try",
2230 connection_fatal("Unable to authenticate");
2231 ssh_state
= SSH_STATE_CLOSED
;
2235 c_write_str(prompt
);
2239 crWaitUntil(!ispkt
);
2241 switch (c
= *in
++) {
2262 if (pos
< sizeof(password
)-1)
2263 password
[pos
++] = c
;
2267 c_write_str("\r\n");
2271 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2273 * Try public key authentication with the specified
2276 static struct RSAKey pubkey
;
2277 static Bignum challenge
, response
;
2279 static unsigned char buffer
[32];
2281 tried_publickey
= 1;
2282 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
2284 c_write_str("Couldn't load public key from ");
2285 c_write_str(cfg
.keyfile
);
2286 c_write_str(".\r\n");
2287 continue; /* go and try password */
2290 c_write_str("Wrong passphrase.\r\n");
2291 tried_publickey
= 0;
2292 continue; /* try again */
2296 * Send a public key attempt.
2298 send_packet(SSH1_CMSG_AUTH_RSA
,
2299 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
2302 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2303 c_write_str("Server refused our public key.\r\n");
2304 continue; /* go and try password */
2306 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2307 bombout(("Bizarre response to offer of public key"));
2310 ssh1_read_bignum(pktin
.body
, &challenge
);
2311 response
= rsadecrypt(challenge
, &pubkey
);
2312 freebn(pubkey
.private_exponent
); /* burn the evidence */
2314 for (i
= 0; i
< 32; i
++) {
2315 buffer
[i
] = bignum_byte(response
, 31 - i
);
2319 MD5Update(&md5c
, buffer
, 32);
2320 MD5Update(&md5c
, session_id
, 16);
2321 MD5Final(buffer
, &md5c
);
2323 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2324 PKT_DATA
, buffer
, 16, PKT_END
);
2327 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2328 if (flags
& FLAG_VERBOSE
)
2330 ("Failed to authenticate with our public key.\r\n");
2331 continue; /* go and try password */
2332 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2334 ("Bizarre response to RSA authentication response"));
2338 break; /* we're through! */
2340 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2342 * Defence against traffic analysis: we send a
2343 * whole bunch of packets containing strings of
2344 * different lengths. One of these strings is the
2345 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2346 * The others are all random data in
2347 * SSH1_MSG_IGNORE packets. This way a passive
2348 * listener can't tell which is the password, and
2349 * hence can't deduce the password length.
2351 * Anybody with a password length greater than 16
2352 * bytes is going to have enough entropy in their
2353 * password that a listener won't find it _that_
2354 * much help to know how long it is. So what we'll
2357 * - if password length < 16, we send 15 packets
2358 * containing string lengths 1 through 15
2360 * - otherwise, we let N be the nearest multiple
2361 * of 8 below the password length, and send 8
2362 * packets containing string lengths N through
2363 * N+7. This won't obscure the order of
2364 * magnitude of the password length, but it will
2365 * introduce a bit of extra uncertainty.
2367 * A few servers (the old 1.2.18 through 1.2.22)
2368 * can't deal with SSH1_MSG_IGNORE. For these
2369 * servers, we need an alternative defence. We make
2370 * use of the fact that the password is interpreted
2371 * as a C string: so we can append a NUL, then some
2374 if (ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) {
2379 len
= strlen(password
);
2380 if (len
< sizeof(string
)) {
2382 strcpy(string
, password
);
2383 len
++; /* cover the zero byte */
2384 while (len
< sizeof(string
)) {
2385 string
[len
++] = (char) random_byte();
2390 send_packet(pwpkt_type
, PKT_INT
, len
,
2391 PKT_DATA
, s
, len
, PKT_END
);
2393 int bottom
, top
, pwlen
, i
;
2396 pwlen
= strlen(password
);
2398 bottom
= 0; /* zero length passwords are OK! :-) */
2401 bottom
= pwlen
& ~7;
2405 assert(pwlen
>= bottom
&& pwlen
<= top
);
2407 randomstr
= smalloc(top
+ 1);
2409 for (i
= bottom
; i
<= top
; i
++) {
2411 defer_packet(pwpkt_type
, PKT_STR
, password
,
2414 for (j
= 0; j
< i
; j
++) {
2416 randomstr
[j
] = random_byte();
2417 } while (randomstr
[j
] == '\0');
2419 randomstr
[i
] = '\0';
2420 defer_packet(SSH1_MSG_IGNORE
,
2421 PKT_STR
, randomstr
, PKT_END
);
2424 ssh_pkt_defersend();
2427 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2430 logevent("Sent password");
2431 memset(password
, 0, strlen(password
));
2433 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2434 if (flags
& FLAG_VERBOSE
)
2435 c_write_str("Access denied\r\n");
2436 logevent("Authentication refused");
2437 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2438 logevent("Received disconnect request");
2439 ssh_state
= SSH_STATE_CLOSED
;
2441 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2442 bombout(("Strange packet received, type %d", pktin
.type
));
2447 logevent("Authentication successful");
2452 void sshfwd_close(struct ssh_channel
*c
)
2454 if (c
&& !c
->closes
) {
2455 if (ssh_version
== 1) {
2456 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2459 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2460 ssh2_pkt_adduint32(c
->remoteid
);
2464 if (c
->type
== CHAN_X11
) {
2466 logevent("Forwarded X11 connection terminated");
2467 } else if (c
->type
== CHAN_SOCKDATA
) {
2469 logevent("Forwarded port closed");
2474 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
2476 if (ssh_version
== 1) {
2477 send_packet(SSH1_MSG_CHANNEL_DATA
,
2478 PKT_INT
, c
->remoteid
,
2479 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2481 * In SSH1 we can return 0 here - implying that forwarded
2482 * connections are never individually throttled - because
2483 * the only circumstance that can cause throttling will be
2484 * the whole SSH connection backing up, in which case
2485 * _everything_ will be throttled as a whole.
2489 ssh2_add_channel_data(c
, buf
, len
);
2490 return ssh2_try_send(c
);
2494 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
2496 if (ssh_version
== 1) {
2497 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
2498 c
->v
.v1
.throttling
= 0;
2502 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
2506 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
)
2512 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2515 if (ssh_state
== SSH_STATE_CLOSED
)
2518 if (cfg
.agentfwd
&& agent_exists()) {
2519 logevent("Requesting agent forwarding");
2520 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2524 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2525 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2526 bombout(("Protocol confusion"));
2528 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2529 logevent("Agent forwarding refused");
2531 logevent("Agent forwarding enabled");
2532 ssh_agentfwd_enabled
= TRUE
;
2536 if (cfg
.x11_forward
) {
2537 char proto
[20], data
[64];
2538 logevent("Requesting X11 forwarding");
2539 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2540 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2541 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2542 PKT_STR
, proto
, PKT_STR
, data
,
2543 PKT_INT
, 0, PKT_END
);
2545 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2546 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
2551 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2552 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2553 bombout(("Protocol confusion"));
2555 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2556 logevent("X11 forwarding refused");
2558 logevent("X11 forwarding enabled");
2559 ssh_X11_fwd_enabled
= TRUE
;
2567 char sports
[256], dports
[256], host
[256];
2570 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh1
);
2571 /* Add port forwardings. */
2576 while (*e
&& *e
!= '\t')
2582 while (*e
&& *e
!= ':')
2592 dport
= atoi(dports
);
2593 sport
= atoi(sports
);
2594 if (sport
&& dport
) {
2596 pfd_addforward(host
, dport
, sport
);
2597 sprintf(buf
, "Local port %d forwarding to %s:%d",
2598 sport
, host
, dport
);
2601 struct ssh_rportfwd
*pf
;
2602 pf
= smalloc(sizeof(*pf
));
2603 strcpy(pf
->dhost
, host
);
2605 if (add234(ssh_rportfwds
, pf
) != pf
) {
2607 "Duplicate remote port forwarding to %s:%d",
2612 sprintf(buf
, "Requesting remote port %d forward to %s:%d",
2613 sport
, host
, dport
);
2615 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST
,
2627 send_packet(SSH1_CMSG_REQUEST_PTY
,
2628 PKT_STR
, cfg
.termtype
,
2629 PKT_INT
, rows
, PKT_INT
, cols
,
2630 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
2631 ssh_state
= SSH_STATE_INTERMED
;
2635 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2636 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2637 bombout(("Protocol confusion"));
2639 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2640 c_write_str("Server refused to allocate pty\r\n");
2641 ssh_editing
= ssh_echoing
= 1;
2643 logevent("Allocated pty");
2645 ssh_editing
= ssh_echoing
= 1;
2648 if (cfg
.compression
) {
2649 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2653 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2654 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2655 bombout(("Protocol confusion"));
2657 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2658 c_write_str("Server refused to compress\r\n");
2660 logevent("Started compression");
2661 ssh1_compressing
= TRUE
;
2662 zlib_compress_init();
2663 zlib_decompress_init();
2666 if (*cfg
.remote_cmd_ptr
)
2667 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd_ptr
,
2670 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2671 logevent("Started session");
2673 ssh_state
= SSH_STATE_SESSION
;
2677 ssh_special(TS_EOF
);
2679 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
2681 ssh_channels
= newtree234(ssh_channelcmp
);
2685 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2686 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2687 long len
= GET_32BIT(pktin
.body
);
2689 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2690 pktin
.body
+ 4, len
);
2691 if (bufsize
> SSH1_BUFFER_LIMIT
) {
2692 ssh1_stdout_throttling
= 1;
2695 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2696 ssh_state
= SSH_STATE_CLOSED
;
2697 logevent("Received disconnect request");
2699 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2700 /* Remote side is trying to open a channel to talk to our
2701 * X-Server. Give them back a local channel number. */
2702 struct ssh_channel
*c
;
2704 logevent("Received X11 connect request");
2705 /* Refuse if X11 forwarding is disabled. */
2706 if (!ssh_X11_fwd_enabled
) {
2707 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2708 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2709 logevent("Rejected X11 connect request");
2711 c
= smalloc(sizeof(struct ssh_channel
));
2713 if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2714 logevent("opening X11 forward connection failed");
2716 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2717 PKT_INT
, GET_32BIT(pktin
.body
),
2721 ("opening X11 forward connection succeeded");
2722 c
->remoteid
= GET_32BIT(pktin
.body
);
2723 c
->localid
= alloc_channel_id();
2725 c
->v
.v1
.throttling
= 0;
2726 c
->type
= CHAN_X11
; /* identify channel type */
2727 add234(ssh_channels
, c
);
2728 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2729 PKT_INT
, c
->remoteid
, PKT_INT
,
2730 c
->localid
, PKT_END
);
2731 logevent("Opened X11 forward channel");
2734 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2735 /* Remote side is trying to open a channel to talk to our
2736 * agent. Give them back a local channel number. */
2737 struct ssh_channel
*c
;
2739 /* Refuse if agent forwarding is disabled. */
2740 if (!ssh_agentfwd_enabled
) {
2741 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2742 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2744 c
= smalloc(sizeof(struct ssh_channel
));
2745 c
->remoteid
= GET_32BIT(pktin
.body
);
2746 c
->localid
= alloc_channel_id();
2748 c
->v
.v1
.throttling
= 0;
2749 c
->type
= CHAN_AGENT
; /* identify channel type */
2750 c
->u
.a
.lensofar
= 0;
2751 add234(ssh_channels
, c
);
2752 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2753 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2756 } else if (pktin
.type
== SSH1_MSG_PORT_OPEN
) {
2757 /* Remote side is trying to open a channel to talk to a
2758 * forwarded port. Give them back a local channel number. */
2759 struct ssh_channel
*c
;
2760 struct ssh_rportfwd pf
;
2762 char host
[256], buf
[1024];
2764 c
= smalloc(sizeof(struct ssh_channel
));
2766 hostsize
= GET_32BIT(pktin
.body
+4);
2767 for(h
= host
, p
= pktin
.body
+8; hostsize
!= 0; hostsize
--) {
2768 if (h
+1 < host
+sizeof(host
))
2773 port
= GET_32BIT(p
);
2775 strcpy(pf
.dhost
, host
);
2778 if (find234(ssh_rportfwds
, &pf
, NULL
) == NULL
) {
2779 sprintf(buf
, "Rejected remote port open request for %s:%d",
2782 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2783 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2785 sprintf(buf
, "Received remote port open request for %s:%d",
2788 e
= pfd_newconnect(&c
->u
.pfd
.s
, host
, port
, c
);
2791 sprintf(buf
, "Port open failed: %s", e
);
2794 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2795 PKT_INT
, GET_32BIT(pktin
.body
),
2798 c
->remoteid
= GET_32BIT(pktin
.body
);
2799 c
->localid
= alloc_channel_id();
2801 c
->v
.v1
.throttling
= 0;
2802 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
2803 add234(ssh_channels
, c
);
2804 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2805 PKT_INT
, c
->remoteid
, PKT_INT
,
2806 c
->localid
, PKT_END
);
2807 logevent("Forwarded port opened successfully");
2811 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
2812 unsigned int remoteid
= GET_32BIT(pktin
.body
);
2813 unsigned int localid
= GET_32BIT(pktin
.body
+4);
2814 struct ssh_channel
*c
;
2816 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
2817 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
2818 c
->remoteid
= localid
;
2819 c
->type
= CHAN_SOCKDATA
;
2820 pfd_confirm(c
->u
.pfd
.s
);
2823 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2824 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2825 /* Remote side closes a channel. */
2826 unsigned i
= GET_32BIT(pktin
.body
);
2827 struct ssh_channel
*c
;
2828 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2832 (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2833 if (!(c
->closes
& closetype
))
2834 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
,
2836 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2837 logevent("Forwarded X11 connection terminated");
2838 assert(c
->u
.x11
.s
!= NULL
);
2839 x11_close(c
->u
.x11
.s
);
2842 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
2843 logevent("Forwarded port closed");
2844 assert(c
->u
.pfd
.s
!= NULL
);
2845 pfd_close(c
->u
.pfd
.s
);
2848 c
->closes
|= closetype
;
2849 if (c
->closes
== 3) {
2850 del234(ssh_channels
, c
);
2854 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2855 /* Data sent down one of our channels. */
2856 int i
= GET_32BIT(pktin
.body
);
2857 int len
= GET_32BIT(pktin
.body
+ 4);
2858 unsigned char *p
= pktin
.body
+ 8;
2859 struct ssh_channel
*c
;
2860 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2865 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
2868 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
2871 /* Data for an agent message. Buffer it. */
2873 if (c
->u
.a
.lensofar
< 4) {
2874 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2875 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
2879 c
->u
.a
.lensofar
+= l
;
2881 if (c
->u
.a
.lensofar
== 4) {
2883 4 + GET_32BIT(c
->u
.a
.msglen
);
2884 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2885 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2887 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2889 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
2891 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
2895 c
->u
.a
.lensofar
+= l
;
2897 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2898 void *reply
, *sentreply
;
2900 agent_query(c
->u
.a
.message
,
2901 c
->u
.a
.totallen
, &reply
,
2906 /* Fake SSH_AGENT_FAILURE. */
2907 sentreply
= "\0\0\0\1\5";
2910 send_packet(SSH1_MSG_CHANNEL_DATA
,
2911 PKT_INT
, c
->remoteid
,
2913 PKT_DATA
, sentreply
, replylen
,
2917 sfree(c
->u
.a
.message
);
2918 c
->u
.a
.lensofar
= 0;
2921 bufsize
= 0; /* agent channels never back up */
2924 if (bufsize
> SSH1_BUFFER_LIMIT
) {
2925 c
->v
.v1
.throttling
= 1;
2929 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2930 /* may be from EXEC_SHELL on some servers */
2931 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2932 /* may be from EXEC_SHELL on some servers
2933 * if no pty is available or in other odd cases. Ignore */
2934 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2935 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2937 bombout(("Strange packet received: type %d", pktin
.type
));
2942 int len
= min(inlen
, 512);
2943 send_packet(SSH1_CMSG_STDIN_DATA
,
2944 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
2955 * Utility routine for decoding comma-separated strings in KEXINIT.
2957 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
2959 int needlen
= strlen(needle
);
2962 * Is it at the start of the string?
2964 if (haylen
>= needlen
&& /* haystack is long enough */
2965 !memcmp(needle
, haystack
, needlen
) && /* initial match */
2966 (haylen
== needlen
|| haystack
[needlen
] == ',')
2967 /* either , or EOS follows */
2971 * If not, search for the next comma and resume after that.
2972 * If no comma found, terminate.
2974 while (haylen
> 0 && *haystack
!= ',')
2975 haylen
--, haystack
++;
2978 haylen
--, haystack
++; /* skip over comma itself */
2983 * SSH2 key creation method.
2985 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
,
2989 /* First 20 bytes. */
2992 SHA_Bytes(&s
, H
, 20);
2993 SHA_Bytes(&s
, &chr
, 1);
2994 SHA_Bytes(&s
, sessid
, 20);
2995 SHA_Final(&s
, keyspace
);
2996 /* Next 20 bytes. */
2999 SHA_Bytes(&s
, H
, 20);
3000 SHA_Bytes(&s
, keyspace
, 20);
3001 SHA_Final(&s
, keyspace
+ 20);
3005 * Handle the SSH2 transport layer.
3007 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
3009 static int i
, j
, len
, nbits
, pbits
, warn
;
3011 static Bignum p
, g
, e
, f
, K
;
3012 static int kex_init_value
, kex_reply_value
;
3013 static const struct ssh_mac
**maclist
;
3015 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
3016 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
3017 static const struct ssh_mac
*csmac_tobe
= NULL
;
3018 static const struct ssh_mac
*scmac_tobe
= NULL
;
3019 static const struct ssh_compress
*cscomp_tobe
= NULL
;
3020 static const struct ssh_compress
*sccomp_tobe
= NULL
;
3021 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
3022 static int hostkeylen
, siglen
;
3023 static void *hkey
; /* actual host key */
3024 static unsigned char exchange_hash
[20];
3025 static unsigned char keyspace
[40];
3026 static int n_preferred_ciphers
;
3027 static const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
3028 static const struct ssh_compress
*preferred_comp
;
3029 static int first_kex
;
3036 * Set up the preferred ciphers. (NULL => warn below here)
3038 n_preferred_ciphers
= 0;
3039 for (i
= 0; i
< CIPHER_MAX
; i
++) {
3040 switch (cfg
.ssh_cipherlist
[i
]) {
3041 case CIPHER_BLOWFISH
:
3042 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_blowfish
;
3043 n_preferred_ciphers
++;
3046 /* Not supported in SSH2; silently drop */
3049 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_3des
;
3050 n_preferred_ciphers
++;
3053 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_aes
;
3054 n_preferred_ciphers
++;
3057 /* Flag for later. Don't bother if it's the last in
3059 if (i
< CIPHER_MAX
- 1) {
3060 preferred_ciphers
[n_preferred_ciphers
] = NULL
;
3061 n_preferred_ciphers
++;
3068 * Set up preferred compression.
3070 if (cfg
.compression
)
3071 preferred_comp
= &ssh_zlib
;
3073 preferred_comp
= &ssh_comp_none
;
3076 * Be prepared to work around the buggy MAC problem.
3078 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
3079 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
3081 maclist
= macs
, nmacs
= lenof(macs
);
3085 * Construct and send our key exchange packet.
3087 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
3088 for (i
= 0; i
< 16; i
++)
3089 ssh2_pkt_addbyte((unsigned char) random_byte());
3090 /* List key exchange algorithms. */
3091 ssh2_pkt_addstring_start();
3092 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3093 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
3094 if (i
< lenof(kex_algs
) - 1)
3095 ssh2_pkt_addstring_str(",");
3097 /* List server host key algorithms. */
3098 ssh2_pkt_addstring_start();
3099 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3100 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
3101 if (i
< lenof(hostkey_algs
) - 1)
3102 ssh2_pkt_addstring_str(",");
3104 /* List client->server encryption algorithms. */
3105 ssh2_pkt_addstring_start();
3106 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3107 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3108 if (!c
) continue; /* warning flag */
3109 for (j
= 0; j
< c
->nciphers
; j
++) {
3110 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3111 if (i
< n_preferred_ciphers
|| j
< c
->nciphers
- 1)
3112 ssh2_pkt_addstring_str(",");
3115 /* List server->client encryption algorithms. */
3116 ssh2_pkt_addstring_start();
3117 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3118 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3119 if (!c
) continue; /* warning flag */
3120 for (j
= 0; j
< c
->nciphers
; j
++) {
3121 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3122 if (i
< n_preferred_ciphers
|| j
< c
->nciphers
- 1)
3123 ssh2_pkt_addstring_str(",");
3126 /* List client->server MAC algorithms. */
3127 ssh2_pkt_addstring_start();
3128 for (i
= 0; i
< nmacs
; i
++) {
3129 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3131 ssh2_pkt_addstring_str(",");
3133 /* List server->client MAC algorithms. */
3134 ssh2_pkt_addstring_start();
3135 for (i
= 0; i
< nmacs
; i
++) {
3136 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3138 ssh2_pkt_addstring_str(",");
3140 /* List client->server compression algorithms. */
3141 ssh2_pkt_addstring_start();
3142 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3143 const struct ssh_compress
*c
=
3144 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3145 ssh2_pkt_addstring_str(c
->name
);
3146 if (i
< lenof(compressions
))
3147 ssh2_pkt_addstring_str(",");
3149 /* List server->client compression algorithms. */
3150 ssh2_pkt_addstring_start();
3151 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3152 const struct ssh_compress
*c
=
3153 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3154 ssh2_pkt_addstring_str(c
->name
);
3155 if (i
< lenof(compressions
))
3156 ssh2_pkt_addstring_str(",");
3158 /* List client->server languages. Empty list. */
3159 ssh2_pkt_addstring_start();
3160 /* List server->client languages. Empty list. */
3161 ssh2_pkt_addstring_start();
3162 /* First KEX packet does _not_ follow, because we're not that brave. */
3163 ssh2_pkt_addbool(FALSE
);
3165 ssh2_pkt_adduint32(0);
3167 exhash
= exhashbase
;
3168 sha_string(&exhash
, pktout
.data
+ 5, pktout
.length
- 5);
3174 sha_string(&exhash
, pktin
.data
+ 5, pktin
.length
- 5);
3177 * Now examine the other side's KEXINIT to see what we're up
3180 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
3181 bombout(("expected key exchange packet from server"));
3186 cscipher_tobe
= NULL
;
3187 sccipher_tobe
= NULL
;
3192 pktin
.savedpos
+= 16; /* skip garbage cookie */
3193 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
3194 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3195 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
3200 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
3201 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3202 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
3203 hostkey
= hostkey_algs
[i
];
3207 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
3209 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3210 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3214 for (j
= 0; j
< c
->nciphers
; j
++) {
3215 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3216 cscipher_tobe
= c
->list
[j
];
3221 if (cscipher_tobe
) {
3223 askcipher(cscipher_tobe
->name
, 1);
3227 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
3229 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3230 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3234 for (j
= 0; j
< c
->nciphers
; j
++) {
3235 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3236 sccipher_tobe
= c
->list
[j
];
3241 if (sccipher_tobe
) {
3243 askcipher(sccipher_tobe
->name
, 2);
3247 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
3248 for (i
= 0; i
< nmacs
; i
++) {
3249 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3250 csmac_tobe
= maclist
[i
];
3254 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
3255 for (i
= 0; i
< nmacs
; i
++) {
3256 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3257 scmac_tobe
= maclist
[i
];
3261 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
3262 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3263 const struct ssh_compress
*c
=
3264 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3265 if (in_commasep_string(c
->name
, str
, len
)) {
3270 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
3271 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3272 const struct ssh_compress
*c
=
3273 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3274 if (in_commasep_string(c
->name
, str
, len
)) {
3281 * Work out the number of bits of key we will need from the key
3282 * exchange. We start with the maximum key length of either
3288 csbits
= cscipher_tobe
->keylen
;
3289 scbits
= sccipher_tobe
->keylen
;
3290 nbits
= (csbits
> scbits ? csbits
: scbits
);
3292 /* The keys only have 160-bit entropy, since they're based on
3293 * a SHA-1 hash. So cap the key size at 160 bits. */
3298 * If we're doing Diffie-Hellman group exchange, start by
3299 * requesting a group.
3301 if (kex
== &ssh_diffiehellman_gex
) {
3302 logevent("Doing Diffie-Hellman group exchange");
3304 * Work out how big a DH group we will need to allow that
3307 pbits
= 512 << ((nbits
- 1) / 64);
3308 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
3309 ssh2_pkt_adduint32(pbits
);
3313 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
3314 bombout(("expected key exchange group packet from server"));
3317 p
= ssh2_pkt_getmp();
3318 g
= ssh2_pkt_getmp();
3319 dh_setup_group(p
, g
);
3320 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
3321 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
3324 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
3325 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
3328 logevent("Doing Diffie-Hellman key exchange");
3330 * Now generate and send e for Diffie-Hellman.
3332 e
= dh_create_e(nbits
* 2);
3333 ssh2_pkt_init(kex_init_value
);
3338 if (pktin
.type
!= kex_reply_value
) {
3339 bombout(("expected key exchange reply packet from server"));
3342 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
3343 f
= ssh2_pkt_getmp();
3344 ssh2_pkt_getstring(&sigdata
, &siglen
);
3348 sha_string(&exhash
, hostkeydata
, hostkeylen
);
3349 if (kex
== &ssh_diffiehellman_gex
) {
3350 sha_uint32(&exhash
, pbits
);
3351 sha_mpint(&exhash
, p
);
3352 sha_mpint(&exhash
, g
);
3354 sha_mpint(&exhash
, e
);
3355 sha_mpint(&exhash
, f
);
3356 sha_mpint(&exhash
, K
);
3357 SHA_Final(&exhash
, exchange_hash
);
3362 debug(("Exchange hash is:\n"));
3363 dmemdump(exchange_hash
, 20);
3366 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
3368 !hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
3369 bombout(("Server's host key did not match the signature supplied"));
3374 * Expect SSH2_MSG_NEWKEYS from server.
3377 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
3378 bombout(("expected new-keys packet from server"));
3383 * Authenticate remote host: verify host key. (We've already
3384 * checked the signature of the exchange hash.)
3386 keystr
= hostkey
->fmtkey(hkey
);
3387 fingerprint
= hostkey
->fingerprint(hkey
);
3388 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
3389 keystr
, fingerprint
);
3390 if (first_kex
) { /* don't bother logging this in rekeys */
3391 logevent("Host key fingerprint is:");
3392 logevent(fingerprint
);
3396 hostkey
->freekey(hkey
);
3399 * Send SSH2_MSG_NEWKEYS.
3401 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
3405 * Create and initialise session keys.
3407 cscipher
= cscipher_tobe
;
3408 sccipher
= sccipher_tobe
;
3411 cscomp
= cscomp_tobe
;
3412 sccomp
= sccomp_tobe
;
3413 cscomp
->compress_init();
3414 sccomp
->decompress_init();
3416 * Set IVs after keys. Here we use the exchange hash from the
3417 * _first_ key exchange.
3420 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
3421 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
3422 cscipher
->setcskey(keyspace
);
3423 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
3424 sccipher
->setsckey(keyspace
);
3425 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
3426 cscipher
->setcsiv(keyspace
);
3427 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
3428 sccipher
->setsciv(keyspace
);
3429 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
3430 csmac
->setcskey(keyspace
);
3431 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
3432 scmac
->setsckey(keyspace
);
3435 * If this is the first key exchange phase, we must pass the
3436 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3437 * wants to see it but because it will need time to initialise
3438 * itself before it sees an actual packet. In subsequent key
3439 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3440 * it would only confuse the layer above.
3448 * Now we're encrypting. Begin returning 1 to the protocol main
3449 * function so that other things can run on top of the
3450 * transport. If we ever see a KEXINIT, we must go back to the
3453 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
3456 logevent("Server initiated key re-exchange");
3457 goto begin_key_exchange
;
3463 * Add data to an SSH2 channel output buffer.
3465 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
3468 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
3472 * Attempt to send data on an SSH2 channel.
3474 static int ssh2_try_send(struct ssh_channel
*c
)
3476 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
3479 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
3480 if ((unsigned)len
> c
->v
.v2
.remwindow
)
3481 len
= c
->v
.v2
.remwindow
;
3482 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
3483 len
= c
->v
.v2
.remmaxpkt
;
3484 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
3485 ssh2_pkt_adduint32(c
->remoteid
);
3486 ssh2_pkt_addstring_start();
3487 ssh2_pkt_addstring_data(data
, len
);
3489 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
3490 c
->v
.v2
.remwindow
-= len
;
3494 * After having sent as much data as we can, return the amount
3497 return bufchain_size(&c
->v
.v2
.outbuffer
);
3501 * Potentially enlarge the window on an SSH2 channel.
3503 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
3505 if (newwin
> c
->v
.v2
.locwindow
) {
3506 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3507 ssh2_pkt_adduint32(c
->remoteid
);
3508 ssh2_pkt_adduint32(newwin
- c
->v
.v2
.locwindow
);
3510 c
->v
.v2
.locwindow
= newwin
;
3515 * Handle the SSH2 userauth and connection layers.
3517 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
3520 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
3522 AUTH_KEYBOARD_INTERACTIVE
3526 AUTH_TYPE_PUBLICKEY
,
3527 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
3528 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
3530 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
3531 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
3533 static int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
3534 static int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
3535 static int kbd_inter_running
;
3536 static int we_are_in
;
3537 static int num_prompts
, echo
;
3538 static char username
[100];
3539 static char pwprompt
[200];
3540 static char password
[100];
3545 * Request userauth protocol, and await a response to it.
3547 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
3548 ssh2_pkt_addstring("ssh-userauth");
3550 crWaitUntilV(ispkt
);
3551 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
3552 bombout(("Server refused user authentication protocol"));
3557 * We repeat this whole loop, including the username prompt,
3558 * until we manage a successful authentication. If the user
3559 * types the wrong _password_, they are sent back to the
3560 * beginning to try another username. (If they specify a
3561 * username in the config, they are never asked, even if they
3562 * do give a wrong password.)
3564 * I think this best serves the needs of
3566 * - the people who have no configuration, no keys, and just
3567 * want to try repeated (username,password) pairs until they
3568 * type both correctly
3570 * - people who have keys and configuration but occasionally
3571 * need to fall back to passwords
3573 * - people with a key held in Pageant, who might not have
3574 * logged in to a particular machine before; so they want to
3575 * type a username, and then _either_ their key will be
3576 * accepted, _or_ they will type a password. If they mistype
3577 * the username they will want to be able to get back and
3588 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
3590 if (!ssh_get_line("login as: ",
3591 username
, sizeof(username
), FALSE
)) {
3593 * get_line failed to get a username.
3596 logevent("No username provided. Abandoning session.");
3597 ssh_state
= SSH_STATE_CLOSED
;
3601 c_write_str("login as: ");
3604 crWaitUntilV(!ispkt
);
3606 switch (c
= *in
++) {
3615 c_write_str("\b \b");
3622 c_write_str("\b \b");
3632 if (((c
>= ' ' && c
<= '~') ||
3633 ((unsigned char) c
>= 160))
3634 && pos
< sizeof(username
)-1) {
3635 username
[pos
++] = c
;
3642 c_write_str("\r\n");
3643 username
[strcspn(username
, "\n\r")] = '\0';
3646 strncpy(username
, cfg
.username
, 99);
3647 username
[99] = '\0';
3648 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
3649 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
3655 * Send an authentication request using method "none": (a)
3656 * just in case it succeeds, and (b) so that we know what
3657 * authentication methods we can usefully try next.
3659 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3660 ssh2_pkt_addstring(username
);
3661 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3662 ssh2_pkt_addstring("none"); /* method */
3664 type
= AUTH_TYPE_NONE
;
3668 tried_pubkey_config
= FALSE
;
3669 tried_agent
= FALSE
;
3670 tried_keyb_inter
= FALSE
;
3671 kbd_inter_running
= FALSE
;
3675 * Wait for the result of the last authentication request.
3678 crWaitUntilV(ispkt
);
3679 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
3683 * Don't show the banner if we're operating in
3684 * non-verbose non-interactive mode. (It's probably
3685 * a script, which means nobody will read the
3686 * banner _anyway_, and moreover the printing of
3687 * the banner will screw up processing on the
3688 * output of (say) plink.)
3690 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
3691 ssh2_pkt_getstring(&banner
, &size
);
3693 c_write_untrusted(banner
, size
);
3695 crWaitUntilV(ispkt
);
3697 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
3698 logevent("Access granted");
3703 if (kbd_inter_running
&&
3704 pktin
.type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
3706 * This is a further prompt in keyboard-interactive
3707 * authentication. Do nothing.
3709 } else if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
3710 bombout(("Strange packet received during authentication: type %d",
3718 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3719 * we can look at the string in it and know what we can
3720 * helpfully try next.
3722 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
) {
3725 ssh2_pkt_getstring(&methods
, &methlen
);
3726 kbd_inter_running
= FALSE
;
3727 if (!ssh2_pkt_getbool()) {
3729 * We have received an unequivocal Access
3730 * Denied. This can translate to a variety of
3733 * - if we'd just tried "none" authentication,
3734 * it's not worth printing anything at all
3736 * - if we'd just tried a public key _offer_,
3737 * the message should be "Server refused our
3738 * key" (or no message at all if the key
3739 * came from Pageant)
3741 * - if we'd just tried anything else, the
3742 * message really should be "Access denied".
3744 * Additionally, if we'd just tried password
3745 * authentication, we should break out of this
3746 * whole loop so as to go back to the username
3749 if (type
== AUTH_TYPE_NONE
) {
3751 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
3752 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
3753 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
3754 c_write_str("Server refused our key\r\n");
3755 logevent("Server refused public key");
3756 } else if (type
== AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
3757 /* server declined keyboard-interactive; ignore */
3759 c_write_str("Access denied\r\n");
3760 logevent("Access denied");
3761 if (type
== AUTH_TYPE_PASSWORD
) {
3767 c_write_str("Further authentication required\r\n");
3768 logevent("Further authentication required");
3772 in_commasep_string("publickey", methods
, methlen
);
3774 in_commasep_string("password", methods
, methlen
);
3776 in_commasep_string("password", methods
, methlen
);
3778 in_commasep_string("keyboard-interactive", methods
, methlen
);
3783 if (!method
&& can_keyb_inter
&& !tried_keyb_inter
) {
3784 method
= AUTH_KEYBOARD_INTERACTIVE
;
3785 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
3786 tried_keyb_inter
= TRUE
;
3788 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3789 ssh2_pkt_addstring(username
);
3790 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3791 ssh2_pkt_addstring("keyboard-interactive"); /* method */
3792 ssh2_pkt_addstring(""); /* lang */
3793 ssh2_pkt_addstring("");
3796 crWaitUntilV(ispkt
);
3797 if (pktin
.type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
3798 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
)
3800 logevent("Keyboard-interactive authentication refused");
3801 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
3805 kbd_inter_running
= TRUE
;
3808 if (kbd_inter_running
) {
3809 method
= AUTH_KEYBOARD_INTERACTIVE
;
3810 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
3811 tried_keyb_inter
= TRUE
;
3813 /* We've got packet with that "interactive" info
3814 dump banners, and set its prompt as ours */
3816 char *name
, *inst
, *lang
, *prompt
;
3817 int name_len
, inst_len
, lang_len
, prompt_len
;
3818 ssh2_pkt_getstring(&name
, &name_len
);
3819 ssh2_pkt_getstring(&inst
, &inst_len
);
3820 ssh2_pkt_getstring(&lang
, &lang_len
);
3822 c_write_untrusted(name
, name_len
);
3824 c_write_untrusted(inst
, inst_len
);
3825 num_prompts
= ssh2_pkt_getuint32();
3827 ssh2_pkt_getstring(&prompt
, &prompt_len
);
3828 strncpy(pwprompt
, prompt
, sizeof(pwprompt
));
3831 echo
= ssh2_pkt_getbool();
3835 if (!method
&& can_pubkey
&& agent_exists() && !tried_agent
) {
3837 * Attempt public-key authentication using Pageant.
3839 static unsigned char request
[5], *response
, *p
;
3840 static int responselen
;
3841 static int i
, nkeys
;
3842 static int authed
= FALSE
;
3847 logevent("Pageant is running. Requesting keys.");
3849 /* Request the keys held by the agent. */
3850 PUT_32BIT(request
, 1);
3851 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
3852 agent_query(request
, 5, &r
, &responselen
);
3853 response
= (unsigned char *) r
;
3854 if (response
&& responselen
>= 5 &&
3855 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
3857 nkeys
= GET_32BIT(p
);
3861 sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
3864 for (i
= 0; i
< nkeys
; i
++) {
3865 static char *pkblob
, *alg
, *commentp
;
3866 static int pklen
, alglen
, commentlen
;
3867 static int siglen
, retlen
, len
;
3868 static char *q
, *agentreq
, *ret
;
3873 sprintf(buf
, "Trying Pageant key #%d", i
);
3876 pklen
= GET_32BIT(p
);
3880 alglen
= GET_32BIT(pkblob
);
3882 commentlen
= GET_32BIT(p
);
3886 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3887 ssh2_pkt_addstring(username
);
3888 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3889 ssh2_pkt_addstring("publickey"); /* method */
3890 ssh2_pkt_addbool(FALSE
); /* no signature included */
3891 ssh2_pkt_addstring_start();
3892 ssh2_pkt_addstring_data(alg
, alglen
);
3893 ssh2_pkt_addstring_start();
3894 ssh2_pkt_addstring_data(pkblob
, pklen
);
3897 crWaitUntilV(ispkt
);
3898 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3899 logevent("Key refused");
3903 if (flags
& FLAG_VERBOSE
) {
3905 ("Authenticating with public key \"");
3906 c_write(commentp
, commentlen
);
3907 c_write_str("\" from agent\r\n");
3911 * Server is willing to accept the key.
3912 * Construct a SIGN_REQUEST.
3914 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3915 ssh2_pkt_addstring(username
);
3916 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3917 ssh2_pkt_addstring("publickey"); /* method */
3918 ssh2_pkt_addbool(TRUE
);
3919 ssh2_pkt_addstring_start();
3920 ssh2_pkt_addstring_data(alg
, alglen
);
3921 ssh2_pkt_addstring_start();
3922 ssh2_pkt_addstring_data(pkblob
, pklen
);
3924 siglen
= pktout
.length
- 5 + 4 + 20;
3925 len
= 1; /* message type */
3926 len
+= 4 + pklen
; /* key blob */
3927 len
+= 4 + siglen
; /* data to sign */
3928 len
+= 4; /* flags */
3929 agentreq
= smalloc(4 + len
);
3930 PUT_32BIT(agentreq
, len
);
3932 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
3933 PUT_32BIT(q
, pklen
);
3935 memcpy(q
, pkblob
, pklen
);
3937 PUT_32BIT(q
, siglen
);
3939 /* Now the data to be signed... */
3942 memcpy(q
, ssh2_session_id
, 20);
3944 memcpy(q
, pktout
.data
+ 5, pktout
.length
- 5);
3945 q
+= pktout
.length
- 5;
3946 /* And finally the (zero) flags word. */
3948 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
3952 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
3953 logevent("Sending Pageant's response");
3954 ssh2_pkt_addstring_start();
3955 ssh2_pkt_addstring_data(ret
+ 9,
3963 ("Pageant failed to answer challenge");
3973 if (!method
&& can_pubkey
&& *cfg
.keyfile
3974 && !tried_pubkey_config
) {
3975 unsigned char *pub_blob
;
3976 char *algorithm
, *comment
;
3979 tried_pubkey_config
= TRUE
;
3982 * Try the public key supplied in the configuration.
3984 * First, offer the public blob to see if the server is
3985 * willing to accept it.
3987 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
3990 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3991 ssh2_pkt_addstring(username
);
3992 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3993 ssh2_pkt_addstring("publickey"); /* method */
3994 ssh2_pkt_addbool(FALSE
); /* no signature included */
3995 ssh2_pkt_addstring(algorithm
);
3996 ssh2_pkt_addstring_start();
3997 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
3999 logevent("Offered public key"); /* FIXME */
4001 crWaitUntilV(ispkt
);
4002 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4004 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
4005 continue; /* key refused; give up on it */
4008 logevent("Offer of public key accepted");
4010 * Actually attempt a serious authentication using
4013 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
4015 "Passphrase for key \"%.100s\": ",
4021 c_write_str("Authenticating with public key \"");
4022 c_write_str(comment
);
4023 c_write_str("\"\r\n");
4024 method
= AUTH_PUBLICKEY_FILE
;
4028 if (!method
&& can_passwd
) {
4029 method
= AUTH_PASSWORD
;
4030 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
,
4037 if (!ssh_get_line(pwprompt
, password
,
4038 sizeof(password
), TRUE
)) {
4040 * get_line failed to get a password (for
4041 * example because one was supplied on the
4042 * command line which has already failed to
4045 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4046 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4048 ("No more passwords available to try");
4049 ssh2_pkt_addstring("en"); /* language tag */
4051 connection_fatal("Unable to authenticate");
4052 ssh_state
= SSH_STATE_CLOSED
;
4059 c_write_untrusted(pwprompt
, strlen(pwprompt
));
4064 crWaitUntilV(!ispkt
);
4066 switch (c
= *in
++) {
4087 if (pos
< sizeof(password
)-1)
4088 password
[pos
++] = c
;
4092 c_write_str("\r\n");
4096 if (method
== AUTH_PUBLICKEY_FILE
) {
4098 * We have our passphrase. Now try the actual authentication.
4100 struct ssh2_userkey
*key
;
4102 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
4103 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
4104 if (key
== SSH2_WRONG_PASSPHRASE
) {
4105 c_write_str("Wrong passphrase\r\n");
4106 tried_pubkey_config
= FALSE
;
4108 c_write_str("Unable to load private key\r\n");
4109 tried_pubkey_config
= TRUE
;
4111 /* Send a spurious AUTH_NONE to return to the top. */
4112 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4113 ssh2_pkt_addstring(username
);
4114 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4115 ssh2_pkt_addstring("none"); /* method */
4117 type
= AUTH_TYPE_NONE
;
4119 unsigned char *blob
, *sigdata
;
4120 int blob_len
, sigdata_len
;
4123 * We have loaded the private key and the server
4124 * has announced that it's willing to accept it.
4125 * Hallelujah. Generate a signature and send it.
4127 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4128 ssh2_pkt_addstring(username
);
4129 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4130 ssh2_pkt_addstring("publickey"); /* method */
4131 ssh2_pkt_addbool(TRUE
);
4132 ssh2_pkt_addstring(key
->alg
->name
);
4133 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
4134 ssh2_pkt_addstring_start();
4135 ssh2_pkt_addstring_data(blob
, blob_len
);
4139 * The data to be signed is:
4143 * followed by everything so far placed in the
4146 sigdata_len
= pktout
.length
- 5 + 4 + 20;
4147 sigdata
= smalloc(sigdata_len
);
4148 PUT_32BIT(sigdata
, 20);
4149 memcpy(sigdata
+ 4, ssh2_session_id
, 20);
4150 memcpy(sigdata
+ 24, pktout
.data
+ 5,
4153 key
->alg
->sign(key
->data
, sigdata
, sigdata_len
,
4155 ssh2_pkt_addstring_start();
4156 ssh2_pkt_addstring_data(blob
, blob_len
);
4161 type
= AUTH_TYPE_PUBLICKEY
;
4163 } else if (method
== AUTH_PASSWORD
) {
4165 * We send the password packet lumped tightly together with
4166 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4167 * string long enough to make the total length of the two
4168 * packets constant. This should ensure that a passive
4169 * listener doing traffic analyis can't work out the length
4172 * For this to work, we need an assumption about the
4173 * maximum length of the password packet. I think 256 is
4174 * pretty conservative. Anyone using a password longer than
4175 * that probably doesn't have much to worry about from
4176 * people who find out how long their password is!
4178 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4179 ssh2_pkt_addstring(username
);
4180 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4181 ssh2_pkt_addstring("password");
4182 ssh2_pkt_addbool(FALSE
);
4183 ssh2_pkt_addstring(password
);
4186 * We'll include a string that's an exact multiple of the
4187 * cipher block size. If the cipher is NULL for some
4188 * reason, we don't do this trick at all because we gain
4194 stringlen
= (256 - deferred_len
);
4195 stringlen
+= cscipher
->blksize
- 1;
4196 stringlen
-= (stringlen
% cscipher
->blksize
);
4199 * Temporarily disable actual compression,
4200 * so we can guarantee to get this string
4201 * exactly the length we want it. The
4202 * compression-disabling routine should
4203 * return an integer indicating how many
4204 * bytes we should adjust our string length
4207 stringlen
-= cscomp
->disable_compression();
4209 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4210 ssh2_pkt_addstring_start();
4211 for (i
= 0; i
< stringlen
; i
++) {
4212 char c
= (char) random_byte();
4213 ssh2_pkt_addstring_data(&c
, 1);
4217 ssh_pkt_defersend();
4218 logevent("Sent password");
4219 type
= AUTH_TYPE_PASSWORD
;
4220 } else if (method
== AUTH_KEYBOARD_INTERACTIVE
) {
4221 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
4222 ssh2_pkt_adduint32(num_prompts
);
4223 ssh2_pkt_addstring(password
);
4224 memset(password
, 0, sizeof(password
));
4226 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4229 ("No supported authentication methods left to try!\r\n");
4231 ("No supported authentications offered. Disconnecting");
4232 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4233 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4235 ("No supported authentication methods available");
4236 ssh2_pkt_addstring("en"); /* language tag */
4238 ssh_state
= SSH_STATE_CLOSED
;
4242 } while (!we_are_in
);
4245 * Now we're authenticated for the connection protocol. The
4246 * connection protocol will automatically have started at this
4247 * point; there's no need to send SERVICE_REQUEST.
4251 * So now create a channel with a session in it.
4253 ssh_channels
= newtree234(ssh_channelcmp
);
4254 mainchan
= smalloc(sizeof(struct ssh_channel
));
4255 mainchan
->localid
= alloc_channel_id();
4256 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
4257 ssh2_pkt_addstring("session");
4258 ssh2_pkt_adduint32(mainchan
->localid
);
4259 mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4260 ssh2_pkt_adduint32(mainchan
->v
.v2
.locwindow
); /* our window size */
4261 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4263 crWaitUntilV(ispkt
);
4264 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4265 bombout(("Server refused to open a session"));
4267 /* FIXME: error data comes back in FAILURE packet */
4269 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
4270 bombout(("Server's channel confirmation cited wrong channel"));
4273 mainchan
->remoteid
= ssh2_pkt_getuint32();
4274 mainchan
->type
= CHAN_MAINSESSION
;
4275 mainchan
->closes
= 0;
4276 mainchan
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4277 mainchan
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4278 bufchain_init(&mainchan
->v
.v2
.outbuffer
);
4279 add234(ssh_channels
, mainchan
);
4280 logevent("Opened channel for session");
4283 * Potentially enable X11 forwarding.
4285 if (cfg
.x11_forward
) {
4286 char proto
[20], data
[64];
4287 logevent("Requesting X11 forwarding");
4288 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
4289 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4290 ssh2_pkt_adduint32(mainchan
->remoteid
);
4291 ssh2_pkt_addstring("x11-req");
4292 ssh2_pkt_addbool(1); /* want reply */
4293 ssh2_pkt_addbool(0); /* many connections */
4294 ssh2_pkt_addstring(proto
);
4295 ssh2_pkt_addstring(data
);
4296 ssh2_pkt_adduint32(0); /* screen number */
4300 crWaitUntilV(ispkt
);
4301 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4302 unsigned i
= ssh2_pkt_getuint32();
4303 struct ssh_channel
*c
;
4304 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4306 continue; /* nonexistent channel */
4307 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4309 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4311 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4312 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4313 bombout(("Server got confused by X11 forwarding request"));
4316 logevent("X11 forwarding refused");
4318 logevent("X11 forwarding enabled");
4319 ssh_X11_fwd_enabled
= TRUE
;
4324 * Enable port forwardings.
4327 static char *e
; /* preserve across crReturn */
4331 char sports
[256], dports
[256], host
[256];
4334 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4335 /* Add port forwardings. */
4340 while (*e
&& *e
!= '\t')
4346 while (*e
&& *e
!= ':')
4356 dport
= atoi(dports
);
4357 sport
= atoi(sports
);
4358 if (sport
&& dport
) {
4360 pfd_addforward(host
, dport
, sport
);
4361 sprintf(buf
, "Local port %d forwarding to %s:%d",
4362 sport
, host
, dport
);
4365 struct ssh_rportfwd
*pf
;
4366 pf
= smalloc(sizeof(*pf
));
4367 strcpy(pf
->dhost
, host
);
4370 if (add234(ssh_rportfwds
, pf
) != pf
) {
4372 "Duplicate remote port forwarding to %s:%d",
4377 sprintf(buf
, "Requesting remote port %d (forwarded to %s:%d)",
4378 sport
, host
, dport
);
4380 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4381 ssh2_pkt_addstring("tcpip-forward");
4382 ssh2_pkt_addbool(1);/* want reply */
4383 ssh2_pkt_addstring("127.0.0.1");
4384 ssh2_pkt_adduint32(sport
);
4388 crWaitUntilV(ispkt
);
4389 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4390 unsigned i
= ssh2_pkt_getuint32();
4391 struct ssh_channel
*c
;
4392 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4394 continue;/* nonexistent channel */
4395 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4397 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4399 if (pktin
.type
!= SSH2_MSG_REQUEST_SUCCESS
) {
4400 if (pktin
.type
!= SSH2_MSG_REQUEST_FAILURE
) {
4401 bombout(("Server got confused by port forwarding request"));
4404 logevent("Server refused this port forwarding");
4406 logevent("Remote port forwarding enabled");
4415 * Potentially enable agent forwarding.
4417 if (cfg
.agentfwd
&& agent_exists()) {
4418 logevent("Requesting OpenSSH-style agent forwarding");
4419 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4420 ssh2_pkt_adduint32(mainchan
->remoteid
);
4421 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4422 ssh2_pkt_addbool(1); /* want reply */
4426 crWaitUntilV(ispkt
);
4427 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4428 unsigned i
= ssh2_pkt_getuint32();
4429 struct ssh_channel
*c
;
4430 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4432 continue; /* nonexistent channel */
4433 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4435 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4437 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4438 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4440 ("Server got confused by agent forwarding request"));
4443 logevent("Agent forwarding refused");
4445 logevent("Agent forwarding enabled");
4446 ssh_agentfwd_enabled
= TRUE
;
4451 * Now allocate a pty for the session.
4454 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4455 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4456 ssh2_pkt_addstring("pty-req");
4457 ssh2_pkt_addbool(1); /* want reply */
4458 ssh2_pkt_addstring(cfg
.termtype
);
4459 ssh2_pkt_adduint32(cols
);
4460 ssh2_pkt_adduint32(rows
);
4461 ssh2_pkt_adduint32(0); /* pixel width */
4462 ssh2_pkt_adduint32(0); /* pixel height */
4463 ssh2_pkt_addstring_start();
4464 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4466 ssh_state
= SSH_STATE_INTERMED
;
4469 crWaitUntilV(ispkt
);
4470 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4471 unsigned i
= ssh2_pkt_getuint32();
4472 struct ssh_channel
*c
;
4473 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4475 continue; /* nonexistent channel */
4476 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4478 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4480 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4481 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4482 bombout(("Server got confused by pty request"));
4485 c_write_str("Server refused to allocate pty\r\n");
4486 ssh_editing
= ssh_echoing
= 1;
4488 logevent("Allocated pty");
4491 ssh_editing
= ssh_echoing
= 1;
4495 * Start a shell or a remote command.
4497 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4498 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4499 if (cfg
.ssh_subsys
) {
4500 ssh2_pkt_addstring("subsystem");
4501 ssh2_pkt_addbool(1); /* want reply */
4502 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
4503 } else if (*cfg
.remote_cmd_ptr
) {
4504 ssh2_pkt_addstring("exec");
4505 ssh2_pkt_addbool(1); /* want reply */
4506 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
4508 ssh2_pkt_addstring("shell");
4509 ssh2_pkt_addbool(1); /* want reply */
4513 crWaitUntilV(ispkt
);
4514 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4515 unsigned i
= ssh2_pkt_getuint32();
4516 struct ssh_channel
*c
;
4517 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4519 continue; /* nonexistent channel */
4520 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4522 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4523 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4524 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4525 bombout(("Server got confused by shell/command request"));
4528 bombout(("Server refused to start a shell/command"));
4531 logevent("Started a shell/command");
4534 ssh_state
= SSH_STATE_SESSION
;
4538 ssh_special(TS_EOF
);
4543 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
4546 static int try_send
;
4550 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
4551 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
4554 unsigned i
= ssh2_pkt_getuint32();
4555 struct ssh_channel
*c
;
4556 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4558 continue; /* nonexistent channel */
4559 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
4560 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
4561 continue; /* extended but not stderr */
4562 ssh2_pkt_getstring(&data
, &length
);
4565 c
->v
.v2
.locwindow
-= length
;
4567 case CHAN_MAINSESSION
:
4569 from_backend(pktin
.type
==
4570 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
4574 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
4577 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
4580 while (length
> 0) {
4581 if (c
->u
.a
.lensofar
< 4) {
4582 int l
= min(4 - c
->u
.a
.lensofar
, length
);
4583 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
4587 c
->u
.a
.lensofar
+= l
;
4589 if (c
->u
.a
.lensofar
== 4) {
4591 4 + GET_32BIT(c
->u
.a
.msglen
);
4592 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
4593 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4595 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
4597 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4599 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
4603 c
->u
.a
.lensofar
+= l
;
4605 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4606 void *reply
, *sentreply
;
4608 agent_query(c
->u
.a
.message
,
4609 c
->u
.a
.totallen
, &reply
,
4614 /* Fake SSH_AGENT_FAILURE. */
4615 sentreply
= "\0\0\0\1\5";
4618 ssh2_add_channel_data(c
, sentreply
,
4623 sfree(c
->u
.a
.message
);
4624 c
->u
.a
.lensofar
= 0;
4631 * If we are not buffering too much data,
4632 * enlarge the window again at the remote side.
4634 if (bufsize
< OUR_V2_WINSIZE
)
4635 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
4637 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
4638 ssh_state
= SSH_STATE_CLOSED
;
4639 logevent("Received disconnect message");
4641 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
4642 continue; /* exit status et al; ignore (FIXME?) */
4643 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
4644 unsigned i
= ssh2_pkt_getuint32();
4645 struct ssh_channel
*c
;
4647 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4649 continue; /* nonexistent channel */
4651 if (c
->type
== CHAN_X11
) {
4653 * Remote EOF on an X11 channel means we should
4654 * wrap up and close the channel ourselves.
4656 x11_close(c
->u
.x11
.s
);
4658 } else if (c
->type
== CHAN_AGENT
) {
4660 } else if (c
->type
== CHAN_SOCKDATA
) {
4661 pfd_close(c
->u
.pfd
.s
);
4664 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
4665 unsigned i
= ssh2_pkt_getuint32();
4666 struct ssh_channel
*c
;
4668 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4670 continue; /* nonexistent channel */
4671 if (c
->closes
== 0) {
4672 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
4673 ssh2_pkt_adduint32(c
->remoteid
);
4676 /* Do pre-close processing on the channel. */
4678 case CHAN_MAINSESSION
:
4679 break; /* nothing to see here, move along */
4687 del234(ssh_channels
, c
);
4688 bufchain_clear(&c
->v
.v2
.outbuffer
);
4692 * See if that was the last channel left open.
4694 if (count234(ssh_channels
) == 0) {
4695 logevent("All channels closed. Disconnecting");
4696 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4697 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4698 ssh2_pkt_addstring("All open channels closed");
4699 ssh2_pkt_addstring("en"); /* language tag */
4701 ssh_state
= SSH_STATE_CLOSED
;
4704 continue; /* remote sends close; ignore (FIXME) */
4705 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4706 unsigned i
= ssh2_pkt_getuint32();
4707 struct ssh_channel
*c
;
4708 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4710 continue; /* nonexistent channel */
4711 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4713 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4714 unsigned i
= ssh2_pkt_getuint32();
4715 struct ssh_channel
*c
;
4716 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4718 continue; /* nonexistent channel */
4719 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
4720 continue; /* dunno why they're confirming this */
4721 c
->remoteid
= ssh2_pkt_getuint32();
4722 c
->type
= CHAN_SOCKDATA
;
4724 c
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4725 c
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4726 bufchain_init(&c
->v
.v2
.outbuffer
);
4727 pfd_confirm(c
->u
.pfd
.s
);
4728 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
4732 struct ssh_channel
*c
;
4733 unsigned remid
, winsize
, pktsize
;
4734 ssh2_pkt_getstring(&type
, &typelen
);
4735 c
= smalloc(sizeof(struct ssh_channel
));
4737 remid
= ssh2_pkt_getuint32();
4738 winsize
= ssh2_pkt_getuint32();
4739 pktsize
= ssh2_pkt_getuint32();
4741 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
4742 if (!ssh_X11_fwd_enabled
)
4743 error
= "X11 forwarding is not enabled";
4744 else if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) !=
4746 error
= "Unable to open an X11 connection";
4750 } else if (typelen
== 15 &&
4751 !memcmp(type
, "forwarded-tcpip", 15)) {
4752 struct ssh_rportfwd pf
, *realpf
;
4755 ssh2_pkt_getstring(&dummy
, &dummylen
);/* skip address */
4756 pf
.sport
= ssh2_pkt_getuint32();
4757 realpf
= find234(ssh_rportfwds
, &pf
, NULL
);
4758 if (realpf
== NULL
) {
4759 error
= "Remote port is not recognised";
4761 char *e
= pfd_newconnect(&c
->u
.pfd
.s
, realpf
->dhost
,
4764 sprintf(buf
, "Received remote port open request for %s:%d",
4765 realpf
->dhost
, realpf
->dport
);
4768 sprintf(buf
, "Port open failed: %s", e
);
4770 error
= "Port open failed";
4772 logevent("Forwarded port opened successfully");
4773 c
->type
= CHAN_SOCKDATA
;
4776 } else if (typelen
== 22 &&
4777 !memcmp(type
, "auth-agent@openssh.com", 3)) {
4778 if (!ssh_agentfwd_enabled
)
4779 error
= "Agent forwarding is not enabled";
4781 c
->type
= CHAN_AGENT
; /* identify channel type */
4782 c
->u
.a
.lensofar
= 0;
4785 error
= "Unsupported channel type requested";
4788 c
->remoteid
= remid
;
4790 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
4791 ssh2_pkt_adduint32(c
->remoteid
);
4792 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
4793 ssh2_pkt_addstring(error
);
4794 ssh2_pkt_addstring("en"); /* language tag */
4798 c
->localid
= alloc_channel_id();
4800 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4801 c
->v
.v2
.remwindow
= winsize
;
4802 c
->v
.v2
.remmaxpkt
= pktsize
;
4803 bufchain_init(&c
->v
.v2
.outbuffer
);
4804 add234(ssh_channels
, c
);
4805 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
4806 ssh2_pkt_adduint32(c
->remoteid
);
4807 ssh2_pkt_adduint32(c
->localid
);
4808 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);
4809 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4813 bombout(("Strange packet received: type %d", pktin
.type
));
4818 * We have spare data. Add it to the channel buffer.
4820 ssh2_add_channel_data(mainchan
, in
, inlen
);
4825 struct ssh_channel
*c
;
4827 * Try to send data on all channels if we can.
4829 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
4830 int bufsize
= ssh2_try_send(c
);
4833 case CHAN_MAINSESSION
:
4834 /* stdin need not receive an unthrottle
4835 * notification since it will be polled */
4838 x11_unthrottle(c
->u
.x11
.s
);
4841 /* agent sockets are request/response and need no
4842 * buffer management */
4845 pfd_unthrottle(c
->u
.pfd
.s
);
4857 * Handle the top-level SSH2 protocol.
4859 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
4861 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
4863 do_ssh2_authconn(in
, inlen
, ispkt
);
4867 * Called to set up the connection.
4869 * Returns an error message, or NULL on success.
4871 static char *ssh_init(char *host
, int port
, char **realhost
)
4876 if (crypto_startup() == 0)
4877 return "Microsoft high encryption pack not installed!";
4883 ssh1_throttle_count
= 0;
4884 ssh_overall_bufsize
= 0;
4886 p
= connect_to_host(host
, port
, realhost
);
4894 * Called to send data down the Telnet connection.
4896 static int ssh_send(char *buf
, int len
)
4898 if (s
== NULL
|| ssh_protocol
== NULL
)
4901 ssh_protocol(buf
, len
, 0);
4903 return ssh_sendbuffer();
4907 * Called to query the current amount of buffered stdin data.
4909 static int ssh_sendbuffer(void)
4913 if (s
== NULL
|| ssh_protocol
== NULL
)
4917 * If the SSH socket itself has backed up, add the total backup
4918 * size on that to any individual buffer on the stdin channel.
4921 if (ssh_throttled_all
)
4922 override_value
= ssh_overall_bufsize
;
4924 if (ssh_version
== 1) {
4925 return override_value
;
4926 } else if (ssh_version
== 2) {
4927 if (!mainchan
|| mainchan
->closes
> 0)
4928 return override_value
;
4930 return override_value
+ bufchain_size(&mainchan
->v
.v2
.outbuffer
);
4937 * Called to set the size of the window from SSH's POV.
4939 static void ssh_size(void)
4941 switch (ssh_state
) {
4942 case SSH_STATE_BEFORE_SIZE
:
4943 case SSH_STATE_PREPACKET
:
4944 case SSH_STATE_CLOSED
:
4945 break; /* do nothing */
4946 case SSH_STATE_INTERMED
:
4947 size_needed
= TRUE
; /* buffer for later */
4949 case SSH_STATE_SESSION
:
4951 if (ssh_version
== 1) {
4952 send_packet(SSH1_CMSG_WINDOW_SIZE
,
4953 PKT_INT
, rows
, PKT_INT
, cols
,
4954 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
4956 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4957 ssh2_pkt_adduint32(mainchan
->remoteid
);
4958 ssh2_pkt_addstring("window-change");
4959 ssh2_pkt_addbool(0);
4960 ssh2_pkt_adduint32(cols
);
4961 ssh2_pkt_adduint32(rows
);
4962 ssh2_pkt_adduint32(0);
4963 ssh2_pkt_adduint32(0);
4972 * Send Telnet special codes. TS_EOF is useful for `plink', so you
4973 * can send an EOF and collect resulting output (e.g. `plink
4976 static void ssh_special(Telnet_Special code
)
4978 if (code
== TS_EOF
) {
4979 if (ssh_state
!= SSH_STATE_SESSION
) {
4981 * Buffer the EOF in case we are pre-SESSION, so we can
4982 * send it as soon as we reach SESSION.
4988 if (ssh_version
== 1) {
4989 send_packet(SSH1_CMSG_EOF
, PKT_END
);
4991 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
4992 ssh2_pkt_adduint32(mainchan
->remoteid
);
4995 logevent("Sent EOF message");
4996 } else if (code
== TS_PING
) {
4997 if (ssh_state
== SSH_STATE_CLOSED
4998 || ssh_state
== SSH_STATE_PREPACKET
) return;
4999 if (ssh_version
== 1) {
5000 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
5002 ssh2_pkt_init(SSH2_MSG_IGNORE
);
5003 ssh2_pkt_addstring_start();
5011 void *new_sock_channel(Socket s
)
5013 struct ssh_channel
*c
;
5014 c
= smalloc(sizeof(struct ssh_channel
));
5017 c
->remoteid
= -1; /* to be set when open confirmed */
5018 c
->localid
= alloc_channel_id();
5020 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
5022 add234(ssh_channels
, c
);
5028 * This is called when stdout/stderr (the entity to which
5029 * from_backend sends data) manages to clear some backlog.
5031 void ssh_unthrottle(int bufsize
)
5033 if (ssh_version
== 1) {
5034 if (bufsize
< SSH1_BUFFER_LIMIT
) {
5035 ssh1_stdout_throttling
= 0;
5039 if (mainchan
&& mainchan
->closes
== 0)
5040 ssh2_set_window(mainchan
, OUR_V2_WINSIZE
- bufsize
);
5044 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
5046 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
5049 sprintf(buf
, "Opening forwarded connection to %.512s:%d", hostname
, port
);
5052 if (ssh_version
== 1) {
5053 send_packet(SSH1_MSG_PORT_OPEN
,
5054 PKT_INT
, c
->localid
,
5057 //PKT_STR, <org:orgport>,
5060 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
5061 ssh2_pkt_addstring("direct-tcpip");
5062 ssh2_pkt_adduint32(c
->localid
);
5063 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5064 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);/* our window size */
5065 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5066 ssh2_pkt_addstring(hostname
);
5067 ssh2_pkt_adduint32(port
);
5069 * We make up values for the originator data; partly it's
5070 * too much hassle to keep track, and partly I'm not
5071 * convinced the server should be told details like that
5072 * about my local network configuration.
5074 ssh2_pkt_addstring("client-side-connection");
5075 ssh2_pkt_adduint32(0);
5081 static Socket
ssh_socket(void)
5086 static int ssh_sendok(void)
5091 static int ssh_ldisc(int option
)
5093 if (option
== LD_ECHO
)
5095 if (option
== LD_EDIT
)
5100 Backend ssh_backend
= {