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
162 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
165 #define GET_32BIT(cp) \
166 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
167 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
168 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
169 ((unsigned long)(unsigned char)(cp)[3]))
171 #define PUT_32BIT(cp, value) { \
172 (cp)[0] = (unsigned char)((value) >> 24); \
173 (cp)[1] = (unsigned char)((value) >> 16); \
174 (cp)[2] = (unsigned char)((value) >> 8); \
175 (cp)[3] = (unsigned char)(value); }
177 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
179 /* Coroutine mechanics for the sillier bits of the code */
180 #define crBegin1 static int crLine = 0;
181 #define crBegin2 switch(crLine) { case 0:;
182 #define crBegin crBegin1; crBegin2;
183 #define crFinish(z) } crLine = 0; return (z)
184 #define crFinishV } crLine = 0; return
185 #define crReturn(z) \
187 crLine=__LINE__; return (z); case __LINE__:;\
191 crLine=__LINE__; return; case __LINE__:;\
193 #define crStop(z) do{ crLine = 0; return (z); }while(0)
194 #define crStopV do{ crLine = 0; return; }while(0)
195 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
196 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
198 extern char *x11_init(Socket *, char *, void *);
199 extern void x11_close(Socket);
200 extern int x11_send(Socket, char *, int);
201 extern void x11_invent_auth(char *, int, char *, int);
202 extern void x11_unthrottle(Socket s);
203 extern void x11_override_throttle(Socket s, int enable);
205 extern char *pfd_newconnect(Socket * s, char *hostname, int port, void *c);
206 extern char *pfd_addforward(char *desthost, int destport, int port);
207 extern void pfd_close(Socket s);
208 extern int pfd_send(Socket s, char *data, int len);
209 extern void pfd_confirm(Socket s);
210 extern void pfd_unthrottle(Socket s);
211 extern void pfd_override_throttle(Socket s, int enable);
214 * Buffer management constants. There are several of these for
215 * various different purposes:
217 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
218 * on a local data stream before we throttle the whole SSH
219 * connection (in SSH1 only). Throttling the whole connection is
220 * pretty drastic so we set this high in the hope it won't
223 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
224 * on the SSH connection itself before we defensively throttle
225 * _all_ local data streams. This is pretty drastic too (though
226 * thankfully unlikely in SSH2 since the window mechanism should
227 * ensure that the server never has any need to throttle its end
228 * of the connection), so we set this high as well.
230 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
234 #define SSH1_BUFFER_LIMIT 32768
235 #define SSH_MAX_BACKLOG 32768
236 #define OUR_V2_WINSIZE 16384
238 const static struct ssh_kex *kex_algs[] = {
239 &ssh_diffiehellman_gex,
243 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
245 static void nullmac_key(unsigned char *key)
248 static void nullmac_generate(unsigned char *blk, int len,
252 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq)
256 const static struct ssh_mac ssh_mac_none = {
257 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
259 const static struct ssh_mac *macs[] = {
260 &ssh_sha1, &ssh_md5, &ssh_mac_none
262 const static struct ssh_mac *buggymacs[] = {
263 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
266 static void ssh_comp_none_init(void)
269 static int ssh_comp_none_block(unsigned char *block, int len,
270 unsigned char **outblock, int *outlen)
274 static int ssh_comp_none_disable(void)
278 const static struct ssh_compress ssh_comp_none = {
280 ssh_comp_none_init, ssh_comp_none_block,
281 ssh_comp_none_init, ssh_comp_none_block,
282 ssh_comp_none_disable
284 extern const struct ssh_compress ssh_zlib;
285 const static struct ssh_compress *compressions[] = {
286 &ssh_zlib, &ssh_comp_none
289 enum { /* channel types */
294 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
298 * 2-3-4 tree storing channels.
301 unsigned remoteid, localid;
305 struct ssh1_data_channel {
308 struct ssh2_data_channel {
310 unsigned remwindow, remmaxpkt;
315 struct ssh_agent_channel {
316 unsigned char *message;
317 unsigned char msglen[4];
318 int lensofar, totallen;
320 struct ssh_x11_channel {
323 struct ssh_pfd_channel {
330 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
331 * 2 use this structure in different ways, reflecting SSH 2's
332 * altogether saner approach to port forwarding.
334 * In SSH 1, you arrange a remote forwarding by sending the server
335 * the remote port number, and the local destination host:port.
336 * When a connection comes in, the server sends you back that
337 * host:port pair, and you connect to it. This is a ready-made
338 * security hole if you're not on the ball: a malicious server
339 * could send you back _any_ host:port pair, so if you trustingly
340 * connect to the address it gives you then you've just opened the
341 * entire inside of your corporate network just by connecting
342 * through it to a dodgy SSH server. Hence, we must store a list of
343 * host:port pairs we _are_ trying to forward to, and reject a
344 * connection request from the server if it's not in the list.
346 * In SSH 2, each side of the connection minds its own business and
347 * doesn't send unnecessary information to the other. You arrange a
348 * remote forwarding by sending the server just the remote port
349 * number. When a connection comes in, the server tells you which
350 * of its ports was connected to; and _you_ have to remember what
351 * local host:port pair went with that port number.
353 * Hence: in SSH 1 this structure stores host:port pairs we intend
354 * to allow connections to, and is indexed by those host:port
355 * pairs. In SSH 2 it stores a mapping from source port to
356 * destination host:port pair, and is indexed by source port.
358 struct ssh_rportfwd {
359 unsigned sport, dport;
372 static SHA_State exhash, exhashbase;
374 static Socket s = NULL;
376 static unsigned char session_key[32];
377 static int ssh1_compressing;
378 static int ssh1_remote_protoflags;
379 static int ssh1_local_protoflags;
380 static int ssh_agentfwd_enabled;
381 static int ssh_X11_fwd_enabled;
382 static int ssh_remote_bugs;
383 static const struct ssh_cipher *cipher = NULL;
384 static const struct ssh2_cipher *cscipher = NULL;
385 static const struct ssh2_cipher *sccipher = NULL;
386 static const struct ssh_mac *csmac = NULL;
387 static const struct ssh_mac *scmac = NULL;
388 static const struct ssh_compress *cscomp = NULL;
389 static const struct ssh_compress *sccomp = NULL;
390 static const struct ssh_kex *kex = NULL;
391 static const struct ssh_signkey *hostkey = NULL;
392 static unsigned char ssh2_session_id[20];
393 int (*ssh_get_line) (const char *prompt, char *str, int maxlen,
396 static char *savedhost;
397 static int savedport;
398 static int ssh_send_ok;
399 static int ssh_echoing, ssh_editing;
401 static tree234 *ssh_channels; /* indexed by local id */
402 static struct ssh_channel *mainchan; /* primary session channel */
404 static tree234 *ssh_rportfwds;
408 SSH_STATE_BEFORE_SIZE,
412 } ssh_state = SSH_STATE_PREPACKET;
414 static int size_needed = FALSE, eof_needed = FALSE;
416 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
417 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
418 static unsigned char *deferred_send_data = NULL;
419 static int deferred_len = 0, deferred_size = 0;
422 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
423 * that fails. This variable is the means by which scp.c can reach
424 * into the SSH code and find out which one it got.
426 int ssh_fallback_cmd = 0;
428 static int ssh_version;
429 static int ssh1_throttle_count;
430 static int ssh_overall_bufsize;
431 static int ssh_throttled_all;
432 static int ssh1_stdout_throttling;
433 static void (*ssh_protocol) (unsigned char *in, int inlen, int ispkt);
434 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
435 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
436 static void ssh_size(void);
437 static void ssh_special(Telnet_Special);
438 static int ssh2_try_send(struct ssh_channel *c);
439 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
441 static void ssh_throttle_all(int enable, int bufsize);
442 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
443 static int (*s_rdpkt) (unsigned char **data, int *datalen);
444 static int ssh_sendbuffer(void);
446 static struct rdpkt1_state_tag {
447 long len, pad, biglen, to_read;
448 unsigned long realcrc, gotcrc;
454 static struct rdpkt2_state_tag {
455 long len, pad, payload, packetlen, maclen;
458 unsigned long incoming_sequence;
461 static int ssh_channelcmp(void *av, void *bv)
463 struct ssh_channel *a = (struct ssh_channel *) av;
464 struct ssh_channel *b = (struct ssh_channel *) bv;
465 if (a->localid < b->localid)
467 if (a->localid > b->localid)
471 static int ssh_channelfind(void *av, void *bv)
473 unsigned *a = (unsigned *) av;
474 struct ssh_channel *b = (struct ssh_channel *) bv;
482 static int ssh_rportcmp_ssh1(void *av, void *bv)
484 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
485 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
487 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
488 return i < 0 ? -1 : +1;
489 if (a->dport > b->dport)
491 if (a->dport < b->dport)
496 static int ssh_rportcmp_ssh2(void *av, void *bv)
498 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
499 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
501 if (a->sport > b->sport)
503 if (a->sport < b->sport)
508 static int alloc_channel_id(void)
510 const unsigned CHANNEL_NUMBER_OFFSET = 256;
511 unsigned low, high, mid;
513 struct ssh_channel *c;
516 * First-fit allocation of channel numbers: always pick the
517 * lowest unused one. To do this, binary-search using the
518 * counted B-tree to find the largest channel ID which is in a
519 * contiguous sequence from the beginning. (Precisely
520 * everything in that sequence must have ID equal to its tree
521 * index plus CHANNEL_NUMBER_OFFSET.)
523 tsize = count234(ssh_channels);
527 while (high - low > 1) {
528 mid = (high + low) / 2;
529 c = index234(ssh_channels, mid);
530 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
531 low = mid; /* this one is fine */
533 high = mid; /* this one is past it */
536 * Now low points to either -1, or the tree index of the
537 * largest ID in the initial sequence.
540 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
541 assert(NULL == find234(ssh_channels, &i, ssh_channelfind));
543 return low + 1 + CHANNEL_NUMBER_OFFSET;
546 static void c_write(char *buf, int len)
548 if ((flags & FLAG_STDERR)) {
550 for (i = 0; i < len; i++)
552 fputc(buf[i], stderr);
555 from_backend(1, buf, len);
558 static void c_write_untrusted(char *buf, int len)
561 for (i = 0; i < len; i++) {
564 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
569 static void c_write_str(char *buf)
571 c_write(buf, strlen(buf));
575 * Collect incoming data in the incoming packet buffer.
576 * Decipher and verify the packet when it is completely read.
577 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
578 * Update the *data and *datalen variables.
579 * Return the additional nr of bytes needed, or 0 when
580 * a complete packet is available.
582 static int ssh1_rdpkt(unsigned char **data, int *datalen)
584 struct rdpkt1_state_tag *st = &rdpkt1_state;
593 for (st->i = st->len = 0; st->i < 4; st->i++) {
594 while ((*datalen) == 0)
596 st->len = (st->len << 8) + **data;
597 (*data)++, (*datalen)--;
600 st->pad = 8 - (st->len % 8);
601 st->biglen = st->len + st->pad;
602 pktin.length = st->len - 5;
604 if (pktin.maxlen < st->biglen) {
605 pktin.maxlen = st->biglen;
606 pktin.data = (pktin.data == NULL ? smalloc(st->biglen + APIEXTRA) :
607 srealloc(pktin.data, st->biglen + APIEXTRA));
609 fatalbox("Out of memory");
612 st->to_read = st->biglen;
614 while (st->to_read > 0) {
615 st->chunk = st->to_read;
616 while ((*datalen) == 0)
617 crReturn(st->to_read);
618 if (st->chunk > (*datalen))
619 st->chunk = (*datalen);
620 memcpy(st->p, *data, st->chunk);
622 *datalen -= st->chunk;
624 st->to_read -= st->chunk;
628 cipher->decrypt(pktin.data, st->biglen);
630 debug(("Got packet len=%d pad=%d\n", st->len, st->pad));
631 dmemdump(pktin.data, st->biglen);
634 st->realcrc = crc32(pktin.data, st->biglen - 4);
635 st->gotcrc = GET_32BIT(pktin.data + st->biglen - 4);
636 if (st->gotcrc != st->realcrc) {
637 bombout(("Incorrect CRC received on packet"));
641 pktin.body = pktin.data + st->pad + 1;
643 if (ssh1_compressing) {
644 unsigned char *decompblk;
647 debug(("Packet payload pre-decompression:\n"));
648 dmemdump(pktin.body - 1, pktin.length + 1);
650 zlib_decompress_block(pktin.body - 1, pktin.length + 1,
651 &decompblk, &decomplen);
653 if (pktin.maxlen < st->pad + decomplen) {
654 pktin.maxlen = st->pad + decomplen;
655 pktin.data = srealloc(pktin.data, pktin.maxlen + APIEXTRA);
656 pktin.body = pktin.data + st->pad + 1;
658 fatalbox("Out of memory");
661 memcpy(pktin.body - 1, decompblk, decomplen);
663 pktin.length = decomplen - 1;
665 debug(("Packet payload post-decompression:\n"));
666 dmemdump(pktin.body - 1, pktin.length + 1);
670 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
671 pktin.type == SSH1_SMSG_STDERR_DATA ||
672 pktin.type == SSH1_MSG_DEBUG ||
673 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
674 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
675 long strlen = GET_32BIT(pktin.body);
676 if (strlen + 4 != pktin.length) {
677 bombout(("Received data packet with bogus string length"));
682 pktin.type = pktin.body[-1];
684 if (pktin.type == SSH1_MSG_DEBUG) {
685 /* log debug message */
687 int strlen = GET_32BIT(pktin.body);
688 strcpy(buf, "Remote: ");
691 memcpy(buf + 8, pktin.body + 4, strlen);
692 buf[8 + strlen] = '\0';
695 } else if (pktin.type == SSH1_MSG_IGNORE) {
700 if (pktin.type == SSH1_MSG_DISCONNECT) {
701 /* log reason code in disconnect message */
703 unsigned msglen = GET_32BIT(pktin.body);
705 strcpy(buf, "Remote sent disconnect: ");
706 nowlen = strlen(buf);
707 if (msglen > sizeof(buf) - nowlen - 1)
708 msglen = sizeof(buf) - nowlen - 1;
709 memcpy(buf + nowlen, pktin.body + 4, msglen);
710 buf[nowlen + msglen] = '\0';
712 bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
719 static int ssh2_rdpkt(unsigned char **data, int *datalen)
721 struct rdpkt2_state_tag *st = &rdpkt2_state;
729 st->cipherblk = sccipher->blksize;
732 if (st->cipherblk < 8)
735 if (pktin.maxlen < st->cipherblk) {
736 pktin.maxlen = st->cipherblk;
739 NULL ? smalloc(st->cipherblk +
740 APIEXTRA) : srealloc(pktin.data,
744 fatalbox("Out of memory");
748 * Acquire and decrypt the first block of the packet. This will
749 * contain the length and padding details.
751 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
752 while ((*datalen) == 0)
753 crReturn(st->cipherblk - st->i);
754 pktin.data[st->i] = *(*data)++;
759 sccipher->decrypt(pktin.data, st->cipherblk);
762 * Now get the length and padding figures.
764 st->len = GET_32BIT(pktin.data);
765 st->pad = pktin.data[4];
768 * This enables us to deduce the payload length.
770 st->payload = st->len - st->pad - 1;
772 pktin.length = st->payload + 5;
775 * So now we can work out the total packet length.
777 st->packetlen = st->len + 4;
778 st->maclen = scmac ? scmac->len : 0;
781 * Adjust memory allocation if packet is too big.
783 if (pktin.maxlen < st->packetlen + st->maclen) {
784 pktin.maxlen = st->packetlen + st->maclen;
787 NULL ? smalloc(pktin.maxlen + APIEXTRA) : srealloc(pktin.data,
792 fatalbox("Out of memory");
796 * Read and decrypt the remainder of the packet.
798 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
800 while ((*datalen) == 0)
801 crReturn(st->packetlen + st->maclen - st->i);
802 pktin.data[st->i] = *(*data)++;
805 /* Decrypt everything _except_ the MAC. */
807 sccipher->decrypt(pktin.data + st->cipherblk,
808 st->packetlen - st->cipherblk);
811 debug(("Got packet len=%d pad=%d\n", st->len, st->pad));
812 dmemdump(pktin.data, st->packetlen);
819 && !scmac->verify(pktin.data, st->len + 4,
820 st->incoming_sequence)) {
821 bombout(("Incorrect MAC received on packet"));
824 st->incoming_sequence++; /* whether or not we MACed */
827 * Decompress packet payload.
830 unsigned char *newpayload;
832 if (sccomp && sccomp->decompress(pktin.data + 5, pktin.length - 5,
833 &newpayload, &newlen)) {
834 if (pktin.maxlen < newlen + 5) {
835 pktin.maxlen = newlen + 5;
838 NULL ? smalloc(pktin.maxlen +
839 APIEXTRA) : srealloc(pktin.data,
843 fatalbox("Out of memory");
845 pktin.length = 5 + newlen;
846 memcpy(pktin.data + 5, newpayload, newlen);
848 debug(("Post-decompression payload:\n"));
849 dmemdump(pktin.data + 5, newlen);
857 pktin.type = pktin.data[5];
859 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
860 goto next_packet; /* FIXME: print DEBUG message */
862 if (pktin.type == SSH2_MSG_DISCONNECT) {
863 /* log reason code in disconnect message */
865 int reason = GET_32BIT(pktin.data + 6);
866 unsigned msglen = GET_32BIT(pktin.data + 10);
868 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
869 sprintf(buf, "Received disconnect message (%s)",
870 ssh2_disconnect_reasons[reason]);
872 sprintf(buf, "Received disconnect message (unknown type %d)",
876 strcpy(buf, "Disconnection message text: ");
877 nowlen = strlen(buf);
878 if (msglen > sizeof(buf) - nowlen - 1)
879 msglen = sizeof(buf) - nowlen - 1;
880 memcpy(buf + nowlen, pktin.data + 14, msglen);
881 buf[nowlen + msglen] = '\0';
883 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
885 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
886 ssh2_disconnect_reasons[reason] : "unknown",
894 static void ssh1_pktout_size(int len)
898 len += 5; /* type and CRC */
902 pktout.length = len - 5;
903 if (pktout.maxlen < biglen) {
904 pktout.maxlen = biglen;
906 /* Allocate enough buffer space for extra block
907 * for MS CryptEncrypt() */
908 pktout.data = (pktout.data == NULL ? smalloc(biglen + 12) :
909 srealloc(pktout.data, biglen + 12));
911 pktout.data = (pktout.data == NULL ? smalloc(biglen + 4) :
912 srealloc(pktout.data, biglen + 4));
915 fatalbox("Out of memory");
917 pktout.body = pktout.data + 4 + pad + 1;
920 static void s_wrpkt_start(int type, int len)
922 ssh1_pktout_size(len);
926 static int s_wrpkt_prepare(void)
928 int pad, len, biglen, i;
931 pktout.body[-1] = pktout.type;
933 if (ssh1_compressing) {
934 unsigned char *compblk;
937 debug(("Packet payload pre-compression:\n"));
938 dmemdump(pktout.body - 1, pktout.length + 1);
940 zlib_compress_block(pktout.body - 1, pktout.length + 1,
942 ssh1_pktout_size(complen - 1);
943 memcpy(pktout.body - 1, compblk, complen);
947 len = pktout.length + 5; /* type and CRC */
951 for (i = 0; i < pad; i++)
952 pktout.data[i + 4] = random_byte();
953 crc = crc32(pktout.data + 4, biglen - 4);
954 PUT_32BIT(pktout.data + biglen, crc);
955 PUT_32BIT(pktout.data, len);
958 debug(("Sending packet len=%d\n", biglen + 4));
959 dmemdump(pktout.data, biglen + 4);
962 cipher->encrypt(pktout.data + 4, biglen);
967 static void s_wrpkt(void)
970 len = s_wrpkt_prepare();
971 backlog = sk_write(s, pktout.data, len);
972 if (backlog > SSH_MAX_BACKLOG)
973 ssh_throttle_all(1, backlog);
976 static void s_wrpkt_defer(void)
979 len = s_wrpkt_prepare();
980 if (deferred_len + len > deferred_size) {
981 deferred_size = deferred_len + len + 128;
982 deferred_send_data = srealloc(deferred_send_data, deferred_size);
984 memcpy(deferred_send_data + deferred_len, pktout.data, len);
989 * Construct a packet with the specified contents.
991 static void construct_packet(int pkttype, va_list ap1, va_list ap2)
993 unsigned char *p, *argp, argchar;
994 unsigned long argint;
995 int pktlen, argtype, arglen;
999 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1002 (void) va_arg(ap1, int);
1006 (void) va_arg(ap1, char);
1010 (void) va_arg(ap1, unsigned char *);
1011 arglen = va_arg(ap1, int);
1015 argp = va_arg(ap1, unsigned char *);
1016 arglen = strlen(argp);
1017 pktlen += 4 + arglen;
1020 bn = va_arg(ap1, Bignum);
1021 pktlen += ssh1_bignum_length(bn);
1028 s_wrpkt_start(pkttype, pktlen);
1031 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1034 argint = va_arg(ap2, int);
1035 PUT_32BIT(p, argint);
1039 argchar = va_arg(ap2, unsigned char);
1044 argp = va_arg(ap2, unsigned char *);
1045 arglen = va_arg(ap2, int);
1046 memcpy(p, argp, arglen);
1050 argp = va_arg(ap2, unsigned char *);
1051 arglen = strlen(argp);
1052 PUT_32BIT(p, arglen);
1053 memcpy(p + 4, argp, arglen);
1057 bn = va_arg(ap2, Bignum);
1058 p += ssh1_write_bignum(p, bn);
1064 static void send_packet(int pkttype, ...)
1067 va_start(ap1, pkttype);
1068 va_start(ap2, pkttype);
1069 construct_packet(pkttype, ap1, ap2);
1073 static void defer_packet(int pkttype, ...)
1076 va_start(ap1, pkttype);
1077 va_start(ap2, pkttype);
1078 construct_packet(pkttype, ap1, ap2);
1082 static int ssh_versioncmp(char *a, char *b)
1085 unsigned long av, bv;
1087 av = strtoul(a, &ae, 10);
1088 bv = strtoul(b, &be, 10);
1090 return (av < bv ? -1 : +1);
1095 av = strtoul(ae, &ae, 10);
1096 bv = strtoul(be, &be, 10);
1098 return (av < bv ? -1 : +1);
1104 * Utility routines for putting an SSH-protocol `string' and
1105 * `uint32' into a SHA state.
1108 static void sha_string(SHA_State * s, void *str, int len)
1110 unsigned char lenblk[4];
1111 PUT_32BIT(lenblk, len);
1112 SHA_Bytes(s, lenblk, 4);
1113 SHA_Bytes(s, str, len);
1116 static void sha_uint32(SHA_State * s, unsigned i)
1118 unsigned char intblk[4];
1119 PUT_32BIT(intblk, i);
1120 SHA_Bytes(s, intblk, 4);
1124 * SSH2 packet construction functions.
1126 static void ssh2_pkt_ensure(int length)
1128 if (pktout.maxlen < length) {
1129 pktout.maxlen = length + 256;
1132 NULL ? smalloc(pktout.maxlen +
1133 APIEXTRA) : srealloc(pktout.data,
1137 fatalbox("Out of memory");
1140 static void ssh2_pkt_adddata(void *data, int len)
1142 pktout.length += len;
1143 ssh2_pkt_ensure(pktout.length);
1144 memcpy(pktout.data + pktout.length - len, data, len);
1146 static void ssh2_pkt_addbyte(unsigned char byte)
1148 ssh2_pkt_adddata(&byte, 1);
1150 static void ssh2_pkt_init(int pkt_type)
1153 ssh2_pkt_addbyte((unsigned char) pkt_type);
1155 static void ssh2_pkt_addbool(unsigned char value)
1157 ssh2_pkt_adddata(&value, 1);
1159 static void ssh2_pkt_adduint32(unsigned long value)
1162 PUT_32BIT(x, value);
1163 ssh2_pkt_adddata(x, 4);
1165 static void ssh2_pkt_addstring_start(void)
1167 ssh2_pkt_adduint32(0);
1168 pktout.savedpos = pktout.length;
1170 static void ssh2_pkt_addstring_str(char *data)
1172 ssh2_pkt_adddata(data, strlen(data));
1173 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1174 pktout.length - pktout.savedpos);
1176 static void ssh2_pkt_addstring_data(char *data, int len)
1178 ssh2_pkt_adddata(data, len);
1179 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1180 pktout.length - pktout.savedpos);
1182 static void ssh2_pkt_addstring(char *data)
1184 ssh2_pkt_addstring_start();
1185 ssh2_pkt_addstring_str(data);
1187 static char *ssh2_mpint_fmt(Bignum b, int *len)
1190 int i, n = (bignum_bitcount(b) + 7) / 8;
1193 fatalbox("out of memory");
1195 for (i = 1; i <= n; i++)
1196 p[i] = bignum_byte(b, n - i);
1198 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1200 memmove(p, p + i, n + 1 - i);
1204 static void ssh2_pkt_addmp(Bignum b)
1208 p = ssh2_mpint_fmt(b, &len);
1209 ssh2_pkt_addstring_start();
1210 ssh2_pkt_addstring_data(p, len);
1215 * Construct an SSH2 final-form packet: compress it, encrypt it,
1216 * put the MAC on it. Final packet, ready to be sent, is stored in
1217 * pktout.data. Total length is returned.
1219 static int ssh2_pkt_construct(void)
1221 int cipherblk, maclen, padding, i;
1222 static unsigned long outgoing_sequence = 0;
1225 * Compress packet payload.
1228 unsigned char *newpayload;
1231 if (cscomp && cscomp != &ssh_comp_none) {
1232 debug(("Pre-compression payload:\n"));
1233 dmemdump(pktout.data + 5, pktout.length - 5);
1236 if (cscomp && cscomp->compress(pktout.data + 5, pktout.length - 5,
1237 &newpayload, &newlen)) {
1239 ssh2_pkt_adddata(newpayload, newlen);
1245 * Add padding. At least four bytes, and must also bring total
1246 * length (minus MAC) up to a multiple of the block size.
1248 cipherblk = cscipher ? cscipher->blksize : 8; /* block size */
1249 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1252 (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
1253 maclen = csmac ? csmac->len : 0;
1254 ssh2_pkt_ensure(pktout.length + padding + maclen);
1255 pktout.data[4] = padding;
1256 for (i = 0; i < padding; i++)
1257 pktout.data[pktout.length + i] = random_byte();
1258 PUT_32BIT(pktout.data, pktout.length + padding - 4);
1260 csmac->generate(pktout.data, pktout.length + padding,
1262 outgoing_sequence++; /* whether or not we MACed */
1265 debug(("Sending packet len=%d\n", pktout.length + padding));
1266 dmemdump(pktout.data, pktout.length + padding);
1270 cscipher->encrypt(pktout.data, pktout.length + padding);
1272 /* Ready-to-send packet starts at pktout.data. We return length. */
1273 return pktout.length + padding + maclen;
1277 * Construct and send an SSH2 packet immediately.
1279 static void ssh2_pkt_send(void)
1283 len = ssh2_pkt_construct();
1284 backlog = sk_write(s, pktout.data, len);
1285 if (backlog > SSH_MAX_BACKLOG)
1286 ssh_throttle_all(1, backlog);
1290 * Construct an SSH2 packet and add it to a deferred data block.
1291 * Useful for sending multiple packets in a single sk_write() call,
1292 * to prevent a traffic-analysing listener from being able to work
1293 * out the length of any particular packet (such as the password
1296 * Note that because SSH2 sequence-numbers its packets, this can
1297 * NOT be used as an m4-style `defer' allowing packets to be
1298 * constructed in one order and sent in another.
1300 static void ssh2_pkt_defer(void)
1302 int len = ssh2_pkt_construct();
1303 if (deferred_len + len > deferred_size) {
1304 deferred_size = deferred_len + len + 128;
1305 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1307 memcpy(deferred_send_data + deferred_len, pktout.data, len);
1308 deferred_len += len;
1312 * Send the whole deferred data block constructed by
1313 * ssh2_pkt_defer() or SSH1's defer_packet().
1315 static void ssh_pkt_defersend(void)
1318 backlog = sk_write(s, deferred_send_data, deferred_len);
1319 deferred_len = deferred_size = 0;
1320 sfree(deferred_send_data);
1321 deferred_send_data = NULL;
1322 if (backlog > SSH_MAX_BACKLOG)
1323 ssh_throttle_all(1, backlog);
1327 void bndebug(char *string, Bignum b)
1331 p = ssh2_mpint_fmt(b, &len);
1332 debug(("%s", string));
1333 for (i = 0; i < len; i++)
1334 debug((" %02x", p[i]));
1340 static void sha_mpint(SHA_State * s, Bignum b)
1344 p = ssh2_mpint_fmt(b, &len);
1345 sha_string(s, p, len);
1350 * SSH2 packet decode functions.
1352 static unsigned long ssh2_pkt_getuint32(void)
1354 unsigned long value;
1355 if (pktin.length - pktin.savedpos < 4)
1356 return 0; /* arrgh, no way to decline (FIXME?) */
1357 value = GET_32BIT(pktin.data + pktin.savedpos);
1358 pktin.savedpos += 4;
1361 static int ssh2_pkt_getbool(void)
1363 unsigned long value;
1364 if (pktin.length - pktin.savedpos < 1)
1365 return 0; /* arrgh, no way to decline (FIXME?) */
1366 value = pktin.data[pktin.savedpos] != 0;
1370 static void ssh2_pkt_getstring(char **p, int *length)
1373 if (pktin.length - pktin.savedpos < 4)
1375 *length = GET_32BIT(pktin.data + pktin.savedpos);
1376 pktin.savedpos += 4;
1377 if (pktin.length - pktin.savedpos < *length)
1379 *p = pktin.data + pktin.savedpos;
1380 pktin.savedpos += *length;
1382 static Bignum ssh2_pkt_getmp(void)
1388 ssh2_pkt_getstring(&p, &length);
1392 bombout(("internal error: Can't handle negative mpints"));
1395 b = bignum_from_bytes(p, length);
1400 * Examine the remote side's version string and compare it against
1401 * a list of known buggy implementations.
1403 static void ssh_detect_bugs(char *vstring)
1405 char *imp; /* pointer to implementation part */
1407 imp += strcspn(imp, "-");
1409 imp += strcspn(imp, "-");
1412 ssh_remote_bugs = 0;
1414 if (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1415 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1416 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")) {
1418 * These versions don't support SSH1_MSG_IGNORE, so we have
1419 * to use a different defence against password length
1422 ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1423 logevent("We believe remote version has SSH1 ignore bug");
1426 if (!strcmp(imp, "Cisco-1.25")) {
1428 * These versions need a plain password sent; they can't
1429 * handle having a null and a random length of data after
1432 ssh_remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1433 logevent("We believe remote version needs a plain SSH1 password");
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 */
1478 vstring = smalloc(vstrsize);
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 vstring[strcspn (vstring, "\r\n")] = '\0'; /* remove end-of-line chars */
1505 sprintf(vlog, "Server version: %s", vstring);
1507 ssh_detect_bugs(vstring);
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 if (ssh_state == SSH_STATE_CLOSED) {
1593 ssh_protocol(NULL, 0, 1);
1594 if (ssh_state == SSH_STATE_CLOSED) {
1604 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1607 ssh_state = SSH_STATE_CLOSED;
1613 /* A socket error has occurred. */
1614 connection_fatal(error_msg);
1616 /* Otherwise, the remote side closed the connection normally. */
1621 static int ssh_receive(Plug plug, int urgent, char *data, int len)
1623 ssh_gotdata(data, len);
1624 if (ssh_state == SSH_STATE_CLOSED) {
1634 static void ssh_sent(Plug plug, int bufsize)
1637 * If the send backlog on the SSH socket itself clears, we
1638 * should unthrottle the whole world if it was throttled.
1640 if (bufsize < SSH_MAX_BACKLOG)
1641 ssh_throttle_all(0, bufsize);
1645 * Connect to specified host and port.
1646 * Returns an error message, or NULL on success.
1647 * Also places the canonical host name into `realhost'. It must be
1648 * freed by the caller.
1650 static char *connect_to_host(char *host, int port, char **realhost, int nodelay)
1652 static struct plug_function_table fn_table = {
1657 }, *fn_table_ptr = &fn_table;
1666 savedhost = smalloc(1 + strlen(host));
1668 fatalbox("Out of memory");
1669 strcpy(savedhost, host);
1672 port = 22; /* default ssh port */
1687 sprintf(buf, "Looking up host \"%.170s\"", host);
1690 addr = sk_namelookup(host, realhost);
1691 if ((err = sk_addr_error(addr)))
1695 *realhost = strdup(FWhost);
1702 char buf[200], addrbuf[100];
1703 sk_getaddr(addr, addrbuf, 100);
1704 sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
1707 s = sk_new(addr, port, 0, 1, nodelay, &fn_table_ptr);
1708 if ((err = sk_socket_error(s)))
1712 sk_write(s, "connect ", 8);
1713 sk_write(s, FWhost, strlen(FWhost));
1716 sprintf(buf, " %d\n", FWport);
1717 sk_write(s, buf, strlen(buf));
1725 * Throttle or unthrottle the SSH connection.
1727 static void ssh1_throttle(int adjust)
1729 int old_count = ssh1_throttle_count;
1730 ssh1_throttle_count += adjust;
1731 assert(ssh1_throttle_count >= 0);
1732 if (ssh1_throttle_count && !old_count) {
1733 sk_set_frozen(s, 1);
1734 } else if (!ssh1_throttle_count && old_count) {
1735 sk_set_frozen(s, 0);
1740 * Throttle or unthrottle _all_ local data streams (for when sends
1741 * on the SSH connection itself back up).
1743 static void ssh_throttle_all(int enable, int bufsize)
1746 struct ssh_channel *c;
1748 if (enable == ssh_throttled_all)
1750 ssh_throttled_all = enable;
1751 ssh_overall_bufsize = bufsize;
1754 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
1756 case CHAN_MAINSESSION:
1758 * This is treated separately, outside the switch.
1762 x11_override_throttle(c->u.x11.s, enable);
1765 /* Agent channels require no buffer management. */
1768 pfd_override_throttle(c->u.x11.s, enable);
1775 * Handle the key exchange and user authentication phases.
1777 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1781 static unsigned char *rsabuf, *keystr1, *keystr2;
1782 unsigned char cookie[8];
1783 struct RSAKey servkey, hostkey;
1784 struct MD5Context md5c;
1785 static unsigned long supported_ciphers_mask, supported_auths_mask;
1786 static int tried_publickey;
1787 static int tis_auth_refused, ccard_auth_refused;
1788 static unsigned char session_id[16];
1789 static int cipher_type;
1790 static char username[100];
1797 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1798 bombout(("Public key packet not received"));
1802 logevent("Received public keys");
1804 memcpy(cookie, pktin.body, 8);
1806 i = makekey(pktin.body + 8, &servkey, &keystr1, 0);
1807 j = makekey(pktin.body + 8 + i, &hostkey, &keystr2, 0);
1810 * Log the host key fingerprint.
1814 logevent("Host key fingerprint is:");
1815 strcpy(logmsg, " ");
1816 hostkey.comment = NULL;
1817 rsa_fingerprint(logmsg + strlen(logmsg),
1818 sizeof(logmsg) - strlen(logmsg), &hostkey);
1822 ssh1_remote_protoflags = GET_32BIT(pktin.body + 8 + i + j);
1823 supported_ciphers_mask = GET_32BIT(pktin.body + 12 + i + j);
1824 supported_auths_mask = GET_32BIT(pktin.body + 16 + i + j);
1826 ssh1_local_protoflags =
1827 ssh1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
1828 ssh1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
1831 MD5Update(&md5c, keystr2, hostkey.bytes);
1832 MD5Update(&md5c, keystr1, servkey.bytes);
1833 MD5Update(&md5c, pktin.body, 8);
1834 MD5Final(session_id, &md5c);
1836 for (i = 0; i < 32; i++)
1837 session_key[i] = random_byte();
1839 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1841 rsabuf = smalloc(len);
1843 fatalbox("Out of memory");
1846 * Verify the host key.
1850 * First format the key into a string.
1852 int len = rsastr_len(&hostkey);
1853 char fingerprint[100];
1854 char *keystr = smalloc(len);
1856 fatalbox("Out of memory");
1857 rsastr_fmt(keystr, &hostkey);
1858 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
1859 verify_ssh_host_key(savedhost, savedport, "rsa", keystr,
1864 for (i = 0; i < 32; i++) {
1865 rsabuf[i] = session_key[i];
1867 rsabuf[i] ^= session_id[i];
1870 if (hostkey.bytes > servkey.bytes) {
1871 rsaencrypt(rsabuf, 32, &servkey);
1872 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1874 rsaencrypt(rsabuf, 32, &hostkey);
1875 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1878 logevent("Encrypted session key");
1881 int cipher_chosen = 0, warn = 0;
1882 char *cipher_string = NULL;
1883 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
1884 int next_cipher = cfg.ssh_cipherlist[i];
1885 if (next_cipher == CIPHER_WARN) {
1886 /* If/when we choose a cipher, warn about it */
1888 } else if (next_cipher == CIPHER_AES) {
1889 /* XXX Probably don't need to mention this. */
1890 logevent("AES not supported in SSH1, skipping");
1892 switch (next_cipher) {
1893 case CIPHER_3DES: cipher_type = SSH_CIPHER_3DES;
1894 cipher_string = "3DES"; break;
1895 case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH;
1896 cipher_string = "Blowfish"; break;
1897 case CIPHER_DES: cipher_type = SSH_CIPHER_DES;
1898 cipher_string = "single-DES"; break;
1900 if (supported_ciphers_mask & (1 << cipher_type))
1904 if (!cipher_chosen) {
1905 if ((supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
1906 bombout(("Server violates SSH 1 protocol by not "
1907 "supporting 3DES encryption"));
1909 /* shouldn't happen */
1910 bombout(("No supported ciphers found"));
1914 /* Warn about chosen cipher if necessary. */
1916 askcipher(cipher_string, 0);
1919 switch (cipher_type) {
1920 case SSH_CIPHER_3DES:
1921 logevent("Using 3DES encryption");
1923 case SSH_CIPHER_DES:
1924 logevent("Using single-DES encryption");
1926 case SSH_CIPHER_BLOWFISH:
1927 logevent("Using Blowfish encryption");
1931 send_packet(SSH1_CMSG_SESSION_KEY,
1932 PKT_CHAR, cipher_type,
1933 PKT_DATA, cookie, 8,
1934 PKT_CHAR, (len * 8) >> 8, PKT_CHAR, (len * 8) & 0xFF,
1935 PKT_DATA, rsabuf, len,
1936 PKT_INT, ssh1_local_protoflags, PKT_END);
1938 logevent("Trying to enable encryption...");
1942 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1943 cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des;
1944 cipher->sesskey(session_key);
1948 if (pktin.type != SSH1_SMSG_SUCCESS) {
1949 bombout(("Encryption not successfully enabled"));
1953 logevent("Successfully started encryption");
1959 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1961 if (!ssh_get_line("login as: ",
1962 username, sizeof(username), FALSE)) {
1964 * get_line failed to get a username.
1967 logevent("No username provided. Abandoning session.");
1968 ssh_state = SSH_STATE_CLOSED;
1972 c_write_str("login as: ");
1975 crWaitUntil(!ispkt);
1977 switch (c = *in++) {
1986 c_write_str("\b \b");
1993 c_write_str("\b \b");
2003 if (((c >= ' ' && c <= '~') ||
2004 ((unsigned char) c >= 160))
2005 && pos < sizeof(username)-1) {
2006 username[pos++] = c;
2012 c_write_str("\r\n");
2013 username[strcspn(username, "\n\r")] = '\0';
2016 strncpy(username, cfg.username, 99);
2017 username[99] = '\0';
2020 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
2022 char userlog[22 + sizeof(username)];
2023 sprintf(userlog, "Sent username \"%s\"", username);
2025 if (flags & FLAG_INTERACTIVE &&
2026 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2027 strcat(userlog, "\r\n");
2028 c_write_str(userlog);
2035 tried_publickey = 0;
2036 tis_auth_refused = ccard_auth_refused = 0;
2038 while (pktin.type == SSH1_SMSG_FAILURE) {
2039 static char password[100];
2040 static char prompt[200];
2043 static int pwpkt_type;
2044 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2046 if (agent_exists()) {
2048 * Attempt RSA authentication using Pageant.
2050 static unsigned char request[5], *response, *p;
2051 static int responselen;
2052 static int i, nkeys;
2053 static int authed = FALSE;
2056 logevent("Pageant is running. Requesting keys.");
2058 /* Request the keys held by the agent. */
2059 PUT_32BIT(request, 1);
2060 request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2061 agent_query(request, 5, &r, &responselen);
2062 response = (unsigned char *) r;
2063 if (response && responselen >= 5 &&
2064 response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2066 nkeys = GET_32BIT(p);
2070 sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
2073 for (i = 0; i < nkeys; i++) {
2074 static struct RSAKey key;
2075 static Bignum challenge;
2076 static char *commentp;
2077 static int commentlen;
2081 sprintf(buf, "Trying Pageant key #%d", i);
2085 p += ssh1_read_bignum(p, &key.exponent);
2086 p += ssh1_read_bignum(p, &key.modulus);
2087 commentlen = GET_32BIT(p);
2091 send_packet(SSH1_CMSG_AUTH_RSA,
2092 PKT_BIGNUM, key.modulus, PKT_END);
2094 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2095 logevent("Key refused");
2098 logevent("Received RSA challenge");
2099 ssh1_read_bignum(pktin.body, &challenge);
2101 char *agentreq, *q, *ret;
2104 len = 1 + 4; /* message type, bit count */
2105 len += ssh1_bignum_length(key.exponent);
2106 len += ssh1_bignum_length(key.modulus);
2107 len += ssh1_bignum_length(challenge);
2108 len += 16; /* session id */
2109 len += 4; /* response format */
2110 agentreq = smalloc(4 + len);
2111 PUT_32BIT(agentreq, len);
2113 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2114 PUT_32BIT(q, bignum_bitcount(key.modulus));
2116 q += ssh1_write_bignum(q, key.exponent);
2117 q += ssh1_write_bignum(q, key.modulus);
2118 q += ssh1_write_bignum(q, challenge);
2119 memcpy(q, session_id, 16);
2121 PUT_32BIT(q, 1); /* response format */
2122 agent_query(agentreq, len + 4, &vret, &retlen);
2126 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2127 logevent("Sending Pageant's response");
2128 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2129 PKT_DATA, ret + 5, 16,
2133 if (pktin.type == SSH1_SMSG_SUCCESS) {
2135 ("Pageant's response accepted");
2136 if (flags & FLAG_VERBOSE) {
2138 ("Authenticated using RSA key \"");
2139 c_write(commentp, commentlen);
2140 c_write_str("\" from agent\r\n");
2145 ("Pageant's response not accepted");
2148 ("Pageant failed to answer challenge");
2152 logevent("No reply received from Pageant");
2155 freebn(key.exponent);
2156 freebn(key.modulus);
2165 if (*cfg.keyfile && !tried_publickey)
2166 pwpkt_type = SSH1_CMSG_AUTH_RSA;
2168 if (cfg.try_tis_auth &&
2169 (supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2170 !tis_auth_refused) {
2171 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2172 logevent("Requested TIS authentication");
2173 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
2175 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2176 logevent("TIS authentication declined");
2177 if (flags & FLAG_INTERACTIVE)
2178 c_write_str("TIS authentication refused.\r\n");
2179 tis_auth_refused = 1;
2182 int challengelen = ((pktin.body[0] << 24) |
2183 (pktin.body[1] << 16) |
2184 (pktin.body[2] << 8) |
2186 logevent("Received TIS challenge");
2187 if (challengelen > sizeof(prompt) - 1)
2188 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2189 memcpy(prompt, pktin.body + 4, challengelen);
2190 /* Prompt heuristic comes from OpenSSH */
2191 strncpy(prompt + challengelen,
2192 memchr(prompt, '\n', challengelen) ?
2193 "": "\r\nResponse: ",
2194 (sizeof prompt) - challengelen);
2195 prompt[(sizeof prompt) - 1] = '\0';
2198 if (cfg.try_tis_auth &&
2199 (supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2200 !ccard_auth_refused) {
2201 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2202 logevent("Requested CryptoCard authentication");
2203 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
2205 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2206 logevent("CryptoCard authentication declined");
2207 c_write_str("CryptoCard authentication refused.\r\n");
2208 ccard_auth_refused = 1;
2211 int challengelen = ((pktin.body[0] << 24) |
2212 (pktin.body[1] << 16) |
2213 (pktin.body[2] << 8) |
2215 logevent("Received CryptoCard challenge");
2216 if (challengelen > sizeof(prompt) - 1)
2217 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2218 memcpy(prompt, pktin.body + 4, challengelen);
2219 strncpy(prompt + challengelen,
2220 memchr(prompt, '\n', challengelen) ?
2221 "" : "\r\nResponse: ",
2222 sizeof(prompt) - challengelen);
2223 prompt[sizeof(prompt) - 1] = '\0';
2226 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2227 sprintf(prompt, "%.90s@%.90s's password: ",
2228 username, savedhost);
2230 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2231 char *comment = NULL;
2232 if (flags & FLAG_VERBOSE)
2233 c_write_str("Trying public key authentication.\r\n");
2234 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2235 if (flags & FLAG_VERBOSE)
2236 c_write_str("No passphrase required.\r\n");
2239 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
2244 * Show password prompt, having first obtained it via a TIS
2245 * or CryptoCard exchange if we're doing TIS or CryptoCard
2249 if (!ssh_get_line(prompt, password, sizeof(password), TRUE)) {
2251 * get_line failed to get a password (for example
2252 * because one was supplied on the command line
2253 * which has already failed to work). Terminate.
2255 send_packet(SSH1_MSG_DISCONNECT,
2256 PKT_STR, "No more passwords available to try",
2258 connection_fatal("Unable to authenticate");
2259 ssh_state = SSH_STATE_CLOSED;
2263 /* Prompt may have come from server. We've munged it a bit, so
2264 * we know it to be zero-terminated at least once. */
2265 c_write_untrusted(prompt, strlen(prompt));
2269 crWaitUntil(!ispkt);
2271 switch (c = *in++) {
2292 if (pos < sizeof(password)-1)
2293 password[pos++] = c;
2297 c_write_str("\r\n");
2301 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2303 * Try public key authentication with the specified
2306 static struct RSAKey pubkey;
2307 static Bignum challenge, response;
2309 static unsigned char buffer[32];
2311 tried_publickey = 1;
2312 i = loadrsakey(cfg.keyfile, &pubkey, password);
2314 c_write_str("Couldn't load private key from ");
2315 c_write_str(cfg.keyfile);
2316 c_write_str(".\r\n");
2317 continue; /* go and try password */
2320 c_write_str("Wrong passphrase.\r\n");
2321 tried_publickey = 0;
2322 continue; /* try again */
2326 * Send a public key attempt.
2328 send_packet(SSH1_CMSG_AUTH_RSA,
2329 PKT_BIGNUM, pubkey.modulus, PKT_END);
2332 if (pktin.type == SSH1_SMSG_FAILURE) {
2333 c_write_str("Server refused our public key.\r\n");
2334 continue; /* go and try password */
2336 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2337 bombout(("Bizarre response to offer of public key"));
2340 ssh1_read_bignum(pktin.body, &challenge);
2341 response = rsadecrypt(challenge, &pubkey);
2342 freebn(pubkey.private_exponent); /* burn the evidence */
2344 for (i = 0; i < 32; i++) {
2345 buffer[i] = bignum_byte(response, 31 - i);
2349 MD5Update(&md5c, buffer, 32);
2350 MD5Update(&md5c, session_id, 16);
2351 MD5Final(buffer, &md5c);
2353 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2354 PKT_DATA, buffer, 16, PKT_END);
2357 if (pktin.type == SSH1_SMSG_FAILURE) {
2358 if (flags & FLAG_VERBOSE)
2360 ("Failed to authenticate with our public key.\r\n");
2361 continue; /* go and try password */
2362 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2364 ("Bizarre response to RSA authentication response"));
2368 break; /* we're through! */
2370 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2372 * Defence against traffic analysis: we send a
2373 * whole bunch of packets containing strings of
2374 * different lengths. One of these strings is the
2375 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2376 * The others are all random data in
2377 * SSH1_MSG_IGNORE packets. This way a passive
2378 * listener can't tell which is the password, and
2379 * hence can't deduce the password length.
2381 * Anybody with a password length greater than 16
2382 * bytes is going to have enough entropy in their
2383 * password that a listener won't find it _that_
2384 * much help to know how long it is. So what we'll
2387 * - if password length < 16, we send 15 packets
2388 * containing string lengths 1 through 15
2390 * - otherwise, we let N be the nearest multiple
2391 * of 8 below the password length, and send 8
2392 * packets containing string lengths N through
2393 * N+7. This won't obscure the order of
2394 * magnitude of the password length, but it will
2395 * introduce a bit of extra uncertainty.
2397 * A few servers (the old 1.2.18 through 1.2.22)
2398 * can't deal with SSH1_MSG_IGNORE. For these
2399 * servers, we need an alternative defence. We make
2400 * use of the fact that the password is interpreted
2401 * as a C string: so we can append a NUL, then some
2404 * One server (a Cisco one) can deal with neither
2405 * SSH1_MSG_IGNORE _nor_ a padded password string.
2406 * For this server we are left with no defences
2407 * against password length sniffing.
2409 if (!(ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2411 * The server can deal with SSH1_MSG_IGNORE, so
2412 * we can use the primary defence.
2414 int bottom, top, pwlen, i;
2417 pwlen = strlen(password);
2419 bottom = 0; /* zero length passwords are OK! :-) */
2422 bottom = pwlen & ~7;
2426 assert(pwlen >= bottom && pwlen <= top);
2428 randomstr = smalloc(top + 1);
2430 for (i = bottom; i <= top; i++) {
2432 defer_packet(pwpkt_type, PKT_STR, password,
2435 for (j = 0; j < i; j++) {
2437 randomstr[j] = random_byte();
2438 } while (randomstr[j] == '\0');
2440 randomstr[i] = '\0';
2441 defer_packet(SSH1_MSG_IGNORE,
2442 PKT_STR, randomstr, PKT_END);
2445 logevent("Sending password with camouflage packets");
2446 ssh_pkt_defersend();
2448 else if (!(ssh_remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2450 * The server can't deal with SSH1_MSG_IGNORE
2451 * but can deal with padded passwords, so we
2452 * can use the secondary defence.
2458 len = strlen(password);
2459 if (len < sizeof(string)) {
2461 strcpy(string, password);
2462 len++; /* cover the zero byte */
2463 while (len < sizeof(string)) {
2464 string[len++] = (char) random_byte();
2469 logevent("Sending length-padded password");
2470 send_packet(pwpkt_type, PKT_INT, len,
2471 PKT_DATA, s, len, PKT_END);
2474 * The server has _both_
2475 * BUG_CHOKES_ON_SSH1_IGNORE and
2476 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2477 * therefore nothing we can do.
2480 len = strlen(password);
2481 logevent("Sending unpadded password");
2482 send_packet(pwpkt_type, PKT_INT, len,
2483 PKT_DATA, password, len, PKT_END);
2486 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
2489 logevent("Sent password");
2490 memset(password, 0, strlen(password));
2492 if (pktin.type == SSH1_SMSG_FAILURE) {
2493 if (flags & FLAG_VERBOSE)
2494 c_write_str("Access denied\r\n");
2495 logevent("Authentication refused");
2496 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2497 logevent("Received disconnect request");
2498 ssh_state = SSH_STATE_CLOSED;
2500 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2501 bombout(("Strange packet received, type %d", pktin.type));
2506 logevent("Authentication successful");
2511 void sshfwd_close(struct ssh_channel *c)
2513 if (c && !c->closes) {
2515 * If the channel's remoteid is -1, we have sent
2516 * CHANNEL_OPEN for this channel, but it hasn't even been
2517 * acknowledged by the server. So we must set a close flag
2518 * on it now, and then when the server acks the channel
2519 * open, we can close it then.
2521 if (c->remoteid != -1) {
2522 if (ssh_version == 1) {
2523 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2526 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2527 ssh2_pkt_adduint32(c->remoteid);
2532 if (c->type == CHAN_X11) {
2534 logevent("Forwarded X11 connection terminated");
2535 } else if (c->type == CHAN_SOCKDATA ||
2536 c->type == CHAN_SOCKDATA_DORMANT) {
2538 logevent("Forwarded port closed");
2543 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2545 if (ssh_version == 1) {
2546 send_packet(SSH1_MSG_CHANNEL_DATA,
2547 PKT_INT, c->remoteid,
2548 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2550 * In SSH1 we can return 0 here - implying that forwarded
2551 * connections are never individually throttled - because
2552 * the only circumstance that can cause throttling will be
2553 * the whole SSH connection backing up, in which case
2554 * _everything_ will be throttled as a whole.
2558 ssh2_add_channel_data(c, buf, len);
2559 return ssh2_try_send(c);
2563 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2565 if (ssh_version == 1) {
2566 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2567 c->v.v1.throttling = 0;
2571 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2575 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt)
2581 while (!do_ssh1_login(in, inlen, ispkt)) {
2584 if (ssh_state == SSH_STATE_CLOSED)
2587 if (cfg.agentfwd && agent_exists()) {
2588 logevent("Requesting agent forwarding");
2589 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2593 if (pktin.type != SSH1_SMSG_SUCCESS
2594 && pktin.type != SSH1_SMSG_FAILURE) {
2595 bombout(("Protocol confusion"));
2597 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2598 logevent("Agent forwarding refused");
2600 logevent("Agent forwarding enabled");
2601 ssh_agentfwd_enabled = TRUE;
2605 if (cfg.x11_forward) {
2606 char proto[20], data[64];
2607 logevent("Requesting X11 forwarding");
2608 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2609 if (ssh1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
2610 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2611 PKT_STR, proto, PKT_STR, data,
2612 PKT_INT, 0, PKT_END);
2614 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2615 PKT_STR, proto, PKT_STR, data, PKT_END);
2620 if (pktin.type != SSH1_SMSG_SUCCESS
2621 && pktin.type != SSH1_SMSG_FAILURE) {
2622 bombout(("Protocol confusion"));
2624 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2625 logevent("X11 forwarding refused");
2627 logevent("X11 forwarding enabled");
2628 ssh_X11_fwd_enabled = TRUE;
2636 char sports[256], dports[256], host[256];
2639 ssh_rportfwds = newtree234(ssh_rportcmp_ssh1);
2640 /* Add port forwardings. */
2645 while (*e && *e != '\t')
2651 while (*e && *e != ':')
2661 dport = atoi(dports);
2662 sport = atoi(sports);
2663 if (sport && dport) {
2665 pfd_addforward(host, dport, sport);
2666 sprintf(buf, "Local port %d forwarding to %s:%d",
2667 sport, host, dport);
2670 struct ssh_rportfwd *pf;
2671 pf = smalloc(sizeof(*pf));
2672 strcpy(pf->dhost, host);
2674 if (add234(ssh_rportfwds, pf) != pf) {
2676 "Duplicate remote port forwarding to %s:%d",
2681 sprintf(buf, "Requesting remote port %d forward to %s:%d",
2682 sport, host, dport);
2684 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST,
2696 send_packet(SSH1_CMSG_REQUEST_PTY,
2697 PKT_STR, cfg.termtype,
2698 PKT_INT, rows, PKT_INT, cols,
2699 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
2700 ssh_state = SSH_STATE_INTERMED;
2704 if (pktin.type != SSH1_SMSG_SUCCESS
2705 && pktin.type != SSH1_SMSG_FAILURE) {
2706 bombout(("Protocol confusion"));
2708 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2709 c_write_str("Server refused to allocate pty\r\n");
2710 ssh_editing = ssh_echoing = 1;
2712 logevent("Allocated pty");
2714 ssh_editing = ssh_echoing = 1;
2717 if (cfg.compression) {
2718 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
2722 if (pktin.type != SSH1_SMSG_SUCCESS
2723 && pktin.type != SSH1_SMSG_FAILURE) {
2724 bombout(("Protocol confusion"));
2726 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2727 c_write_str("Server refused to compress\r\n");
2729 logevent("Started compression");
2730 ssh1_compressing = TRUE;
2731 zlib_compress_init();
2732 zlib_decompress_init();
2736 * Start the shell or command.
2738 * Special case: if the first-choice command is an SSH2
2739 * subsystem (hence not usable here) and the second choice
2740 * exists, we fall straight back to that.
2743 char *cmd = cfg.remote_cmd_ptr;
2745 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
2746 cmd = cfg.remote_cmd_ptr2;
2747 ssh_fallback_cmd = TRUE;
2750 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
2752 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
2753 logevent("Started session");
2756 ssh_state = SSH_STATE_SESSION;
2760 ssh_special(TS_EOF);
2762 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
2764 ssh_channels = newtree234(ssh_channelcmp);
2768 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
2769 pktin.type == SSH1_SMSG_STDERR_DATA) {
2770 long len = GET_32BIT(pktin.body);
2772 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
2773 pktin.body + 4, len);
2774 if (!ssh1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
2775 ssh1_stdout_throttling = 1;
2778 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2779 ssh_state = SSH_STATE_CLOSED;
2780 logevent("Received disconnect request");
2782 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
2783 /* Remote side is trying to open a channel to talk to our
2784 * X-Server. Give them back a local channel number. */
2785 struct ssh_channel *c;
2787 logevent("Received X11 connect request");
2788 /* Refuse if X11 forwarding is disabled. */
2789 if (!ssh_X11_fwd_enabled) {
2790 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2791 PKT_INT, GET_32BIT(pktin.body), PKT_END);
2792 logevent("Rejected X11 connect request");
2794 c = smalloc(sizeof(struct ssh_channel));
2796 if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
2797 logevent("opening X11 forward connection failed");
2799 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2800 PKT_INT, GET_32BIT(pktin.body),
2804 ("opening X11 forward connection succeeded");
2805 c->remoteid = GET_32BIT(pktin.body);
2806 c->localid = alloc_channel_id();
2808 c->v.v1.throttling = 0;
2809 c->type = CHAN_X11; /* identify channel type */
2810 add234(ssh_channels, c);
2811 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2812 PKT_INT, c->remoteid, PKT_INT,
2813 c->localid, PKT_END);
2814 logevent("Opened X11 forward channel");
2817 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
2818 /* Remote side is trying to open a channel to talk to our
2819 * agent. Give them back a local channel number. */
2820 struct ssh_channel *c;
2822 /* Refuse if agent forwarding is disabled. */
2823 if (!ssh_agentfwd_enabled) {
2824 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2825 PKT_INT, GET_32BIT(pktin.body), PKT_END);
2827 c = smalloc(sizeof(struct ssh_channel));
2828 c->remoteid = GET_32BIT(pktin.body);
2829 c->localid = alloc_channel_id();
2831 c->v.v1.throttling = 0;
2832 c->type = CHAN_AGENT; /* identify channel type */
2833 c->u.a.lensofar = 0;
2834 add234(ssh_channels, c);
2835 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2836 PKT_INT, c->remoteid, PKT_INT, c->localid,
2839 } else if (pktin.type == SSH1_MSG_PORT_OPEN) {
2840 /* Remote side is trying to open a channel to talk to a
2841 * forwarded port. Give them back a local channel number. */
2842 struct ssh_channel *c;
2843 struct ssh_rportfwd pf;
2845 char host[256], buf[1024];
2847 c = smalloc(sizeof(struct ssh_channel));
2849 hostsize = GET_32BIT(pktin.body+4);
2850 for(h = host, p = pktin.body+8; hostsize != 0; hostsize--) {
2851 if (h+1 < host+sizeof(host))
2856 port = GET_32BIT(p);
2858 strcpy(pf.dhost, host);
2861 if (find234(ssh_rportfwds, &pf, NULL) == NULL) {
2862 sprintf(buf, "Rejected remote port open request for %s:%d",
2865 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2866 PKT_INT, GET_32BIT(pktin.body), PKT_END);
2868 sprintf(buf, "Received remote port open request for %s:%d",
2871 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
2874 sprintf(buf, "Port open failed: %s", e);
2877 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2878 PKT_INT, GET_32BIT(pktin.body),
2881 c->remoteid = GET_32BIT(pktin.body);
2882 c->localid = alloc_channel_id();
2884 c->v.v1.throttling = 0;
2885 c->type = CHAN_SOCKDATA; /* identify channel type */
2886 add234(ssh_channels, c);
2887 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2888 PKT_INT, c->remoteid, PKT_INT,
2889 c->localid, PKT_END);
2890 logevent("Forwarded port opened successfully");
2894 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
2895 unsigned int remoteid = GET_32BIT(pktin.body);
2896 unsigned int localid = GET_32BIT(pktin.body+4);
2897 struct ssh_channel *c;
2899 c = find234(ssh_channels, &remoteid, ssh_channelfind);
2900 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
2901 c->remoteid = localid;
2902 c->type = CHAN_SOCKDATA;
2903 c->v.v1.throttling = 0;
2904 pfd_confirm(c->u.pfd.s);
2907 if (c && c->closes) {
2909 * We have a pending close on this channel,
2910 * which we decided on before the server acked
2911 * the channel open. So now we know the
2912 * remoteid, we can close it again.
2914 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2918 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
2919 unsigned int remoteid = GET_32BIT(pktin.body);
2920 unsigned int localid = GET_32BIT(pktin.body+4);
2921 struct ssh_channel *c;
2923 c = find234(ssh_channels, &remoteid, ssh_channelfind);
2924 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
2925 logevent("Forwarded connection refused by server");
2926 pfd_close(c->u.pfd.s);
2927 del234(ssh_channels, c);
2931 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2932 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
2933 /* Remote side closes a channel. */
2934 unsigned i = GET_32BIT(pktin.body);
2935 struct ssh_channel *c;
2936 c = find234(ssh_channels, &i, ssh_channelfind);
2940 (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2941 if (!(c->closes & closetype))
2942 send_packet(pktin.type, PKT_INT, c->remoteid,
2944 if ((c->closes == 0) && (c->type == CHAN_X11)) {
2945 logevent("Forwarded X11 connection terminated");
2946 assert(c->u.x11.s != NULL);
2947 x11_close(c->u.x11.s);
2950 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
2951 logevent("Forwarded port closed");
2952 assert(c->u.pfd.s != NULL);
2953 pfd_close(c->u.pfd.s);
2956 c->closes |= closetype;
2957 if (c->closes == 3) {
2958 del234(ssh_channels, c);
2962 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2963 /* Data sent down one of our channels. */
2964 int i = GET_32BIT(pktin.body);
2965 int len = GET_32BIT(pktin.body + 4);
2966 unsigned char *p = pktin.body + 8;
2967 struct ssh_channel *c;
2968 c = find234(ssh_channels, &i, ssh_channelfind);
2973 bufsize = x11_send(c->u.x11.s, p, len);
2976 bufsize = pfd_send(c->u.pfd.s, p, len);
2979 /* Data for an agent message. Buffer it. */
2981 if (c->u.a.lensofar < 4) {
2982 int l = min(4 - c->u.a.lensofar, len);
2983 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
2987 c->u.a.lensofar += l;
2989 if (c->u.a.lensofar == 4) {
2991 4 + GET_32BIT(c->u.a.msglen);
2992 c->u.a.message = smalloc(c->u.a.totallen);
2993 memcpy(c->u.a.message, c->u.a.msglen, 4);
2995 if (c->u.a.lensofar >= 4 && len > 0) {
2997 min(c->u.a.totallen - c->u.a.lensofar,
2999 memcpy(c->u.a.message + c->u.a.lensofar, p,
3003 c->u.a.lensofar += l;
3005 if (c->u.a.lensofar == c->u.a.totallen) {
3006 void *reply, *sentreply;
3008 agent_query(c->u.a.message,
3009 c->u.a.totallen, &reply,
3014 /* Fake SSH_AGENT_FAILURE. */
3015 sentreply = "\0\0\0\1\5";
3018 send_packet(SSH1_MSG_CHANNEL_DATA,
3019 PKT_INT, c->remoteid,
3021 PKT_DATA, sentreply, replylen,
3025 sfree(c->u.a.message);
3026 c->u.a.lensofar = 0;
3029 bufsize = 0; /* agent channels never back up */
3032 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3033 c->v.v1.throttling = 1;
3037 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
3038 /* may be from EXEC_SHELL on some servers */
3039 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3040 /* may be from EXEC_SHELL on some servers
3041 * if no pty is available or in other odd cases. Ignore */
3042 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
3043 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3045 * In case `helpful' firewalls or proxies tack
3046 * extra human-readable text on the end of the
3047 * session which we might mistake for another
3048 * encrypted packet, we close the session once
3049 * we've sent EXIT_CONFIRMATION.
3051 ssh_state = SSH_STATE_CLOSED;
3054 bombout(("Strange packet received: type %d", pktin.type));
3059 int len = min(inlen, 512);
3060 send_packet(SSH1_CMSG_STDIN_DATA,
3061 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3072 * Utility routine for decoding comma-separated strings in KEXINIT.
3074 static int in_commasep_string(char *needle, char *haystack, int haylen)
3076 int needlen = strlen(needle);
3079 * Is it at the start of the string?
3081 if (haylen >= needlen && /* haystack is long enough */
3082 !memcmp(needle, haystack, needlen) && /* initial match */
3083 (haylen == needlen || haystack[needlen] == ',')
3084 /* either , or EOS follows */
3088 * If not, search for the next comma and resume after that.
3089 * If no comma found, terminate.
3091 while (haylen > 0 && *haystack != ',')
3092 haylen--, haystack++;
3095 haylen--, haystack++; /* skip over comma itself */
3100 * SSH2 key creation method.
3102 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr,
3106 /* First 20 bytes. */
3109 SHA_Bytes(&s, H, 20);
3110 SHA_Bytes(&s, &chr, 1);
3111 SHA_Bytes(&s, sessid, 20);
3112 SHA_Final(&s, keyspace);
3113 /* Next 20 bytes. */
3116 SHA_Bytes(&s, H, 20);
3117 SHA_Bytes(&s, keyspace, 20);
3118 SHA_Final(&s, keyspace + 20);
3122 * Handle the SSH2 transport layer.
3124 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
3126 static int i, j, len, nbits, pbits, warn;
3128 static Bignum p, g, e, f, K;
3129 static int kex_init_value, kex_reply_value;
3130 static const struct ssh_mac **maclist;
3132 static const struct ssh2_cipher *cscipher_tobe = NULL;
3133 static const struct ssh2_cipher *sccipher_tobe = NULL;
3134 static const struct ssh_mac *csmac_tobe = NULL;
3135 static const struct ssh_mac *scmac_tobe = NULL;
3136 static const struct ssh_compress *cscomp_tobe = NULL;
3137 static const struct ssh_compress *sccomp_tobe = NULL;
3138 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
3139 static int hostkeylen, siglen;
3140 static void *hkey; /* actual host key */
3141 static unsigned char exchange_hash[20];
3142 static unsigned char keyspace[40];
3143 static int n_preferred_ciphers;
3144 static const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3145 static const struct ssh_compress *preferred_comp;
3146 static int cipherstr_started;
3147 static int first_kex;
3154 * Set up the preferred ciphers. (NULL => warn below here)
3156 n_preferred_ciphers = 0;
3157 for (i = 0; i < CIPHER_MAX; i++) {
3158 switch (cfg.ssh_cipherlist[i]) {
3159 case CIPHER_BLOWFISH:
3160 preferred_ciphers[n_preferred_ciphers] = &ssh2_blowfish;
3161 n_preferred_ciphers++;
3164 if (cfg.ssh2_des_cbc) {
3165 preferred_ciphers[n_preferred_ciphers] = &ssh2_des;
3166 n_preferred_ciphers++;
3170 preferred_ciphers[n_preferred_ciphers] = &ssh2_3des;
3171 n_preferred_ciphers++;
3174 preferred_ciphers[n_preferred_ciphers] = &ssh2_aes;
3175 n_preferred_ciphers++;
3178 /* Flag for later. Don't bother if it's the last in
3180 if (i < CIPHER_MAX - 1) {
3181 preferred_ciphers[n_preferred_ciphers] = NULL;
3182 n_preferred_ciphers++;
3189 * Set up preferred compression.
3191 if (cfg.compression)
3192 preferred_comp = &ssh_zlib;
3194 preferred_comp = &ssh_comp_none;
3197 * Be prepared to work around the buggy MAC problem.
3199 if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
3200 maclist = buggymacs, nmacs = lenof(buggymacs);
3202 maclist = macs, nmacs = lenof(macs);
3206 * Construct and send our key exchange packet.
3208 ssh2_pkt_init(SSH2_MSG_KEXINIT);
3209 for (i = 0; i < 16; i++)
3210 ssh2_pkt_addbyte((unsigned char) random_byte());
3211 /* List key exchange algorithms. */
3212 ssh2_pkt_addstring_start();
3213 for (i = 0; i < lenof(kex_algs); i++) {
3214 ssh2_pkt_addstring_str(kex_algs[i]->name);
3215 if (i < lenof(kex_algs) - 1)
3216 ssh2_pkt_addstring_str(",");
3218 /* List server host key algorithms. */
3219 ssh2_pkt_addstring_start();
3220 for (i = 0; i < lenof(hostkey_algs); i++) {
3221 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
3222 if (i < lenof(hostkey_algs) - 1)
3223 ssh2_pkt_addstring_str(",");
3225 /* List client->server encryption algorithms. */
3226 ssh2_pkt_addstring_start();
3227 cipherstr_started = 0;
3228 for (i = 0; i < n_preferred_ciphers; i++) {
3229 const struct ssh2_ciphers *c = preferred_ciphers[i];
3230 if (!c) continue; /* warning flag */
3231 for (j = 0; j < c->nciphers; j++) {
3232 if (cipherstr_started)
3233 ssh2_pkt_addstring_str(",");
3234 ssh2_pkt_addstring_str(c->list[j]->name);
3235 cipherstr_started = 1;
3238 /* List server->client encryption algorithms. */
3239 ssh2_pkt_addstring_start();
3240 cipherstr_started = 0;
3241 for (i = 0; i < n_preferred_ciphers; i++) {
3242 const struct ssh2_ciphers *c = preferred_ciphers[i];
3243 if (!c) continue; /* warning flag */
3244 for (j = 0; j < c->nciphers; j++) {
3245 if (cipherstr_started)
3246 ssh2_pkt_addstring_str(",");
3247 ssh2_pkt_addstring_str(c->list[j]->name);
3248 cipherstr_started = 1;
3251 /* List client->server MAC algorithms. */
3252 ssh2_pkt_addstring_start();
3253 for (i = 0; i < nmacs; i++) {
3254 ssh2_pkt_addstring_str(maclist[i]->name);
3256 ssh2_pkt_addstring_str(",");
3258 /* List server->client MAC algorithms. */
3259 ssh2_pkt_addstring_start();
3260 for (i = 0; i < nmacs; i++) {
3261 ssh2_pkt_addstring_str(maclist[i]->name);
3263 ssh2_pkt_addstring_str(",");
3265 /* List client->server compression algorithms. */
3266 ssh2_pkt_addstring_start();
3267 for (i = 0; i < lenof(compressions) + 1; i++) {
3268 const struct ssh_compress *c =
3269 i == 0 ? preferred_comp : compressions[i - 1];
3270 ssh2_pkt_addstring_str(c->name);
3271 if (i < lenof(compressions))
3272 ssh2_pkt_addstring_str(",");
3274 /* List server->client compression algorithms. */
3275 ssh2_pkt_addstring_start();
3276 for (i = 0; i < lenof(compressions) + 1; i++) {
3277 const struct ssh_compress *c =
3278 i == 0 ? preferred_comp : compressions[i - 1];
3279 ssh2_pkt_addstring_str(c->name);
3280 if (i < lenof(compressions))
3281 ssh2_pkt_addstring_str(",");
3283 /* List client->server languages. Empty list. */
3284 ssh2_pkt_addstring_start();
3285 /* List server->client languages. Empty list. */
3286 ssh2_pkt_addstring_start();
3287 /* First KEX packet does _not_ follow, because we're not that brave. */
3288 ssh2_pkt_addbool(FALSE);
3290 ssh2_pkt_adduint32(0);
3292 exhash = exhashbase;
3293 sha_string(&exhash, pktout.data + 5, pktout.length - 5);
3299 sha_string(&exhash, pktin.data + 5, pktin.length - 5);
3302 * Now examine the other side's KEXINIT to see what we're up
3305 if (pktin.type != SSH2_MSG_KEXINIT) {
3306 bombout(("expected key exchange packet from server"));
3311 cscipher_tobe = NULL;
3312 sccipher_tobe = NULL;
3317 pktin.savedpos += 16; /* skip garbage cookie */
3318 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
3319 for (i = 0; i < lenof(kex_algs); i++) {
3320 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3325 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
3326 for (i = 0; i < lenof(hostkey_algs); i++) {
3327 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3328 hostkey = hostkey_algs[i];
3332 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
3334 for (i = 0; i < n_preferred_ciphers; i++) {
3335 const struct ssh2_ciphers *c = preferred_ciphers[i];
3339 for (j = 0; j < c->nciphers; j++) {
3340 if (in_commasep_string(c->list[j]->name, str, len)) {
3341 cscipher_tobe = c->list[j];
3346 if (cscipher_tobe) {
3348 askcipher(cscipher_tobe->name, 1);
3352 if (!cscipher_tobe) {
3353 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str));
3357 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
3359 for (i = 0; i < n_preferred_ciphers; i++) {
3360 const struct ssh2_ciphers *c = preferred_ciphers[i];
3364 for (j = 0; j < c->nciphers; j++) {
3365 if (in_commasep_string(c->list[j]->name, str, len)) {
3366 sccipher_tobe = c->list[j];
3371 if (sccipher_tobe) {
3373 askcipher(sccipher_tobe->name, 2);
3377 if (!sccipher_tobe) {
3378 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str));
3382 ssh2_pkt_getstring(&str, &len); /* client->server mac */
3383 for (i = 0; i < nmacs; i++) {
3384 if (in_commasep_string(maclist[i]->name, str, len)) {
3385 csmac_tobe = maclist[i];
3389 ssh2_pkt_getstring(&str, &len); /* server->client mac */
3390 for (i = 0; i < nmacs; i++) {
3391 if (in_commasep_string(maclist[i]->name, str, len)) {
3392 scmac_tobe = maclist[i];
3396 ssh2_pkt_getstring(&str, &len); /* client->server compression */
3397 for (i = 0; i < lenof(compressions) + 1; i++) {
3398 const struct ssh_compress *c =
3399 i == 0 ? preferred_comp : compressions[i - 1];
3400 if (in_commasep_string(c->name, str, len)) {
3405 ssh2_pkt_getstring(&str, &len); /* server->client compression */
3406 for (i = 0; i < lenof(compressions) + 1; i++) {
3407 const struct ssh_compress *c =
3408 i == 0 ? preferred_comp : compressions[i - 1];
3409 if (in_commasep_string(c->name, str, len)) {
3416 * Work out the number of bits of key we will need from the key
3417 * exchange. We start with the maximum key length of either
3423 csbits = cscipher_tobe->keylen;
3424 scbits = sccipher_tobe->keylen;
3425 nbits = (csbits > scbits ? csbits : scbits);
3427 /* The keys only have 160-bit entropy, since they're based on
3428 * a SHA-1 hash. So cap the key size at 160 bits. */
3433 * If we're doing Diffie-Hellman group exchange, start by
3434 * requesting a group.
3436 if (kex == &ssh_diffiehellman_gex) {
3437 logevent("Doing Diffie-Hellman group exchange");
3439 * Work out how big a DH group we will need to allow that
3442 pbits = 512 << ((nbits - 1) / 64);
3443 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
3444 ssh2_pkt_adduint32(pbits);
3448 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3449 bombout(("expected key exchange group packet from server"));
3452 p = ssh2_pkt_getmp();
3453 g = ssh2_pkt_getmp();
3454 dh_setup_group(p, g);
3455 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3456 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3459 kex_init_value = SSH2_MSG_KEXDH_INIT;
3460 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3463 logevent("Doing Diffie-Hellman key exchange");
3465 * Now generate and send e for Diffie-Hellman.
3467 e = dh_create_e(nbits * 2);
3468 ssh2_pkt_init(kex_init_value);
3473 if (pktin.type != kex_reply_value) {
3474 bombout(("expected key exchange reply packet from server"));
3477 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
3478 f = ssh2_pkt_getmp();
3479 ssh2_pkt_getstring(&sigdata, &siglen);
3483 sha_string(&exhash, hostkeydata, hostkeylen);
3484 if (kex == &ssh_diffiehellman_gex) {
3485 sha_uint32(&exhash, pbits);
3486 sha_mpint(&exhash, p);
3487 sha_mpint(&exhash, g);
3489 sha_mpint(&exhash, e);
3490 sha_mpint(&exhash, f);
3491 sha_mpint(&exhash, K);
3492 SHA_Final(&exhash, exchange_hash);
3497 debug(("Exchange hash is:\n"));
3498 dmemdump(exchange_hash, 20);
3501 hkey = hostkey->newkey(hostkeydata, hostkeylen);
3503 !hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
3504 bombout(("Server's host key did not match the signature supplied"));
3509 * Authenticate remote host: verify host key. (We've already
3510 * checked the signature of the exchange hash.)
3512 keystr = hostkey->fmtkey(hkey);
3513 fingerprint = hostkey->fingerprint(hkey);
3514 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
3515 keystr, fingerprint);
3516 if (first_kex) { /* don't bother logging this in rekeys */
3517 logevent("Host key fingerprint is:");
3518 logevent(fingerprint);
3522 hostkey->freekey(hkey);
3525 * Send SSH2_MSG_NEWKEYS.
3527 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
3531 * Expect SSH2_MSG_NEWKEYS from server.
3534 if (pktin.type != SSH2_MSG_NEWKEYS) {
3535 bombout(("expected new-keys packet from server"));
3540 * Create and initialise session keys.
3542 cscipher = cscipher_tobe;
3543 sccipher = sccipher_tobe;
3546 cscomp = cscomp_tobe;
3547 sccomp = sccomp_tobe;
3548 cscomp->compress_init();
3549 sccomp->decompress_init();
3551 * Set IVs after keys. Here we use the exchange hash from the
3552 * _first_ key exchange.
3555 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
3556 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
3557 cscipher->setcskey(keyspace);
3558 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
3559 sccipher->setsckey(keyspace);
3560 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
3561 cscipher->setcsiv(keyspace);
3562 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
3563 sccipher->setsciv(keyspace);
3564 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
3565 csmac->setcskey(keyspace);
3566 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
3567 scmac->setsckey(keyspace);
3570 * If this is the first key exchange phase, we must pass the
3571 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3572 * wants to see it but because it will need time to initialise
3573 * itself before it sees an actual packet. In subsequent key
3574 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3575 * it would only confuse the layer above.
3583 * Now we're encrypting. Begin returning 1 to the protocol main
3584 * function so that other things can run on top of the
3585 * transport. If we ever see a KEXINIT, we must go back to the
3588 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
3591 logevent("Server initiated key re-exchange");
3592 goto begin_key_exchange;
3598 * Add data to an SSH2 channel output buffer.
3600 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
3603 bufchain_add(&c->v.v2.outbuffer, buf, len);
3607 * Attempt to send data on an SSH2 channel.
3609 static int ssh2_try_send(struct ssh_channel *c)
3611 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
3614 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
3615 if ((unsigned)len > c->v.v2.remwindow)
3616 len = c->v.v2.remwindow;
3617 if ((unsigned)len > c->v.v2.remmaxpkt)
3618 len = c->v.v2.remmaxpkt;
3619 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
3620 ssh2_pkt_adduint32(c->remoteid);
3621 ssh2_pkt_addstring_start();
3622 ssh2_pkt_addstring_data(data, len);
3624 bufchain_consume(&c->v.v2.outbuffer, len);
3625 c->v.v2.remwindow -= len;
3629 * After having sent as much data as we can, return the amount
3632 return bufchain_size(&c->v.v2.outbuffer);
3636 * Potentially enlarge the window on an SSH2 channel.
3638 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
3640 if (newwin > c->v.v2.locwindow) {
3641 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3642 ssh2_pkt_adduint32(c->remoteid);
3643 ssh2_pkt_adduint32(newwin - c->v.v2.locwindow);
3645 c->v.v2.locwindow = newwin;
3650 * Handle the SSH2 userauth and connection layers.
3652 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
3655 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
3657 AUTH_KEYBOARD_INTERACTIVE
3661 AUTH_TYPE_PUBLICKEY,
3662 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
3663 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
3665 AUTH_TYPE_KEYBOARD_INTERACTIVE,
3666 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
3668 static int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
3669 static int tried_pubkey_config, tried_agent, tried_keyb_inter;
3670 static int kbd_inter_running;
3671 static int we_are_in;
3672 static int num_prompts, echo;
3673 static char username[100];
3674 static char pwprompt[200];
3675 static char password[100];
3680 * Request userauth protocol, and await a response to it.
3682 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
3683 ssh2_pkt_addstring("ssh-userauth");
3685 crWaitUntilV(ispkt);
3686 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
3687 bombout(("Server refused user authentication protocol"));
3692 * We repeat this whole loop, including the username prompt,
3693 * until we manage a successful authentication. If the user
3694 * types the wrong _password_, they are sent back to the
3695 * beginning to try another username. (If they specify a
3696 * username in the config, they are never asked, even if they
3697 * do give a wrong password.)
3699 * I think this best serves the needs of
3701 * - the people who have no configuration, no keys, and just
3702 * want to try repeated (username,password) pairs until they
3703 * type both correctly
3705 * - people who have keys and configuration but occasionally
3706 * need to fall back to passwords
3708 * - people with a key held in Pageant, who might not have
3709 * logged in to a particular machine before; so they want to
3710 * type a username, and then _either_ their key will be
3711 * accepted, _or_ they will type a password. If they mistype
3712 * the username they will want to be able to get back and
3723 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
3725 if (!ssh_get_line("login as: ",
3726 username, sizeof(username), FALSE)) {
3728 * get_line failed to get a username.
3731 logevent("No username provided. Abandoning session.");
3732 ssh_state = SSH_STATE_CLOSED;
3736 c_write_str("login as: ");
3739 crWaitUntilV(!ispkt);
3741 switch (c = *in++) {
3750 c_write_str("\b \b");
3757 c_write_str("\b \b");
3767 if (((c >= ' ' && c <= '~') ||
3768 ((unsigned char) c >= 160))
3769 && pos < sizeof(username)-1) {
3770 username[pos++] = c;
3777 c_write_str("\r\n");
3778 username[strcspn(username, "\n\r")] = '\0';
3781 strncpy(username, cfg.username, 99);
3782 username[99] = '\0';
3783 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3784 sprintf(stuff, "Using username \"%s\".\r\n", username);
3790 * Send an authentication request using method "none": (a)
3791 * just in case it succeeds, and (b) so that we know what
3792 * authentication methods we can usefully try next.
3794 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3795 ssh2_pkt_addstring(username);
3796 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3797 ssh2_pkt_addstring("none"); /* method */
3799 type = AUTH_TYPE_NONE;
3803 tried_pubkey_config = FALSE;
3804 tried_agent = FALSE;
3805 tried_keyb_inter = FALSE;
3806 kbd_inter_running = FALSE;
3810 * Wait for the result of the last authentication request.
3813 crWaitUntilV(ispkt);
3814 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
3818 * Don't show the banner if we're operating in
3819 * non-verbose non-interactive mode. (It's probably
3820 * a script, which means nobody will read the
3821 * banner _anyway_, and moreover the printing of
3822 * the banner will screw up processing on the
3823 * output of (say) plink.)
3825 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
3826 ssh2_pkt_getstring(&banner, &size);
3828 c_write_untrusted(banner, size);
3830 crWaitUntilV(ispkt);
3832 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
3833 logevent("Access granted");
3838 if (kbd_inter_running &&
3839 pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
3841 * This is a further prompt in keyboard-interactive
3842 * authentication. Do nothing.
3844 } else if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
3845 bombout(("Strange packet received during authentication: type %d",
3853 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3854 * we can look at the string in it and know what we can
3855 * helpfully try next.
3857 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
3860 ssh2_pkt_getstring(&methods, &methlen);
3861 kbd_inter_running = FALSE;
3862 if (!ssh2_pkt_getbool()) {
3864 * We have received an unequivocal Access
3865 * Denied. This can translate to a variety of
3868 * - if we'd just tried "none" authentication,
3869 * it's not worth printing anything at all
3871 * - if we'd just tried a public key _offer_,
3872 * the message should be "Server refused our
3873 * key" (or no message at all if the key
3874 * came from Pageant)
3876 * - if we'd just tried anything else, the
3877 * message really should be "Access denied".
3879 * Additionally, if we'd just tried password
3880 * authentication, we should break out of this
3881 * whole loop so as to go back to the username
3884 if (type == AUTH_TYPE_NONE) {
3886 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
3887 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
3888 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
3889 c_write_str("Server refused our key\r\n");
3890 logevent("Server refused public key");
3891 } else if (type == AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
3892 /* server declined keyboard-interactive; ignore */
3894 c_write_str("Access denied\r\n");
3895 logevent("Access denied");
3896 if (type == AUTH_TYPE_PASSWORD) {
3902 c_write_str("Further authentication required\r\n");
3903 logevent("Further authentication required");
3907 in_commasep_string("publickey", methods, methlen);
3909 in_commasep_string("password", methods, methlen);
3910 can_keyb_inter = cfg.try_ki_auth &&
3911 in_commasep_string("keyboard-interactive", methods, methlen);
3916 if (!method && can_pubkey && agent_exists() && !tried_agent) {
3918 * Attempt public-key authentication using Pageant.
3920 static unsigned char request[5], *response, *p;
3921 static int responselen;
3922 static int i, nkeys;
3923 static int authed = FALSE;
3928 logevent("Pageant is running. Requesting keys.");
3930 /* Request the keys held by the agent. */
3931 PUT_32BIT(request, 1);
3932 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
3933 agent_query(request, 5, &r, &responselen);
3934 response = (unsigned char *) r;
3935 if (response && responselen >= 5 &&
3936 response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
3938 nkeys = GET_32BIT(p);
3942 sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
3945 for (i = 0; i < nkeys; i++) {
3946 static char *pkblob, *alg, *commentp;
3947 static int pklen, alglen, commentlen;
3948 static int siglen, retlen, len;
3949 static char *q, *agentreq, *ret;
3954 sprintf(buf, "Trying Pageant key #%d", i);
3957 pklen = GET_32BIT(p);
3961 alglen = GET_32BIT(pkblob);
3963 commentlen = GET_32BIT(p);
3967 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3968 ssh2_pkt_addstring(username);
3969 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3970 ssh2_pkt_addstring("publickey"); /* method */
3971 ssh2_pkt_addbool(FALSE); /* no signature included */
3972 ssh2_pkt_addstring_start();
3973 ssh2_pkt_addstring_data(alg, alglen);
3974 ssh2_pkt_addstring_start();
3975 ssh2_pkt_addstring_data(pkblob, pklen);
3978 crWaitUntilV(ispkt);
3979 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3980 logevent("Key refused");
3984 if (flags & FLAG_VERBOSE) {
3986 ("Authenticating with public key \"");
3987 c_write(commentp, commentlen);
3988 c_write_str("\" from agent\r\n");
3992 * Server is willing to accept the key.
3993 * Construct a SIGN_REQUEST.
3995 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3996 ssh2_pkt_addstring(username);
3997 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3998 ssh2_pkt_addstring("publickey"); /* method */
3999 ssh2_pkt_addbool(TRUE);
4000 ssh2_pkt_addstring_start();
4001 ssh2_pkt_addstring_data(alg, alglen);
4002 ssh2_pkt_addstring_start();
4003 ssh2_pkt_addstring_data(pkblob, pklen);
4005 siglen = pktout.length - 5 + 4 + 20;
4006 len = 1; /* message type */
4007 len += 4 + pklen; /* key blob */
4008 len += 4 + siglen; /* data to sign */
4009 len += 4; /* flags */
4010 agentreq = smalloc(4 + len);
4011 PUT_32BIT(agentreq, len);
4013 *q++ = SSH2_AGENTC_SIGN_REQUEST;
4014 PUT_32BIT(q, pklen);
4016 memcpy(q, pkblob, pklen);
4018 PUT_32BIT(q, siglen);
4020 /* Now the data to be signed... */
4023 memcpy(q, ssh2_session_id, 20);
4025 memcpy(q, pktout.data + 5, pktout.length - 5);
4026 q += pktout.length - 5;
4027 /* And finally the (zero) flags word. */
4029 agent_query(agentreq, len + 4, &vret, &retlen);
4033 if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4034 logevent("Sending Pageant's response");
4035 ssh2_pkt_addstring_start();
4036 ssh2_pkt_addstring_data(ret + 9,
4044 ("Pageant failed to answer challenge");
4054 if (!method && can_pubkey && *cfg.keyfile
4055 && !tried_pubkey_config) {
4056 unsigned char *pub_blob;
4057 char *algorithm, *comment;
4060 tried_pubkey_config = TRUE;
4063 * Try the public key supplied in the configuration.
4065 * First, offer the public blob to see if the server is
4066 * willing to accept it.
4068 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4071 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4072 ssh2_pkt_addstring(username);
4073 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4074 ssh2_pkt_addstring("publickey"); /* method */
4075 ssh2_pkt_addbool(FALSE); /* no signature included */
4076 ssh2_pkt_addstring(algorithm);
4077 ssh2_pkt_addstring_start();
4078 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
4080 logevent("Offered public key"); /* FIXME */
4082 crWaitUntilV(ispkt);
4083 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4085 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4086 continue; /* key refused; give up on it */
4089 logevent("Offer of public key accepted");
4091 * Actually attempt a serious authentication using
4094 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4096 "Passphrase for key \"%.100s\": ",
4102 c_write_str("Authenticating with public key \"");
4103 c_write_str(comment);
4104 c_write_str("\"\r\n");
4105 method = AUTH_PUBLICKEY_FILE;
4109 if (!method && can_keyb_inter && !tried_keyb_inter) {
4110 method = AUTH_KEYBOARD_INTERACTIVE;
4111 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4112 tried_keyb_inter = TRUE;
4114 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4115 ssh2_pkt_addstring(username);
4116 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4117 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4118 ssh2_pkt_addstring(""); /* lang */
4119 ssh2_pkt_addstring("");
4122 crWaitUntilV(ispkt);
4123 if (pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4124 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4126 logevent("Keyboard-interactive authentication refused");
4127 type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4131 kbd_inter_running = TRUE;
4134 if (kbd_inter_running) {
4135 method = AUTH_KEYBOARD_INTERACTIVE;
4136 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4137 tried_keyb_inter = TRUE;
4139 /* We've got packet with that "interactive" info
4140 dump banners, and set its prompt as ours */
4142 char *name, *inst, *lang, *prompt;
4143 int name_len, inst_len, lang_len, prompt_len;
4144 ssh2_pkt_getstring(&name, &name_len);
4145 ssh2_pkt_getstring(&inst, &inst_len);
4146 ssh2_pkt_getstring(&lang, &lang_len);
4148 c_write_untrusted(name, name_len);
4150 c_write_untrusted(inst, inst_len);
4151 num_prompts = ssh2_pkt_getuint32();
4153 ssh2_pkt_getstring(&prompt, &prompt_len);
4154 strncpy(pwprompt, prompt, sizeof(pwprompt));
4155 pwprompt[prompt_len < sizeof(pwprompt) ?
4156 prompt_len : sizeof(pwprompt)-1] = '\0';
4159 echo = ssh2_pkt_getbool();
4163 if (!method && can_passwd) {
4164 method = AUTH_PASSWORD;
4165 sprintf(pwprompt, "%.90s@%.90s's password: ", username,
4172 if (!ssh_get_line(pwprompt, password,
4173 sizeof(password), TRUE)) {
4175 * get_line failed to get a password (for
4176 * example because one was supplied on the
4177 * command line which has already failed to
4180 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4181 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4183 ("No more passwords available to try");
4184 ssh2_pkt_addstring("en"); /* language tag */
4186 connection_fatal("Unable to authenticate");
4187 ssh_state = SSH_STATE_CLOSED;
4194 c_write_untrusted(pwprompt, strlen(pwprompt));
4199 crWaitUntilV(!ispkt);
4201 switch (c = *in++) {
4222 if (pos < sizeof(password)-1)
4223 password[pos++] = c;
4227 c_write_str("\r\n");
4231 if (method == AUTH_PUBLICKEY_FILE) {
4233 * We have our passphrase. Now try the actual authentication.
4235 struct ssh2_userkey *key;
4237 key = ssh2_load_userkey(cfg.keyfile, password);
4238 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4239 if (key == SSH2_WRONG_PASSPHRASE) {
4240 c_write_str("Wrong passphrase\r\n");
4241 tried_pubkey_config = FALSE;
4243 c_write_str("Unable to load private key\r\n");
4244 tried_pubkey_config = TRUE;
4246 /* Send a spurious AUTH_NONE to return to the top. */
4247 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4248 ssh2_pkt_addstring(username);
4249 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4250 ssh2_pkt_addstring("none"); /* method */
4252 type = AUTH_TYPE_NONE;
4254 unsigned char *blob, *sigdata;
4255 int blob_len, sigdata_len;
4258 * We have loaded the private key and the server
4259 * has announced that it's willing to accept it.
4260 * Hallelujah. Generate a signature and send it.
4262 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4263 ssh2_pkt_addstring(username);
4264 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4265 ssh2_pkt_addstring("publickey"); /* method */
4266 ssh2_pkt_addbool(TRUE);
4267 ssh2_pkt_addstring(key->alg->name);
4268 blob = key->alg->public_blob(key->data, &blob_len);
4269 ssh2_pkt_addstring_start();
4270 ssh2_pkt_addstring_data(blob, blob_len);
4274 * The data to be signed is:
4278 * followed by everything so far placed in the
4281 sigdata_len = pktout.length - 5 + 4 + 20;
4282 sigdata = smalloc(sigdata_len);
4283 PUT_32BIT(sigdata, 20);
4284 memcpy(sigdata + 4, ssh2_session_id, 20);
4285 memcpy(sigdata + 24, pktout.data + 5,
4288 key->alg->sign(key->data, sigdata, sigdata_len,
4290 ssh2_pkt_addstring_start();
4291 ssh2_pkt_addstring_data(blob, blob_len);
4296 type = AUTH_TYPE_PUBLICKEY;
4298 } else if (method == AUTH_PASSWORD) {
4300 * We send the password packet lumped tightly together with
4301 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4302 * string long enough to make the total length of the two
4303 * packets constant. This should ensure that a passive
4304 * listener doing traffic analyis can't work out the length
4307 * For this to work, we need an assumption about the
4308 * maximum length of the password packet. I think 256 is
4309 * pretty conservative. Anyone using a password longer than
4310 * that probably doesn't have much to worry about from
4311 * people who find out how long their password is!
4313 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4314 ssh2_pkt_addstring(username);
4315 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4316 ssh2_pkt_addstring("password");
4317 ssh2_pkt_addbool(FALSE);
4318 ssh2_pkt_addstring(password);
4321 * We'll include a string that's an exact multiple of the
4322 * cipher block size. If the cipher is NULL for some
4323 * reason, we don't do this trick at all because we gain
4329 stringlen = (256 - deferred_len);
4330 stringlen += cscipher->blksize - 1;
4331 stringlen -= (stringlen % cscipher->blksize);
4334 * Temporarily disable actual compression,
4335 * so we can guarantee to get this string
4336 * exactly the length we want it. The
4337 * compression-disabling routine should
4338 * return an integer indicating how many
4339 * bytes we should adjust our string length
4342 stringlen -= cscomp->disable_compression();
4344 ssh2_pkt_init(SSH2_MSG_IGNORE);
4345 ssh2_pkt_addstring_start();
4346 for (i = 0; i < stringlen; i++) {
4347 char c = (char) random_byte();
4348 ssh2_pkt_addstring_data(&c, 1);
4352 ssh_pkt_defersend();
4353 logevent("Sent password");
4354 type = AUTH_TYPE_PASSWORD;
4355 } else if (method == AUTH_KEYBOARD_INTERACTIVE) {
4356 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
4357 ssh2_pkt_adduint32(num_prompts);
4358 ssh2_pkt_addstring(password);
4359 memset(password, 0, sizeof(password));
4361 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4364 ("No supported authentication methods left to try!\r\n");
4366 ("No supported authentications offered. Disconnecting");
4367 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4368 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4370 ("No supported authentication methods available");
4371 ssh2_pkt_addstring("en"); /* language tag */
4373 ssh_state = SSH_STATE_CLOSED;
4377 } while (!we_are_in);
4380 * Now we're authenticated for the connection protocol. The
4381 * connection protocol will automatically have started at this
4382 * point; there's no need to send SERVICE_REQUEST.
4386 * So now create a channel with a session in it.
4388 ssh_channels = newtree234(ssh_channelcmp);
4389 mainchan = smalloc(sizeof(struct ssh_channel));
4390 mainchan->localid = alloc_channel_id();
4391 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
4392 ssh2_pkt_addstring("session");
4393 ssh2_pkt_adduint32(mainchan->localid);
4394 mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
4395 ssh2_pkt_adduint32(mainchan->v.v2.locwindow); /* our window size */
4396 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
4398 crWaitUntilV(ispkt);
4399 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4400 bombout(("Server refused to open a session"));
4402 /* FIXME: error data comes back in FAILURE packet */
4404 if (ssh2_pkt_getuint32() != mainchan->localid) {
4405 bombout(("Server's channel confirmation cited wrong channel"));
4408 mainchan->remoteid = ssh2_pkt_getuint32();
4409 mainchan->type = CHAN_MAINSESSION;
4410 mainchan->closes = 0;
4411 mainchan->v.v2.remwindow = ssh2_pkt_getuint32();
4412 mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4413 bufchain_init(&mainchan->v.v2.outbuffer);
4414 add234(ssh_channels, mainchan);
4415 logevent("Opened channel for session");
4418 * Potentially enable X11 forwarding.
4420 if (cfg.x11_forward) {
4421 char proto[20], data[64];
4422 logevent("Requesting X11 forwarding");
4423 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
4424 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4425 ssh2_pkt_adduint32(mainchan->remoteid);
4426 ssh2_pkt_addstring("x11-req");
4427 ssh2_pkt_addbool(1); /* want reply */
4428 ssh2_pkt_addbool(0); /* many connections */
4429 ssh2_pkt_addstring(proto);
4430 ssh2_pkt_addstring(data);
4431 ssh2_pkt_adduint32(0); /* screen number */
4435 crWaitUntilV(ispkt);
4436 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4437 unsigned i = ssh2_pkt_getuint32();
4438 struct ssh_channel *c;
4439 c = find234(ssh_channels, &i, ssh_channelfind);
4441 continue; /* nonexistent channel */
4442 c->v.v2.remwindow += ssh2_pkt_getuint32();
4444 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4446 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4447 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4448 bombout(("Unexpected response to X11 forwarding request:"
4449 " packet type %d", pktin.type));
4452 logevent("X11 forwarding refused");
4454 logevent("X11 forwarding enabled");
4455 ssh_X11_fwd_enabled = TRUE;
4460 * Enable port forwardings.
4463 static char *e; /* preserve across crReturn */
4467 char sports[256], dports[256], host[256];
4470 ssh_rportfwds = newtree234(ssh_rportcmp_ssh2);
4471 /* Add port forwardings. */
4476 while (*e && *e != '\t')
4482 while (*e && *e != ':')
4492 dport = atoi(dports);
4493 sport = atoi(sports);
4494 if (sport && dport) {
4496 pfd_addforward(host, dport, sport);
4497 sprintf(buf, "Local port %d forwarding to %s:%d",
4498 sport, host, dport);
4501 struct ssh_rportfwd *pf;
4502 pf = smalloc(sizeof(*pf));
4503 strcpy(pf->dhost, host);
4506 if (add234(ssh_rportfwds, pf) != pf) {
4508 "Duplicate remote port forwarding to %s:%d",
4513 sprintf(buf, "Requesting remote port %d (forwarded to %s:%d)",
4514 sport, host, dport);
4516 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4517 ssh2_pkt_addstring("tcpip-forward");
4518 ssh2_pkt_addbool(1);/* want reply */
4519 ssh2_pkt_addstring("127.0.0.1");
4520 ssh2_pkt_adduint32(sport);
4524 crWaitUntilV(ispkt);
4525 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4526 unsigned i = ssh2_pkt_getuint32();
4527 struct ssh_channel *c;
4528 c = find234(ssh_channels, &i, ssh_channelfind);
4530 continue;/* nonexistent channel */
4531 c->v.v2.remwindow += ssh2_pkt_getuint32();
4533 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4535 if (pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
4536 if (pktin.type != SSH2_MSG_REQUEST_FAILURE) {
4537 bombout(("Unexpected response to port "
4538 "forwarding request: packet type %d",
4542 logevent("Server refused this port forwarding");
4544 logevent("Remote port forwarding enabled");
4553 * Potentially enable agent forwarding.
4555 if (cfg.agentfwd && agent_exists()) {
4556 logevent("Requesting OpenSSH-style agent forwarding");
4557 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4558 ssh2_pkt_adduint32(mainchan->remoteid);
4559 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4560 ssh2_pkt_addbool(1); /* want reply */
4564 crWaitUntilV(ispkt);
4565 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4566 unsigned i = ssh2_pkt_getuint32();
4567 struct ssh_channel *c;
4568 c = find234(ssh_channels, &i, ssh_channelfind);
4570 continue; /* nonexistent channel */
4571 c->v.v2.remwindow += ssh2_pkt_getuint32();
4573 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4575 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4576 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4577 bombout(("Unexpected response to agent forwarding request:"
4578 " packet type %d", pktin.type));
4581 logevent("Agent forwarding refused");
4583 logevent("Agent forwarding enabled");
4584 ssh_agentfwd_enabled = TRUE;
4589 * Now allocate a pty for the session.
4592 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4593 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
4594 ssh2_pkt_addstring("pty-req");
4595 ssh2_pkt_addbool(1); /* want reply */
4596 ssh2_pkt_addstring(cfg.termtype);
4597 ssh2_pkt_adduint32(cols);
4598 ssh2_pkt_adduint32(rows);
4599 ssh2_pkt_adduint32(0); /* pixel width */
4600 ssh2_pkt_adduint32(0); /* pixel height */
4601 ssh2_pkt_addstring_start();
4602 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4604 ssh_state = SSH_STATE_INTERMED;
4607 crWaitUntilV(ispkt);
4608 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4609 unsigned i = ssh2_pkt_getuint32();
4610 struct ssh_channel *c;
4611 c = find234(ssh_channels, &i, ssh_channelfind);
4613 continue; /* nonexistent channel */
4614 c->v.v2.remwindow += ssh2_pkt_getuint32();
4616 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4618 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4619 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4620 bombout(("Unexpected response to pty request:"
4621 " packet type %d", pktin.type));
4624 c_write_str("Server refused to allocate pty\r\n");
4625 ssh_editing = ssh_echoing = 1;
4627 logevent("Allocated pty");
4630 ssh_editing = ssh_echoing = 1;
4634 * Start a shell or a remote command. We may have to attempt
4635 * this twice if the config data has provided a second choice
4642 if (ssh_fallback_cmd) {
4643 subsys = cfg.ssh_subsys2;
4644 cmd = cfg.remote_cmd_ptr2;
4646 subsys = cfg.ssh_subsys;
4647 cmd = cfg.remote_cmd_ptr;
4650 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4651 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
4653 ssh2_pkt_addstring("subsystem");
4654 ssh2_pkt_addbool(1); /* want reply */
4655 ssh2_pkt_addstring(cmd);
4657 ssh2_pkt_addstring("exec");
4658 ssh2_pkt_addbool(1); /* want reply */
4659 ssh2_pkt_addstring(cmd);
4661 ssh2_pkt_addstring("shell");
4662 ssh2_pkt_addbool(1); /* want reply */
4666 crWaitUntilV(ispkt);
4667 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4668 unsigned i = ssh2_pkt_getuint32();
4669 struct ssh_channel *c;
4670 c = find234(ssh_channels, &i, ssh_channelfind);
4672 continue; /* nonexistent channel */
4673 c->v.v2.remwindow += ssh2_pkt_getuint32();
4675 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4676 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4677 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4678 bombout(("Unexpected response to shell/command request:"
4679 " packet type %d", pktin.type));
4683 * We failed to start the command. If this is the
4684 * fallback command, we really are finished; if it's
4685 * not, and if the fallback command exists, try falling
4686 * back to it before complaining.
4688 if (!ssh_fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
4689 logevent("Primary command failed; attempting fallback");
4690 ssh_fallback_cmd = TRUE;
4693 bombout(("Server refused to start a shell/command"));
4696 logevent("Started a shell/command");
4701 ssh_state = SSH_STATE_SESSION;
4705 ssh_special(TS_EOF);
4710 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
4713 static int try_send;
4717 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
4718 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
4721 unsigned i = ssh2_pkt_getuint32();
4722 struct ssh_channel *c;
4723 c = find234(ssh_channels, &i, ssh_channelfind);
4725 continue; /* nonexistent channel */
4726 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
4727 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
4728 continue; /* extended but not stderr */
4729 ssh2_pkt_getstring(&data, &length);
4732 c->v.v2.locwindow -= length;
4734 case CHAN_MAINSESSION:
4736 from_backend(pktin.type ==
4737 SSH2_MSG_CHANNEL_EXTENDED_DATA,
4741 bufsize = x11_send(c->u.x11.s, data, length);
4744 bufsize = pfd_send(c->u.pfd.s, data, length);
4747 while (length > 0) {
4748 if (c->u.a.lensofar < 4) {
4749 int l = min(4 - c->u.a.lensofar, length);
4750 memcpy(c->u.a.msglen + c->u.a.lensofar,
4754 c->u.a.lensofar += l;
4756 if (c->u.a.lensofar == 4) {
4758 4 + GET_32BIT(c->u.a.msglen);
4759 c->u.a.message = smalloc(c->u.a.totallen);
4760 memcpy(c->u.a.message, c->u.a.msglen, 4);
4762 if (c->u.a.lensofar >= 4 && length > 0) {
4764 min(c->u.a.totallen - c->u.a.lensofar,
4766 memcpy(c->u.a.message + c->u.a.lensofar,
4770 c->u.a.lensofar += l;
4772 if (c->u.a.lensofar == c->u.a.totallen) {
4773 void *reply, *sentreply;
4775 agent_query(c->u.a.message,
4776 c->u.a.totallen, &reply,
4781 /* Fake SSH_AGENT_FAILURE. */
4782 sentreply = "\0\0\0\1\5";
4785 ssh2_add_channel_data(c, sentreply,
4790 sfree(c->u.a.message);
4791 c->u.a.lensofar = 0;
4798 * If we are not buffering too much data,
4799 * enlarge the window again at the remote side.
4801 if (bufsize < OUR_V2_WINSIZE)
4802 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
4804 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
4805 ssh_state = SSH_STATE_CLOSED;
4806 logevent("Received disconnect message");
4808 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
4809 unsigned i = ssh2_pkt_getuint32();
4810 struct ssh_channel *c;
4812 c = find234(ssh_channels, &i, ssh_channelfind);
4814 continue; /* nonexistent channel */
4816 if (c->type == CHAN_X11) {
4818 * Remote EOF on an X11 channel means we should
4819 * wrap up and close the channel ourselves.
4821 x11_close(c->u.x11.s);
4823 } else if (c->type == CHAN_AGENT) {
4825 } else if (c->type == CHAN_SOCKDATA) {
4826 pfd_close(c->u.pfd.s);
4829 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
4830 unsigned i = ssh2_pkt_getuint32();
4831 struct ssh_channel *c;
4833 c = find234(ssh_channels, &i, ssh_channelfind);
4835 continue; /* nonexistent channel */
4836 /* Do pre-close processing on the channel. */
4838 case CHAN_MAINSESSION:
4839 break; /* nothing to see here, move along */
4841 if (c->u.x11.s != NULL)
4842 x11_close(c->u.x11.s);
4849 if (c->u.pfd.s != NULL)
4850 pfd_close(c->u.pfd.s);
4854 if (c->closes == 0) {
4855 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4856 ssh2_pkt_adduint32(c->remoteid);
4859 del234(ssh_channels, c);
4860 bufchain_clear(&c->v.v2.outbuffer);
4864 * See if that was the last channel left open.
4866 if (count234(ssh_channels) == 0) {
4867 logevent("All channels closed. Disconnecting");
4868 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4869 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4870 ssh2_pkt_addstring("All open channels closed");
4871 ssh2_pkt_addstring("en"); /* language tag */
4873 ssh_state = SSH_STATE_CLOSED;
4876 continue; /* remote sends close; ignore (FIXME) */
4877 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4878 unsigned i = ssh2_pkt_getuint32();
4879 struct ssh_channel *c;
4880 c = find234(ssh_channels, &i, ssh_channelfind);
4882 continue; /* nonexistent channel */
4883 c->v.v2.remwindow += ssh2_pkt_getuint32();
4885 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4886 unsigned i = ssh2_pkt_getuint32();
4887 struct ssh_channel *c;
4888 c = find234(ssh_channels, &i, ssh_channelfind);
4890 continue; /* nonexistent channel */
4891 if (c->type != CHAN_SOCKDATA_DORMANT)
4892 continue; /* dunno why they're confirming this */
4893 c->remoteid = ssh2_pkt_getuint32();
4894 c->type = CHAN_SOCKDATA;
4895 c->v.v2.remwindow = ssh2_pkt_getuint32();
4896 c->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4897 bufchain_init(&c->v.v2.outbuffer);
4899 pfd_confirm(c->u.pfd.s);
4902 * We have a pending close on this channel,
4903 * which we decided on before the server acked
4904 * the channel open. So now we know the
4905 * remoteid, we can close it again.
4907 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4908 ssh2_pkt_adduint32(c->remoteid);
4911 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
4912 unsigned i = ssh2_pkt_getuint32();
4913 struct ssh_channel *c;
4914 c = find234(ssh_channels, &i, ssh_channelfind);
4916 continue; /* nonexistent channel */
4917 if (c->type != CHAN_SOCKDATA_DORMANT)
4918 continue; /* dunno why they're failing this */
4920 logevent("Forwarded connection refused by server");
4922 pfd_close(c->u.pfd.s);
4924 del234(ssh_channels, c);
4926 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
4929 int typelen, want_reply;
4930 struct ssh_channel *c;
4932 localid = ssh2_pkt_getuint32();
4933 ssh2_pkt_getstring(&type, &typelen);
4934 want_reply = ssh2_pkt_getbool();
4937 * First, check that the channel exists. Otherwise,
4938 * we can instantly disconnect with a rude message.
4940 c = find234(ssh_channels, &localid, ssh_channelfind);
4943 sprintf(buf, "Received channel request for nonexistent"
4944 " channel %d", localid);
4946 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4947 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4948 ssh2_pkt_addstring(buf);
4949 ssh2_pkt_addstring("en"); /* language tag */
4951 connection_fatal(buf);
4952 ssh_state = SSH_STATE_CLOSED;
4957 * We don't recognise any form of channel request,
4958 * so we now either ignore the request or respond
4959 * with CHANNEL_FAILURE, depending on want_reply.
4962 ssh2_pkt_init(SSH2_MSG_CHANNEL_FAILURE);
4963 ssh2_pkt_adduint32(c->remoteid);
4966 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
4970 struct ssh_channel *c;
4971 unsigned remid, winsize, pktsize;
4972 ssh2_pkt_getstring(&type, &typelen);
4973 c = smalloc(sizeof(struct ssh_channel));
4975 remid = ssh2_pkt_getuint32();
4976 winsize = ssh2_pkt_getuint32();
4977 pktsize = ssh2_pkt_getuint32();
4979 if (typelen == 3 && !memcmp(type, "x11", 3)) {
4980 if (!ssh_X11_fwd_enabled)
4981 error = "X11 forwarding is not enabled";
4982 else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
4984 error = "Unable to open an X11 connection";
4988 } else if (typelen == 15 &&
4989 !memcmp(type, "forwarded-tcpip", 15)) {
4990 struct ssh_rportfwd pf, *realpf;
4993 ssh2_pkt_getstring(&dummy, &dummylen);/* skip address */
4994 pf.sport = ssh2_pkt_getuint32();
4995 realpf = find234(ssh_rportfwds, &pf, NULL);
4996 if (realpf == NULL) {
4997 error = "Remote port is not recognised";
4999 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5002 sprintf(buf, "Received remote port open request for %s:%d",
5003 realpf->dhost, realpf->dport);
5006 sprintf(buf, "Port open failed: %s", e);
5008 error = "Port open failed";
5010 logevent("Forwarded port opened successfully");
5011 c->type = CHAN_SOCKDATA;
5014 } else if (typelen == 22 &&
5015 !memcmp(type, "auth-agent@openssh.com", 3)) {
5016 if (!ssh_agentfwd_enabled)
5017 error = "Agent forwarding is not enabled";
5019 c->type = CHAN_AGENT; /* identify channel type */
5020 c->u.a.lensofar = 0;
5023 error = "Unsupported channel type requested";
5026 c->remoteid = remid;
5028 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
5029 ssh2_pkt_adduint32(c->remoteid);
5030 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
5031 ssh2_pkt_addstring(error);
5032 ssh2_pkt_addstring("en"); /* language tag */
5036 c->localid = alloc_channel_id();
5038 c->v.v2.locwindow = OUR_V2_WINSIZE;
5039 c->v.v2.remwindow = winsize;
5040 c->v.v2.remmaxpkt = pktsize;
5041 bufchain_init(&c->v.v2.outbuffer);
5042 add234(ssh_channels, c);
5043 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5044 ssh2_pkt_adduint32(c->remoteid);
5045 ssh2_pkt_adduint32(c->localid);
5046 ssh2_pkt_adduint32(c->v.v2.locwindow);
5047 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5051 bombout(("Strange packet received: type %d", pktin.type));
5056 * We have spare data. Add it to the channel buffer.
5058 ssh2_add_channel_data(mainchan, in, inlen);
5063 struct ssh_channel *c;
5065 * Try to send data on all channels if we can.
5067 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
5068 int bufsize = ssh2_try_send(c);
5071 case CHAN_MAINSESSION:
5072 /* stdin need not receive an unthrottle
5073 * notification since it will be polled */
5076 x11_unthrottle(c->u.x11.s);
5079 /* agent sockets are request/response and need no
5080 * buffer management */
5083 pfd_unthrottle(c->u.pfd.s);
5095 * Handle the top-level SSH2 protocol.
5097 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
5099 if (do_ssh2_transport(in, inlen, ispkt) == 0)
5101 do_ssh2_authconn(in, inlen, ispkt);
5105 * Called to set up the connection.
5107 * Returns an error message, or NULL on success.
5109 static char *ssh_init(char *host, int port, char **realhost, int nodelay)
5114 if (crypto_startup() == 0)
5115 return "Microsoft high encryption pack not installed!";
5121 ssh1_throttle_count = 0;
5122 ssh_overall_bufsize = 0;
5123 ssh_fallback_cmd = 0;
5125 p = connect_to_host(host, port, realhost, nodelay);
5133 * Called to send data down the Telnet connection.
5135 static int ssh_send(char *buf, int len)
5137 if (s == NULL || ssh_protocol == NULL)
5140 ssh_protocol(buf, len, 0);
5142 return ssh_sendbuffer();
5146 * Called to query the current amount of buffered stdin data.
5148 static int ssh_sendbuffer(void)
5152 if (s == NULL || ssh_protocol == NULL)
5156 * If the SSH socket itself has backed up, add the total backup
5157 * size on that to any individual buffer on the stdin channel.
5160 if (ssh_throttled_all)
5161 override_value = ssh_overall_bufsize;
5163 if (ssh_version == 1) {
5164 return override_value;
5165 } else if (ssh_version == 2) {
5166 if (!mainchan || mainchan->closes > 0)
5167 return override_value;
5169 return override_value + bufchain_size(&mainchan->v.v2.outbuffer);
5176 * Called to set the size of the window from SSH's POV.
5178 static void ssh_size(void)
5180 switch (ssh_state) {
5181 case SSH_STATE_BEFORE_SIZE:
5182 case SSH_STATE_PREPACKET:
5183 case SSH_STATE_CLOSED:
5184 break; /* do nothing */
5185 case SSH_STATE_INTERMED:
5186 size_needed = TRUE; /* buffer for later */
5188 case SSH_STATE_SESSION:
5190 if (ssh_version == 1) {
5191 send_packet(SSH1_CMSG_WINDOW_SIZE,
5192 PKT_INT, rows, PKT_INT, cols,
5193 PKT_INT, 0, PKT_INT, 0, PKT_END);
5195 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5196 ssh2_pkt_adduint32(mainchan->remoteid);
5197 ssh2_pkt_addstring("window-change");
5198 ssh2_pkt_addbool(0);
5199 ssh2_pkt_adduint32(cols);
5200 ssh2_pkt_adduint32(rows);
5201 ssh2_pkt_adduint32(0);
5202 ssh2_pkt_adduint32(0);
5211 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5212 * can send an EOF and collect resulting output (e.g. `plink
5215 static void ssh_special(Telnet_Special code)
5217 if (code == TS_EOF) {
5218 if (ssh_state != SSH_STATE_SESSION) {
5220 * Buffer the EOF in case we are pre-SESSION, so we can
5221 * send it as soon as we reach SESSION.
5227 if (ssh_version == 1) {
5228 send_packet(SSH1_CMSG_EOF, PKT_END);
5230 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
5231 ssh2_pkt_adduint32(mainchan->remoteid);
5234 logevent("Sent EOF message");
5235 } else if (code == TS_PING) {
5236 if (ssh_state == SSH_STATE_CLOSED
5237 || ssh_state == SSH_STATE_PREPACKET) return;
5238 if (ssh_version == 1) {
5239 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
5241 ssh2_pkt_init(SSH2_MSG_IGNORE);
5242 ssh2_pkt_addstring_start();
5250 void *new_sock_channel(Socket s)
5252 struct ssh_channel *c;
5253 c = smalloc(sizeof(struct ssh_channel));
5256 c->remoteid = -1; /* to be set when open confirmed */
5257 c->localid = alloc_channel_id();
5259 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
5261 add234(ssh_channels, c);
5267 * This is called when stdout/stderr (the entity to which
5268 * from_backend sends data) manages to clear some backlog.
5270 void ssh_unthrottle(int bufsize)
5272 if (ssh_version == 1) {
5273 if (ssh1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
5274 ssh1_stdout_throttling = 0;
5278 if (mainchan && mainchan->closes == 0)
5279 ssh2_set_window(mainchan, OUR_V2_WINSIZE - bufsize);
5283 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
5285 struct ssh_channel *c = (struct ssh_channel *)channel;
5288 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
5291 if (ssh_version == 1) {
5292 send_packet(SSH1_MSG_PORT_OPEN,
5293 PKT_INT, c->localid,
5296 //PKT_STR, <org:orgport>,
5299 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
5300 ssh2_pkt_addstring("direct-tcpip");
5301 ssh2_pkt_adduint32(c->localid);
5302 c->v.v2.locwindow = OUR_V2_WINSIZE;
5303 ssh2_pkt_adduint32(c->v.v2.locwindow);/* our window size */
5304 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5305 ssh2_pkt_addstring(hostname);
5306 ssh2_pkt_adduint32(port);
5308 * We make up values for the originator data; partly it's
5309 * too much hassle to keep track, and partly I'm not
5310 * convinced the server should be told details like that
5311 * about my local network configuration.
5313 ssh2_pkt_addstring("client-side-connection");
5314 ssh2_pkt_adduint32(0);
5320 static Socket ssh_socket(void)
5325 static int ssh_sendok(void)
5330 static int ssh_ldisc(int option)
5332 if (option == LD_ECHO)
5334 if (option == LD_EDIT)
5339 Backend ssh_backend = {