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
241 const static struct ssh2_ciphers *ciphers[] = {
248 const static struct ssh_kex *kex_algs[] = {
249 &ssh_diffiehellman_gex,
253 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
255 static void nullmac_key(unsigned char *key)
258 static void nullmac_generate(unsigned char *blk, int len,
262 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq)
266 const static struct ssh_mac ssh_mac_none = {
267 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
269 const static struct ssh_mac *macs[] = {
270 &ssh_sha1, &ssh_md5, &ssh_mac_none
272 const static struct ssh_mac *buggymacs[] = {
273 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
276 static void ssh_comp_none_init(void)
279 static int ssh_comp_none_block(unsigned char *block, int len,
280 unsigned char **outblock, int *outlen)
284 static int ssh_comp_none_disable(void)
288 const static struct ssh_compress ssh_comp_none = {
290 ssh_comp_none_init, ssh_comp_none_block,
291 ssh_comp_none_init, ssh_comp_none_block,
292 ssh_comp_none_disable
294 extern const struct ssh_compress ssh_zlib;
295 const static struct ssh_compress *compressions[] = {
296 &ssh_zlib, &ssh_comp_none
299 enum { /* channel types */
304 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
308 * 2-3-4 tree storing channels.
311 unsigned remoteid, localid;
315 struct ssh1_data_channel {
318 struct ssh2_data_channel {
320 unsigned remwindow, remmaxpkt;
325 struct ssh_agent_channel {
326 unsigned char *message;
327 unsigned char msglen[4];
328 int lensofar, totallen;
330 struct ssh_x11_channel {
333 struct ssh_pfd_channel {
340 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
341 * 2 use this structure in different ways, reflecting SSH 2's
342 * altogether saner approach to port forwarding.
344 * In SSH 1, you arrange a remote forwarding by sending the server
345 * the remote port number, and the local destination host:port.
346 * When a connection comes in, the server sends you back that
347 * host:port pair, and you connect to it. This is a ready-made
348 * security hole if you're not on the ball: a malicious server
349 * could send you back _any_ host:port pair, so if you trustingly
350 * connect to the address it gives you then you've just opened the
351 * entire inside of your corporate network just by connecting
352 * through it to a dodgy SSH server. Hence, we must store a list of
353 * host:port pairs we _are_ trying to forward to, and reject a
354 * connection request from the server if it's not in the list.
356 * In SSH 2, each side of the connection minds its own business and
357 * doesn't send unnecessary information to the other. You arrange a
358 * remote forwarding by sending the server just the remote port
359 * number. When a connection comes in, the server tells you which
360 * of its ports was connected to; and _you_ have to remember what
361 * local host:port pair went with that port number.
363 * Hence: in SSH 1 this structure stores host:port pairs we intend
364 * to allow connections to, and is indexed by those host:port
365 * pairs. In SSH 2 it stores a mapping from source port to
366 * destination host:port pair, and is indexed by source port.
368 struct ssh_rportfwd {
369 unsigned sport, dport;
382 static SHA_State exhash, exhashbase;
384 static Socket s = NULL;
386 static unsigned char session_key[32];
387 static int ssh1_compressing;
388 static int ssh1_remote_protoflags;
389 static int ssh1_local_protoflags;
390 static int ssh_agentfwd_enabled;
391 static int ssh_X11_fwd_enabled;
392 static int ssh_remote_bugs;
393 static const struct ssh_cipher *cipher = NULL;
394 static const struct ssh2_cipher *cscipher = NULL;
395 static const struct ssh2_cipher *sccipher = NULL;
396 static const struct ssh_mac *csmac = NULL;
397 static const struct ssh_mac *scmac = NULL;
398 static const struct ssh_compress *cscomp = NULL;
399 static const struct ssh_compress *sccomp = NULL;
400 static const struct ssh_kex *kex = NULL;
401 static const struct ssh_signkey *hostkey = NULL;
402 static unsigned char ssh2_session_id[20];
403 int (*ssh_get_line) (const char *prompt, char *str, int maxlen,
406 static char *savedhost;
407 static int savedport;
408 static int ssh_send_ok;
409 static int ssh_echoing, ssh_editing;
411 static tree234 *ssh_channels; /* indexed by local id */
412 static struct ssh_channel *mainchan; /* primary session channel */
414 static tree234 *ssh_rportfwds;
418 SSH_STATE_BEFORE_SIZE,
422 } ssh_state = SSH_STATE_PREPACKET;
424 static int size_needed = FALSE, eof_needed = FALSE;
426 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
427 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
428 static unsigned char *deferred_send_data = NULL;
429 static int deferred_len = 0, deferred_size = 0;
432 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
433 * that fails. This variable is the means by which scp.c can reach
434 * into the SSH code and find out which one it got.
436 int ssh_fallback_cmd = 0;
438 static int ssh_version;
439 static int ssh1_throttle_count;
440 static int ssh_overall_bufsize;
441 static int ssh_throttled_all;
442 static int ssh1_stdout_throttling;
443 static void (*ssh_protocol) (unsigned char *in, int inlen, int ispkt);
444 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
445 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
446 static void ssh_size(void);
447 static void ssh_special(Telnet_Special);
448 static int ssh2_try_send(struct ssh_channel *c);
449 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
451 static void ssh_throttle_all(int enable, int bufsize);
452 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
453 static int (*s_rdpkt) (unsigned char **data, int *datalen);
454 static int ssh_sendbuffer(void);
456 static struct rdpkt1_state_tag {
457 long len, pad, biglen, to_read;
458 unsigned long realcrc, gotcrc;
464 static struct rdpkt2_state_tag {
465 long len, pad, payload, packetlen, maclen;
468 unsigned long incoming_sequence;
471 static int ssh_channelcmp(void *av, void *bv)
473 struct ssh_channel *a = (struct ssh_channel *) av;
474 struct ssh_channel *b = (struct ssh_channel *) bv;
475 if (a->localid < b->localid)
477 if (a->localid > b->localid)
481 static int ssh_channelfind(void *av, void *bv)
483 unsigned *a = (unsigned *) av;
484 struct ssh_channel *b = (struct ssh_channel *) bv;
492 static int ssh_rportcmp_ssh1(void *av, void *bv)
494 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
495 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
497 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
498 return i < 0 ? -1 : +1;
499 if (a->dport > b->dport)
501 if (a->dport < b->dport)
506 static int ssh_rportcmp_ssh2(void *av, void *bv)
508 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
509 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
511 if (a->sport > b->sport)
513 if (a->sport < b->sport)
518 static int alloc_channel_id(void)
520 const unsigned CHANNEL_NUMBER_OFFSET = 256;
521 unsigned low, high, mid;
523 struct ssh_channel *c;
526 * First-fit allocation of channel numbers: always pick the
527 * lowest unused one. To do this, binary-search using the
528 * counted B-tree to find the largest channel ID which is in a
529 * contiguous sequence from the beginning. (Precisely
530 * everything in that sequence must have ID equal to its tree
531 * index plus CHANNEL_NUMBER_OFFSET.)
533 tsize = count234(ssh_channels);
537 while (high - low > 1) {
538 mid = (high + low) / 2;
539 c = index234(ssh_channels, mid);
540 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
541 low = mid; /* this one is fine */
543 high = mid; /* this one is past it */
546 * Now low points to either -1, or the tree index of the
547 * largest ID in the initial sequence.
550 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
551 assert(NULL == find234(ssh_channels, &i, ssh_channelfind));
553 return low + 1 + CHANNEL_NUMBER_OFFSET;
556 static void c_write(char *buf, int len)
558 if ((flags & FLAG_STDERR)) {
560 for (i = 0; i < len; i++)
562 fputc(buf[i], stderr);
565 from_backend(1, buf, len);
568 static void c_write_untrusted(char *buf, int len)
571 for (i = 0; i < len; i++) {
574 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
579 static void c_write_str(char *buf)
581 c_write(buf, strlen(buf));
585 * Collect incoming data in the incoming packet buffer.
586 * Decipher and verify the packet when it is completely read.
587 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
588 * Update the *data and *datalen variables.
589 * Return the additional nr of bytes needed, or 0 when
590 * a complete packet is available.
592 static int ssh1_rdpkt(unsigned char **data, int *datalen)
594 struct rdpkt1_state_tag *st = &rdpkt1_state;
603 for (st->i = st->len = 0; st->i < 4; st->i++) {
604 while ((*datalen) == 0)
606 st->len = (st->len << 8) + **data;
607 (*data)++, (*datalen)--;
610 st->pad = 8 - (st->len % 8);
611 st->biglen = st->len + st->pad;
612 pktin.length = st->len - 5;
614 if (pktin.maxlen < st->biglen) {
615 pktin.maxlen = st->biglen;
616 pktin.data = (pktin.data == NULL ? smalloc(st->biglen + APIEXTRA) :
617 srealloc(pktin.data, st->biglen + APIEXTRA));
619 fatalbox("Out of memory");
622 st->to_read = st->biglen;
624 while (st->to_read > 0) {
625 st->chunk = st->to_read;
626 while ((*datalen) == 0)
627 crReturn(st->to_read);
628 if (st->chunk > (*datalen))
629 st->chunk = (*datalen);
630 memcpy(st->p, *data, st->chunk);
632 *datalen -= st->chunk;
634 st->to_read -= st->chunk;
638 cipher->decrypt(pktin.data, st->biglen);
640 debug(("Got packet len=%d pad=%d\n", st->len, st->pad));
641 dmemdump(pktin.data, st->biglen);
644 st->realcrc = crc32(pktin.data, st->biglen - 4);
645 st->gotcrc = GET_32BIT(pktin.data + st->biglen - 4);
646 if (st->gotcrc != st->realcrc) {
647 bombout(("Incorrect CRC received on packet"));
651 pktin.body = pktin.data + st->pad + 1;
653 if (ssh1_compressing) {
654 unsigned char *decompblk;
657 debug(("Packet payload pre-decompression:\n"));
658 dmemdump(pktin.body - 1, pktin.length + 1);
660 zlib_decompress_block(pktin.body - 1, pktin.length + 1,
661 &decompblk, &decomplen);
663 if (pktin.maxlen < st->pad + decomplen) {
664 pktin.maxlen = st->pad + decomplen;
665 pktin.data = srealloc(pktin.data, pktin.maxlen + APIEXTRA);
666 pktin.body = pktin.data + st->pad + 1;
668 fatalbox("Out of memory");
671 memcpy(pktin.body - 1, decompblk, decomplen);
673 pktin.length = decomplen - 1;
675 debug(("Packet payload post-decompression:\n"));
676 dmemdump(pktin.body - 1, pktin.length + 1);
680 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
681 pktin.type == SSH1_SMSG_STDERR_DATA ||
682 pktin.type == SSH1_MSG_DEBUG ||
683 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
684 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
685 long strlen = GET_32BIT(pktin.body);
686 if (strlen + 4 != pktin.length) {
687 bombout(("Received data packet with bogus string length"));
692 pktin.type = pktin.body[-1];
694 if (pktin.type == SSH1_MSG_DEBUG) {
695 /* log debug message */
697 int strlen = GET_32BIT(pktin.body);
698 strcpy(buf, "Remote: ");
701 memcpy(buf + 8, pktin.body + 4, strlen);
702 buf[8 + strlen] = '\0';
705 } else if (pktin.type == SSH1_MSG_IGNORE) {
710 if (pktin.type == SSH1_MSG_DISCONNECT) {
711 /* log reason code in disconnect message */
713 unsigned msglen = GET_32BIT(pktin.body);
715 strcpy(buf, "Remote sent disconnect: ");
716 nowlen = strlen(buf);
717 if (msglen > sizeof(buf) - nowlen - 1)
718 msglen = sizeof(buf) - nowlen - 1;
719 memcpy(buf + nowlen, pktin.body + 4, msglen);
720 buf[nowlen + msglen] = '\0';
722 bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
729 static int ssh2_rdpkt(unsigned char **data, int *datalen)
731 struct rdpkt2_state_tag *st = &rdpkt2_state;
739 st->cipherblk = sccipher->blksize;
742 if (st->cipherblk < 8)
745 if (pktin.maxlen < st->cipherblk) {
746 pktin.maxlen = st->cipherblk;
749 NULL ? smalloc(st->cipherblk +
750 APIEXTRA) : srealloc(pktin.data,
754 fatalbox("Out of memory");
758 * Acquire and decrypt the first block of the packet. This will
759 * contain the length and padding details.
761 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
762 while ((*datalen) == 0)
763 crReturn(st->cipherblk - st->i);
764 pktin.data[st->i] = *(*data)++;
769 sccipher->decrypt(pktin.data, st->cipherblk);
772 * Now get the length and padding figures.
774 st->len = GET_32BIT(pktin.data);
775 st->pad = pktin.data[4];
778 * This enables us to deduce the payload length.
780 st->payload = st->len - st->pad - 1;
782 pktin.length = st->payload + 5;
785 * So now we can work out the total packet length.
787 st->packetlen = st->len + 4;
788 st->maclen = scmac ? scmac->len : 0;
791 * Adjust memory allocation if packet is too big.
793 if (pktin.maxlen < st->packetlen + st->maclen) {
794 pktin.maxlen = st->packetlen + st->maclen;
797 NULL ? smalloc(pktin.maxlen + APIEXTRA) : srealloc(pktin.data,
802 fatalbox("Out of memory");
806 * Read and decrypt the remainder of the packet.
808 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
810 while ((*datalen) == 0)
811 crReturn(st->packetlen + st->maclen - st->i);
812 pktin.data[st->i] = *(*data)++;
815 /* Decrypt everything _except_ the MAC. */
817 sccipher->decrypt(pktin.data + st->cipherblk,
818 st->packetlen - st->cipherblk);
821 debug(("Got packet len=%d pad=%d\n", st->len, st->pad));
822 dmemdump(pktin.data, st->packetlen);
829 && !scmac->verify(pktin.data, st->len + 4,
830 st->incoming_sequence)) {
831 bombout(("Incorrect MAC received on packet"));
834 st->incoming_sequence++; /* whether or not we MACed */
837 * Decompress packet payload.
840 unsigned char *newpayload;
842 if (sccomp && sccomp->decompress(pktin.data + 5, pktin.length - 5,
843 &newpayload, &newlen)) {
844 if (pktin.maxlen < newlen + 5) {
845 pktin.maxlen = newlen + 5;
848 NULL ? smalloc(pktin.maxlen +
849 APIEXTRA) : srealloc(pktin.data,
853 fatalbox("Out of memory");
855 pktin.length = 5 + newlen;
856 memcpy(pktin.data + 5, newpayload, newlen);
858 debug(("Post-decompression payload:\n"));
859 dmemdump(pktin.data + 5, newlen);
867 pktin.type = pktin.data[5];
869 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
870 goto next_packet; /* FIXME: print DEBUG message */
872 if (pktin.type == SSH2_MSG_DISCONNECT) {
873 /* log reason code in disconnect message */
875 int reason = GET_32BIT(pktin.data + 6);
876 unsigned msglen = GET_32BIT(pktin.data + 10);
878 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
879 sprintf(buf, "Received disconnect message (%s)",
880 ssh2_disconnect_reasons[reason]);
882 sprintf(buf, "Received disconnect message (unknown type %d)",
886 strcpy(buf, "Disconnection message text: ");
887 nowlen = strlen(buf);
888 if (msglen > sizeof(buf) - nowlen - 1)
889 msglen = sizeof(buf) - nowlen - 1;
890 memcpy(buf + nowlen, pktin.data + 14, msglen);
891 buf[nowlen + msglen] = '\0';
893 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
895 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
896 ssh2_disconnect_reasons[reason] : "unknown",
904 static void ssh1_pktout_size(int len)
908 len += 5; /* type and CRC */
912 pktout.length = len - 5;
913 if (pktout.maxlen < biglen) {
914 pktout.maxlen = biglen;
916 /* Allocate enough buffer space for extra block
917 * for MS CryptEncrypt() */
918 pktout.data = (pktout.data == NULL ? smalloc(biglen + 12) :
919 srealloc(pktout.data, biglen + 12));
921 pktout.data = (pktout.data == NULL ? smalloc(biglen + 4) :
922 srealloc(pktout.data, biglen + 4));
925 fatalbox("Out of memory");
927 pktout.body = pktout.data + 4 + pad + 1;
930 static void s_wrpkt_start(int type, int len)
932 ssh1_pktout_size(len);
936 static int s_wrpkt_prepare(void)
938 int pad, len, biglen, i;
941 pktout.body[-1] = pktout.type;
943 if (ssh1_compressing) {
944 unsigned char *compblk;
947 debug(("Packet payload pre-compression:\n"));
948 dmemdump(pktout.body - 1, pktout.length + 1);
950 zlib_compress_block(pktout.body - 1, pktout.length + 1,
952 ssh1_pktout_size(complen - 1);
953 memcpy(pktout.body - 1, compblk, complen);
957 len = pktout.length + 5; /* type and CRC */
961 for (i = 0; i < pad; i++)
962 pktout.data[i + 4] = random_byte();
963 crc = crc32(pktout.data + 4, biglen - 4);
964 PUT_32BIT(pktout.data + biglen, crc);
965 PUT_32BIT(pktout.data, len);
968 debug(("Sending packet len=%d\n", biglen + 4));
969 dmemdump(pktout.data, biglen + 4);
972 cipher->encrypt(pktout.data + 4, biglen);
977 static void s_wrpkt(void)
980 len = s_wrpkt_prepare();
981 backlog = sk_write(s, pktout.data, len);
982 if (backlog > SSH_MAX_BACKLOG)
983 ssh_throttle_all(1, backlog);
986 static void s_wrpkt_defer(void)
989 len = s_wrpkt_prepare();
990 if (deferred_len + len > deferred_size) {
991 deferred_size = deferred_len + len + 128;
992 deferred_send_data = srealloc(deferred_send_data, deferred_size);
994 memcpy(deferred_send_data + deferred_len, pktout.data, len);
999 * Construct a packet with the specified contents.
1001 static void construct_packet(int pkttype, va_list ap1, va_list ap2)
1003 unsigned char *p, *argp, argchar;
1004 unsigned long argint;
1005 int pktlen, argtype, arglen;
1009 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1012 (void) va_arg(ap1, int);
1016 (void) va_arg(ap1, char);
1020 (void) va_arg(ap1, unsigned char *);
1021 arglen = va_arg(ap1, int);
1025 argp = va_arg(ap1, unsigned char *);
1026 arglen = strlen(argp);
1027 pktlen += 4 + arglen;
1030 bn = va_arg(ap1, Bignum);
1031 pktlen += ssh1_bignum_length(bn);
1038 s_wrpkt_start(pkttype, pktlen);
1041 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1044 argint = va_arg(ap2, int);
1045 PUT_32BIT(p, argint);
1049 argchar = va_arg(ap2, unsigned char);
1054 argp = va_arg(ap2, unsigned char *);
1055 arglen = va_arg(ap2, int);
1056 memcpy(p, argp, arglen);
1060 argp = va_arg(ap2, unsigned char *);
1061 arglen = strlen(argp);
1062 PUT_32BIT(p, arglen);
1063 memcpy(p + 4, argp, arglen);
1067 bn = va_arg(ap2, Bignum);
1068 p += ssh1_write_bignum(p, bn);
1074 static void send_packet(int pkttype, ...)
1077 va_start(ap1, pkttype);
1078 va_start(ap2, pkttype);
1079 construct_packet(pkttype, ap1, ap2);
1083 static void defer_packet(int pkttype, ...)
1086 va_start(ap1, pkttype);
1087 va_start(ap2, pkttype);
1088 construct_packet(pkttype, ap1, ap2);
1092 static int ssh_versioncmp(char *a, char *b)
1095 unsigned long av, bv;
1097 av = strtoul(a, &ae, 10);
1098 bv = strtoul(b, &be, 10);
1100 return (av < bv ? -1 : +1);
1105 av = strtoul(ae, &ae, 10);
1106 bv = strtoul(be, &be, 10);
1108 return (av < bv ? -1 : +1);
1114 * Utility routines for putting an SSH-protocol `string' and
1115 * `uint32' into a SHA state.
1118 static void sha_string(SHA_State * s, void *str, int len)
1120 unsigned char lenblk[4];
1121 PUT_32BIT(lenblk, len);
1122 SHA_Bytes(s, lenblk, 4);
1123 SHA_Bytes(s, str, len);
1126 static void sha_uint32(SHA_State * s, unsigned i)
1128 unsigned char intblk[4];
1129 PUT_32BIT(intblk, i);
1130 SHA_Bytes(s, intblk, 4);
1134 * SSH2 packet construction functions.
1136 static void ssh2_pkt_ensure(int length)
1138 if (pktout.maxlen < length) {
1139 pktout.maxlen = length + 256;
1142 NULL ? smalloc(pktout.maxlen +
1143 APIEXTRA) : srealloc(pktout.data,
1147 fatalbox("Out of memory");
1150 static void ssh2_pkt_adddata(void *data, int len)
1152 pktout.length += len;
1153 ssh2_pkt_ensure(pktout.length);
1154 memcpy(pktout.data + pktout.length - len, data, len);
1156 static void ssh2_pkt_addbyte(unsigned char byte)
1158 ssh2_pkt_adddata(&byte, 1);
1160 static void ssh2_pkt_init(int pkt_type)
1163 ssh2_pkt_addbyte((unsigned char) pkt_type);
1165 static void ssh2_pkt_addbool(unsigned char value)
1167 ssh2_pkt_adddata(&value, 1);
1169 static void ssh2_pkt_adduint32(unsigned long value)
1172 PUT_32BIT(x, value);
1173 ssh2_pkt_adddata(x, 4);
1175 static void ssh2_pkt_addstring_start(void)
1177 ssh2_pkt_adduint32(0);
1178 pktout.savedpos = pktout.length;
1180 static void ssh2_pkt_addstring_str(char *data)
1182 ssh2_pkt_adddata(data, strlen(data));
1183 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1184 pktout.length - pktout.savedpos);
1186 static void ssh2_pkt_addstring_data(char *data, int len)
1188 ssh2_pkt_adddata(data, len);
1189 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1190 pktout.length - pktout.savedpos);
1192 static void ssh2_pkt_addstring(char *data)
1194 ssh2_pkt_addstring_start();
1195 ssh2_pkt_addstring_str(data);
1197 static char *ssh2_mpint_fmt(Bignum b, int *len)
1200 int i, n = (bignum_bitcount(b) + 7) / 8;
1203 fatalbox("out of memory");
1205 for (i = 1; i <= n; i++)
1206 p[i] = bignum_byte(b, n - i);
1208 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1210 memmove(p, p + i, n + 1 - i);
1214 static void ssh2_pkt_addmp(Bignum b)
1218 p = ssh2_mpint_fmt(b, &len);
1219 ssh2_pkt_addstring_start();
1220 ssh2_pkt_addstring_data(p, len);
1225 * Construct an SSH2 final-form packet: compress it, encrypt it,
1226 * put the MAC on it. Final packet, ready to be sent, is stored in
1227 * pktout.data. Total length is returned.
1229 static int ssh2_pkt_construct(void)
1231 int cipherblk, maclen, padding, i;
1232 static unsigned long outgoing_sequence = 0;
1235 * Compress packet payload.
1238 unsigned char *newpayload;
1241 if (cscomp && cscomp != &ssh_comp_none) {
1242 debug(("Pre-compression payload:\n"));
1243 dmemdump(pktout.data + 5, pktout.length - 5);
1246 if (cscomp && cscomp->compress(pktout.data + 5, pktout.length - 5,
1247 &newpayload, &newlen)) {
1249 ssh2_pkt_adddata(newpayload, newlen);
1255 * Add padding. At least four bytes, and must also bring total
1256 * length (minus MAC) up to a multiple of the block size.
1258 cipherblk = cscipher ? cscipher->blksize : 8; /* block size */
1259 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1262 (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
1263 maclen = csmac ? csmac->len : 0;
1264 ssh2_pkt_ensure(pktout.length + padding + maclen);
1265 pktout.data[4] = padding;
1266 for (i = 0; i < padding; i++)
1267 pktout.data[pktout.length + i] = random_byte();
1268 PUT_32BIT(pktout.data, pktout.length + padding - 4);
1270 csmac->generate(pktout.data, pktout.length + padding,
1272 outgoing_sequence++; /* whether or not we MACed */
1275 debug(("Sending packet len=%d\n", pktout.length + padding));
1276 dmemdump(pktout.data, pktout.length + padding);
1280 cscipher->encrypt(pktout.data, pktout.length + padding);
1282 /* Ready-to-send packet starts at pktout.data. We return length. */
1283 return pktout.length + padding + maclen;
1287 * Construct and send an SSH2 packet immediately.
1289 static void ssh2_pkt_send(void)
1293 len = ssh2_pkt_construct();
1294 backlog = sk_write(s, pktout.data, len);
1295 if (backlog > SSH_MAX_BACKLOG)
1296 ssh_throttle_all(1, backlog);
1300 * Construct an SSH2 packet and add it to a deferred data block.
1301 * Useful for sending multiple packets in a single sk_write() call,
1302 * to prevent a traffic-analysing listener from being able to work
1303 * out the length of any particular packet (such as the password
1306 * Note that because SSH2 sequence-numbers its packets, this can
1307 * NOT be used as an m4-style `defer' allowing packets to be
1308 * constructed in one order and sent in another.
1310 static void ssh2_pkt_defer(void)
1312 int len = ssh2_pkt_construct();
1313 if (deferred_len + len > deferred_size) {
1314 deferred_size = deferred_len + len + 128;
1315 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1317 memcpy(deferred_send_data + deferred_len, pktout.data, len);
1318 deferred_len += len;
1322 * Send the whole deferred data block constructed by
1323 * ssh2_pkt_defer() or SSH1's defer_packet().
1325 static void ssh_pkt_defersend(void)
1328 backlog = sk_write(s, deferred_send_data, deferred_len);
1329 deferred_len = deferred_size = 0;
1330 sfree(deferred_send_data);
1331 deferred_send_data = NULL;
1332 if (backlog > SSH_MAX_BACKLOG)
1333 ssh_throttle_all(1, backlog);
1337 void bndebug(char *string, Bignum b)
1341 p = ssh2_mpint_fmt(b, &len);
1342 debug(("%s", string));
1343 for (i = 0; i < len; i++)
1344 debug((" %02x", p[i]));
1350 static void sha_mpint(SHA_State * s, Bignum b)
1354 p = ssh2_mpint_fmt(b, &len);
1355 sha_string(s, p, len);
1360 * SSH2 packet decode functions.
1362 static unsigned long ssh2_pkt_getuint32(void)
1364 unsigned long value;
1365 if (pktin.length - pktin.savedpos < 4)
1366 return 0; /* arrgh, no way to decline (FIXME?) */
1367 value = GET_32BIT(pktin.data + pktin.savedpos);
1368 pktin.savedpos += 4;
1371 static int ssh2_pkt_getbool(void)
1373 unsigned long value;
1374 if (pktin.length - pktin.savedpos < 1)
1375 return 0; /* arrgh, no way to decline (FIXME?) */
1376 value = pktin.data[pktin.savedpos] != 0;
1380 static void ssh2_pkt_getstring(char **p, int *length)
1383 if (pktin.length - pktin.savedpos < 4)
1385 *length = GET_32BIT(pktin.data + pktin.savedpos);
1386 pktin.savedpos += 4;
1387 if (pktin.length - pktin.savedpos < *length)
1389 *p = pktin.data + pktin.savedpos;
1390 pktin.savedpos += *length;
1392 static Bignum ssh2_pkt_getmp(void)
1398 ssh2_pkt_getstring(&p, &length);
1402 bombout(("internal error: Can't handle negative mpints"));
1405 b = bignum_from_bytes(p, length);
1410 * Examine the remote side's version string and compare it against
1411 * a list of known buggy implementations.
1413 static void ssh_detect_bugs(char *vstring)
1415 char *imp; /* pointer to implementation part */
1417 imp += strcspn(imp, "-");
1419 imp += strcspn(imp, "-");
1422 ssh_remote_bugs = 0;
1424 if (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1425 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1426 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")) {
1428 * These versions don't support SSH1_MSG_IGNORE, so we have
1429 * to use a different defence against password length
1432 ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1433 logevent("We believe remote version has SSH1 ignore bug");
1436 if (!strcmp(imp, "Cisco-1.25")) {
1438 * These versions need a plain password sent; they can't
1439 * handle having a null and a random length of data after
1442 ssh_remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1443 logevent("We believe remote version needs a plain SSH1 password");
1446 if (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1447 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1448 !strncmp(imp, "2.1 ", 4)) {
1450 * These versions have the HMAC bug.
1452 ssh_remote_bugs |= BUG_SSH2_HMAC;
1453 logevent("We believe remote version has SSH2 HMAC bug");
1457 static int do_ssh_init(unsigned char c)
1460 static char version[10];
1461 static char *vstring;
1462 static int vstrsize;
1468 /* Search for the string "SSH-" in the input. */
1471 static const int transS[] = { 1, 2, 2, 1 };
1472 static const int transH[] = { 0, 0, 3, 0 };
1473 static const int transminus[] = { 0, 0, 0, -1 };
1484 crReturn(1); /* get another character */
1488 vstring = smalloc(vstrsize);
1489 strcpy(vstring, "SSH-");
1493 crReturn(1); /* get another char */
1494 if (vslen >= vstrsize - 1) {
1496 vstring = srealloc(vstring, vstrsize);
1498 vstring[vslen++] = c;
1503 } else if (i < sizeof(version) - 1)
1505 } else if (c == '\n')
1509 ssh_agentfwd_enabled = FALSE;
1510 rdpkt2_state.incoming_sequence = 0;
1513 vlog = smalloc(20 + vslen);
1514 vstring[strcspn (vstring, "\r\n")] = '\0'; /* remove end-of-line chars */
1515 sprintf(vlog, "Server version: %s", vstring);
1517 ssh_detect_bugs(vstring);
1521 * Server version "1.99" means we can choose whether we use v1
1522 * or v2 protocol. Choice is based on cfg.sshprot.
1524 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1526 * This is a v2 server. Begin v2 protocol.
1528 char verstring[80], vlog[100];
1529 sprintf(verstring, "SSH-2.0-%s", sshver);
1530 SHA_Init(&exhashbase);
1532 * Hash our version string and their version string.
1534 sha_string(&exhashbase, verstring, strlen(verstring));
1535 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1536 sprintf(vlog, "We claim version: %s", verstring);
1538 strcat(verstring, "\n");
1539 logevent("Using SSH protocol version 2");
1540 sk_write(s, verstring, strlen(verstring));
1541 ssh_protocol = ssh2_protocol;
1543 s_rdpkt = ssh2_rdpkt;
1546 * This is a v1 server. Begin v1 protocol.
1548 char verstring[80], vlog[100];
1549 sprintf(verstring, "SSH-%s-%s",
1550 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"),
1552 sprintf(vlog, "We claim version: %s", verstring);
1554 strcat(verstring, "\n");
1555 logevent("Using SSH protocol version 1");
1556 sk_write(s, verstring, strlen(verstring));
1557 ssh_protocol = ssh1_protocol;
1559 s_rdpkt = ssh1_rdpkt;
1561 ssh_state = SSH_STATE_BEFORE_SIZE;
1568 static void ssh_gotdata(unsigned char *data, int datalen)
1573 * To begin with, feed the characters one by one to the
1574 * protocol initialisation / selection function do_ssh_init().
1575 * When that returns 0, we're done with the initial greeting
1576 * exchange and can move on to packet discipline.
1581 crReturnV; /* more data please */
1582 ret = do_ssh_init(*data);
1590 * We emerge from that loop when the initial negotiation is
1591 * over and we have selected an s_rdpkt function. Now pass
1592 * everything to s_rdpkt, and then pass the resulting packets
1593 * to the proper protocol handler.
1598 while (datalen > 0) {
1599 if (s_rdpkt(&data, &datalen) == 0) {
1600 if (ssh_state == SSH_STATE_CLOSED) {
1603 ssh_protocol(NULL, 0, 1);
1604 if (ssh_state == SSH_STATE_CLOSED) {
1614 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1617 ssh_state = SSH_STATE_CLOSED;
1623 /* A socket error has occurred. */
1624 connection_fatal(error_msg);
1626 /* Otherwise, the remote side closed the connection normally. */
1631 static int ssh_receive(Plug plug, int urgent, char *data, int len)
1633 ssh_gotdata(data, len);
1634 if (ssh_state == SSH_STATE_CLOSED) {
1644 static void ssh_sent(Plug plug, int bufsize)
1647 * If the send backlog on the SSH socket itself clears, we
1648 * should unthrottle the whole world if it was throttled.
1650 if (bufsize < SSH_MAX_BACKLOG)
1651 ssh_throttle_all(0, bufsize);
1655 * Connect to specified host and port.
1656 * Returns an error message, or NULL on success.
1657 * Also places the canonical host name into `realhost'. It must be
1658 * freed by the caller.
1660 static char *connect_to_host(char *host, int port, char **realhost)
1662 static struct plug_function_table fn_table = {
1667 }, *fn_table_ptr = &fn_table;
1676 savedhost = smalloc(1 + strlen(host));
1678 fatalbox("Out of memory");
1679 strcpy(savedhost, host);
1682 port = 22; /* default ssh port */
1697 sprintf(buf, "Looking up host \"%.170s\"", host);
1700 addr = sk_namelookup(host, realhost);
1701 if ((err = sk_addr_error(addr)))
1705 *realhost = strdup(FWhost);
1712 char buf[200], addrbuf[100];
1713 sk_getaddr(addr, addrbuf, 100);
1714 sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
1717 s = sk_new(addr, port, 0, 1, &fn_table_ptr);
1718 if ((err = sk_socket_error(s)))
1722 sk_write(s, "connect ", 8);
1723 sk_write(s, FWhost, strlen(FWhost));
1726 sprintf(buf, " %d\n", FWport);
1727 sk_write(s, buf, strlen(buf));
1735 * Throttle or unthrottle the SSH connection.
1737 static void ssh1_throttle(int adjust)
1739 int old_count = ssh1_throttle_count;
1740 ssh1_throttle_count += adjust;
1741 assert(ssh1_throttle_count >= 0);
1742 if (ssh1_throttle_count && !old_count) {
1743 sk_set_frozen(s, 1);
1744 } else if (!ssh1_throttle_count && old_count) {
1745 sk_set_frozen(s, 0);
1750 * Throttle or unthrottle _all_ local data streams (for when sends
1751 * on the SSH connection itself back up).
1753 static void ssh_throttle_all(int enable, int bufsize)
1756 struct ssh_channel *c;
1758 if (enable == ssh_throttled_all)
1760 ssh_throttled_all = enable;
1761 ssh_overall_bufsize = bufsize;
1764 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
1766 case CHAN_MAINSESSION:
1768 * This is treated separately, outside the switch.
1772 x11_override_throttle(c->u.x11.s, enable);
1775 /* Agent channels require no buffer management. */
1778 pfd_override_throttle(c->u.x11.s, enable);
1785 * Handle the key exchange and user authentication phases.
1787 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1791 static unsigned char *rsabuf, *keystr1, *keystr2;
1792 unsigned char cookie[8];
1793 struct RSAKey servkey, hostkey;
1794 struct MD5Context md5c;
1795 static unsigned long supported_ciphers_mask, supported_auths_mask;
1796 static int tried_publickey;
1797 static int tis_auth_refused, ccard_auth_refused;
1798 static unsigned char session_id[16];
1799 static int cipher_type;
1800 static char username[100];
1807 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1808 bombout(("Public key packet not received"));
1812 logevent("Received public keys");
1814 memcpy(cookie, pktin.body, 8);
1816 i = makekey(pktin.body + 8, &servkey, &keystr1, 0);
1817 j = makekey(pktin.body + 8 + i, &hostkey, &keystr2, 0);
1820 * Log the host key fingerprint.
1824 logevent("Host key fingerprint is:");
1825 strcpy(logmsg, " ");
1826 hostkey.comment = NULL;
1827 rsa_fingerprint(logmsg + strlen(logmsg),
1828 sizeof(logmsg) - strlen(logmsg), &hostkey);
1832 ssh1_remote_protoflags = GET_32BIT(pktin.body + 8 + i + j);
1833 supported_ciphers_mask = GET_32BIT(pktin.body + 12 + i + j);
1834 supported_auths_mask = GET_32BIT(pktin.body + 16 + i + j);
1836 ssh1_local_protoflags =
1837 ssh1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
1838 ssh1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
1841 MD5Update(&md5c, keystr2, hostkey.bytes);
1842 MD5Update(&md5c, keystr1, servkey.bytes);
1843 MD5Update(&md5c, pktin.body, 8);
1844 MD5Final(session_id, &md5c);
1846 for (i = 0; i < 32; i++)
1847 session_key[i] = random_byte();
1849 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1851 rsabuf = smalloc(len);
1853 fatalbox("Out of memory");
1856 * Verify the host key.
1860 * First format the key into a string.
1862 int len = rsastr_len(&hostkey);
1863 char fingerprint[100];
1864 char *keystr = smalloc(len);
1866 fatalbox("Out of memory");
1867 rsastr_fmt(keystr, &hostkey);
1868 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
1869 verify_ssh_host_key(savedhost, savedport, "rsa", keystr,
1874 for (i = 0; i < 32; i++) {
1875 rsabuf[i] = session_key[i];
1877 rsabuf[i] ^= session_id[i];
1880 if (hostkey.bytes > servkey.bytes) {
1881 rsaencrypt(rsabuf, 32, &servkey);
1882 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1884 rsaencrypt(rsabuf, 32, &hostkey);
1885 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1888 logevent("Encrypted session key");
1891 int cipher_chosen = 0, warn = 0;
1892 char *cipher_string = NULL;
1893 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
1894 int next_cipher = cfg.ssh_cipherlist[i];
1895 if (next_cipher == CIPHER_WARN) {
1896 /* If/when we choose a cipher, warn about it */
1898 } else if (next_cipher == CIPHER_AES) {
1899 /* XXX Probably don't need to mention this. */
1900 logevent("AES not supported in SSH1, skipping");
1902 switch (next_cipher) {
1903 case CIPHER_3DES: cipher_type = SSH_CIPHER_3DES;
1904 cipher_string = "3DES"; break;
1905 case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH;
1906 cipher_string = "Blowfish"; break;
1907 case CIPHER_DES: cipher_type = SSH_CIPHER_DES;
1908 cipher_string = "single-DES"; break;
1910 if (supported_ciphers_mask & (1 << cipher_type))
1914 if (!cipher_chosen) {
1915 if ((supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
1916 bombout(("Server violates SSH 1 protocol by not "
1917 "supporting 3DES encryption"));
1919 /* shouldn't happen */
1920 bombout(("No supported ciphers found"));
1924 /* Warn about chosen cipher if necessary. */
1926 askcipher(cipher_string, 0);
1929 switch (cipher_type) {
1930 case SSH_CIPHER_3DES:
1931 logevent("Using 3DES encryption");
1933 case SSH_CIPHER_DES:
1934 logevent("Using single-DES encryption");
1936 case SSH_CIPHER_BLOWFISH:
1937 logevent("Using Blowfish encryption");
1941 send_packet(SSH1_CMSG_SESSION_KEY,
1942 PKT_CHAR, cipher_type,
1943 PKT_DATA, cookie, 8,
1944 PKT_CHAR, (len * 8) >> 8, PKT_CHAR, (len * 8) & 0xFF,
1945 PKT_DATA, rsabuf, len,
1946 PKT_INT, ssh1_local_protoflags, PKT_END);
1948 logevent("Trying to enable encryption...");
1952 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1953 cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des;
1954 cipher->sesskey(session_key);
1958 if (pktin.type != SSH1_SMSG_SUCCESS) {
1959 bombout(("Encryption not successfully enabled"));
1963 logevent("Successfully started encryption");
1969 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1971 if (!ssh_get_line("login as: ",
1972 username, sizeof(username), FALSE)) {
1974 * get_line failed to get a username.
1977 logevent("No username provided. Abandoning session.");
1978 ssh_state = SSH_STATE_CLOSED;
1982 c_write_str("login as: ");
1985 crWaitUntil(!ispkt);
1987 switch (c = *in++) {
1996 c_write_str("\b \b");
2003 c_write_str("\b \b");
2013 if (((c >= ' ' && c <= '~') ||
2014 ((unsigned char) c >= 160))
2015 && pos < sizeof(username)-1) {
2016 username[pos++] = c;
2022 c_write_str("\r\n");
2023 username[strcspn(username, "\n\r")] = '\0';
2026 strncpy(username, cfg.username, 99);
2027 username[99] = '\0';
2030 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
2032 char userlog[22 + sizeof(username)];
2033 sprintf(userlog, "Sent username \"%s\"", username);
2035 if (flags & FLAG_INTERACTIVE &&
2036 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2037 strcat(userlog, "\r\n");
2038 c_write_str(userlog);
2045 tried_publickey = 0;
2046 tis_auth_refused = ccard_auth_refused = 0;
2048 while (pktin.type == SSH1_SMSG_FAILURE) {
2049 static char password[100];
2050 static char prompt[200];
2053 static int pwpkt_type;
2054 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2056 if (agent_exists()) {
2058 * Attempt RSA authentication using Pageant.
2060 static unsigned char request[5], *response, *p;
2061 static int responselen;
2062 static int i, nkeys;
2063 static int authed = FALSE;
2066 logevent("Pageant is running. Requesting keys.");
2068 /* Request the keys held by the agent. */
2069 PUT_32BIT(request, 1);
2070 request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2071 agent_query(request, 5, &r, &responselen);
2072 response = (unsigned char *) r;
2073 if (response && responselen >= 5 &&
2074 response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2076 nkeys = GET_32BIT(p);
2080 sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
2083 for (i = 0; i < nkeys; i++) {
2084 static struct RSAKey key;
2085 static Bignum challenge;
2086 static char *commentp;
2087 static int commentlen;
2091 sprintf(buf, "Trying Pageant key #%d", i);
2095 p += ssh1_read_bignum(p, &key.exponent);
2096 p += ssh1_read_bignum(p, &key.modulus);
2097 commentlen = GET_32BIT(p);
2101 send_packet(SSH1_CMSG_AUTH_RSA,
2102 PKT_BIGNUM, key.modulus, PKT_END);
2104 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2105 logevent("Key refused");
2108 logevent("Received RSA challenge");
2109 ssh1_read_bignum(pktin.body, &challenge);
2111 char *agentreq, *q, *ret;
2114 len = 1 + 4; /* message type, bit count */
2115 len += ssh1_bignum_length(key.exponent);
2116 len += ssh1_bignum_length(key.modulus);
2117 len += ssh1_bignum_length(challenge);
2118 len += 16; /* session id */
2119 len += 4; /* response format */
2120 agentreq = smalloc(4 + len);
2121 PUT_32BIT(agentreq, len);
2123 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2124 PUT_32BIT(q, bignum_bitcount(key.modulus));
2126 q += ssh1_write_bignum(q, key.exponent);
2127 q += ssh1_write_bignum(q, key.modulus);
2128 q += ssh1_write_bignum(q, challenge);
2129 memcpy(q, session_id, 16);
2131 PUT_32BIT(q, 1); /* response format */
2132 agent_query(agentreq, len + 4, &vret, &retlen);
2136 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2137 logevent("Sending Pageant's response");
2138 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2139 PKT_DATA, ret + 5, 16,
2143 if (pktin.type == SSH1_SMSG_SUCCESS) {
2145 ("Pageant's response accepted");
2146 if (flags & FLAG_VERBOSE) {
2148 ("Authenticated using RSA key \"");
2149 c_write(commentp, commentlen);
2150 c_write_str("\" from agent\r\n");
2155 ("Pageant's response not accepted");
2158 ("Pageant failed to answer challenge");
2162 logevent("No reply received from Pageant");
2165 freebn(key.exponent);
2166 freebn(key.modulus);
2175 if (*cfg.keyfile && !tried_publickey)
2176 pwpkt_type = SSH1_CMSG_AUTH_RSA;
2178 if (cfg.try_tis_auth &&
2179 (supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2180 !tis_auth_refused) {
2181 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2182 logevent("Requested TIS authentication");
2183 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
2185 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2186 logevent("TIS authentication declined");
2187 if (flags & FLAG_INTERACTIVE)
2188 c_write_str("TIS authentication refused.\r\n");
2189 tis_auth_refused = 1;
2192 int challengelen = ((pktin.body[0] << 24) |
2193 (pktin.body[1] << 16) |
2194 (pktin.body[2] << 8) |
2196 logevent("Received TIS challenge");
2197 if (challengelen > sizeof(prompt) - 1)
2198 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2199 memcpy(prompt, pktin.body + 4, challengelen);
2200 /* Prompt heuristic comes from OpenSSH */
2201 strncpy(prompt + challengelen,
2202 memchr(prompt, '\n', challengelen) ?
2203 "": "\r\nResponse: ",
2204 (sizeof prompt) - challengelen);
2205 prompt[(sizeof prompt) - 1] = '\0';
2208 if (cfg.try_tis_auth &&
2209 (supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2210 !ccard_auth_refused) {
2211 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2212 logevent("Requested CryptoCard authentication");
2213 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
2215 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2216 logevent("CryptoCard authentication declined");
2217 c_write_str("CryptoCard authentication refused.\r\n");
2218 ccard_auth_refused = 1;
2221 int challengelen = ((pktin.body[0] << 24) |
2222 (pktin.body[1] << 16) |
2223 (pktin.body[2] << 8) |
2225 logevent("Received CryptoCard challenge");
2226 if (challengelen > sizeof(prompt) - 1)
2227 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2228 memcpy(prompt, pktin.body + 4, challengelen);
2229 strncpy(prompt + challengelen,
2230 memchr(prompt, '\n', challengelen) ?
2231 "" : "\r\nResponse: ",
2232 sizeof(prompt) - challengelen);
2233 prompt[sizeof(prompt) - 1] = '\0';
2236 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2237 sprintf(prompt, "%.90s@%.90s's password: ",
2238 username, savedhost);
2240 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2241 char *comment = NULL;
2242 if (flags & FLAG_VERBOSE)
2243 c_write_str("Trying public key authentication.\r\n");
2244 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2245 if (flags & FLAG_VERBOSE)
2246 c_write_str("No passphrase required.\r\n");
2249 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
2254 * Show password prompt, having first obtained it via a TIS
2255 * or CryptoCard exchange if we're doing TIS or CryptoCard
2259 if (!ssh_get_line(prompt, password, sizeof(password), TRUE)) {
2261 * get_line failed to get a password (for example
2262 * because one was supplied on the command line
2263 * which has already failed to work). Terminate.
2265 send_packet(SSH1_MSG_DISCONNECT,
2266 PKT_STR, "No more passwords available to try",
2268 connection_fatal("Unable to authenticate");
2269 ssh_state = SSH_STATE_CLOSED;
2273 /* Prompt may have come from server. We've munged it a bit, so
2274 * we know it to be zero-terminated at least once. */
2275 c_write_untrusted(prompt, strlen(prompt));
2279 crWaitUntil(!ispkt);
2281 switch (c = *in++) {
2302 if (pos < sizeof(password)-1)
2303 password[pos++] = c;
2307 c_write_str("\r\n");
2311 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2313 * Try public key authentication with the specified
2316 static struct RSAKey pubkey;
2317 static Bignum challenge, response;
2319 static unsigned char buffer[32];
2321 tried_publickey = 1;
2322 i = loadrsakey(cfg.keyfile, &pubkey, password);
2324 c_write_str("Couldn't load private key from ");
2325 c_write_str(cfg.keyfile);
2326 c_write_str(".\r\n");
2327 continue; /* go and try password */
2330 c_write_str("Wrong passphrase.\r\n");
2331 tried_publickey = 0;
2332 continue; /* try again */
2336 * Send a public key attempt.
2338 send_packet(SSH1_CMSG_AUTH_RSA,
2339 PKT_BIGNUM, pubkey.modulus, PKT_END);
2342 if (pktin.type == SSH1_SMSG_FAILURE) {
2343 c_write_str("Server refused our public key.\r\n");
2344 continue; /* go and try password */
2346 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2347 bombout(("Bizarre response to offer of public key"));
2350 ssh1_read_bignum(pktin.body, &challenge);
2351 response = rsadecrypt(challenge, &pubkey);
2352 freebn(pubkey.private_exponent); /* burn the evidence */
2354 for (i = 0; i < 32; i++) {
2355 buffer[i] = bignum_byte(response, 31 - i);
2359 MD5Update(&md5c, buffer, 32);
2360 MD5Update(&md5c, session_id, 16);
2361 MD5Final(buffer, &md5c);
2363 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2364 PKT_DATA, buffer, 16, PKT_END);
2367 if (pktin.type == SSH1_SMSG_FAILURE) {
2368 if (flags & FLAG_VERBOSE)
2370 ("Failed to authenticate with our public key.\r\n");
2371 continue; /* go and try password */
2372 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2374 ("Bizarre response to RSA authentication response"));
2378 break; /* we're through! */
2380 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2382 * Defence against traffic analysis: we send a
2383 * whole bunch of packets containing strings of
2384 * different lengths. One of these strings is the
2385 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2386 * The others are all random data in
2387 * SSH1_MSG_IGNORE packets. This way a passive
2388 * listener can't tell which is the password, and
2389 * hence can't deduce the password length.
2391 * Anybody with a password length greater than 16
2392 * bytes is going to have enough entropy in their
2393 * password that a listener won't find it _that_
2394 * much help to know how long it is. So what we'll
2397 * - if password length < 16, we send 15 packets
2398 * containing string lengths 1 through 15
2400 * - otherwise, we let N be the nearest multiple
2401 * of 8 below the password length, and send 8
2402 * packets containing string lengths N through
2403 * N+7. This won't obscure the order of
2404 * magnitude of the password length, but it will
2405 * introduce a bit of extra uncertainty.
2407 * A few servers (the old 1.2.18 through 1.2.22)
2408 * can't deal with SSH1_MSG_IGNORE. For these
2409 * servers, we need an alternative defence. We make
2410 * use of the fact that the password is interpreted
2411 * as a C string: so we can append a NUL, then some
2414 * One server (a Cisco one) can deal with neither
2415 * SSH1_MSG_IGNORE _nor_ a padded password string.
2416 * For this server we are left with no defences
2417 * against password length sniffing.
2419 if (!(ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2421 * The server can deal with SSH1_MSG_IGNORE, so
2422 * we can use the primary defence.
2424 int bottom, top, pwlen, i;
2427 pwlen = strlen(password);
2429 bottom = 0; /* zero length passwords are OK! :-) */
2432 bottom = pwlen & ~7;
2436 assert(pwlen >= bottom && pwlen <= top);
2438 randomstr = smalloc(top + 1);
2440 for (i = bottom; i <= top; i++) {
2442 defer_packet(pwpkt_type, PKT_STR, password,
2445 for (j = 0; j < i; j++) {
2447 randomstr[j] = random_byte();
2448 } while (randomstr[j] == '\0');
2450 randomstr[i] = '\0';
2451 defer_packet(SSH1_MSG_IGNORE,
2452 PKT_STR, randomstr, PKT_END);
2455 logevent("Sending password with camouflage packets");
2456 ssh_pkt_defersend();
2458 else if (!(ssh_remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2460 * The server can't deal with SSH1_MSG_IGNORE
2461 * but can deal with padded passwords, so we
2462 * can use the secondary defence.
2468 len = strlen(password);
2469 if (len < sizeof(string)) {
2471 strcpy(string, password);
2472 len++; /* cover the zero byte */
2473 while (len < sizeof(string)) {
2474 string[len++] = (char) random_byte();
2479 logevent("Sending length-padded password");
2480 send_packet(pwpkt_type, PKT_INT, len,
2481 PKT_DATA, s, len, PKT_END);
2484 * The server has _both_
2485 * BUG_CHOKES_ON_SSH1_IGNORE and
2486 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2487 * therefore nothing we can do.
2490 len = strlen(password);
2491 logevent("Sending unpadded password");
2492 send_packet(pwpkt_type, PKT_INT, len,
2493 PKT_DATA, password, len, PKT_END);
2496 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
2499 logevent("Sent password");
2500 memset(password, 0, strlen(password));
2502 if (pktin.type == SSH1_SMSG_FAILURE) {
2503 if (flags & FLAG_VERBOSE)
2504 c_write_str("Access denied\r\n");
2505 logevent("Authentication refused");
2506 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2507 logevent("Received disconnect request");
2508 ssh_state = SSH_STATE_CLOSED;
2510 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2511 bombout(("Strange packet received, type %d", pktin.type));
2516 logevent("Authentication successful");
2521 void sshfwd_close(struct ssh_channel *c)
2523 if (c && !c->closes) {
2525 * If the channel's remoteid is -1, we have sent
2526 * CHANNEL_OPEN for this channel, but it hasn't even been
2527 * acknowledged by the server. So we must set a close flag
2528 * on it now, and then when the server acks the channel
2529 * open, we can close it then.
2531 if (c->remoteid != -1) {
2532 if (ssh_version == 1) {
2533 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2536 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2537 ssh2_pkt_adduint32(c->remoteid);
2542 if (c->type == CHAN_X11) {
2544 logevent("Forwarded X11 connection terminated");
2545 } else if (c->type == CHAN_SOCKDATA ||
2546 c->type == CHAN_SOCKDATA_DORMANT) {
2548 logevent("Forwarded port closed");
2553 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2555 if (ssh_version == 1) {
2556 send_packet(SSH1_MSG_CHANNEL_DATA,
2557 PKT_INT, c->remoteid,
2558 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2560 * In SSH1 we can return 0 here - implying that forwarded
2561 * connections are never individually throttled - because
2562 * the only circumstance that can cause throttling will be
2563 * the whole SSH connection backing up, in which case
2564 * _everything_ will be throttled as a whole.
2568 ssh2_add_channel_data(c, buf, len);
2569 return ssh2_try_send(c);
2573 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2575 if (ssh_version == 1) {
2576 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2577 c->v.v1.throttling = 0;
2581 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2585 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt)
2591 while (!do_ssh1_login(in, inlen, ispkt)) {
2594 if (ssh_state == SSH_STATE_CLOSED)
2597 if (cfg.agentfwd && agent_exists()) {
2598 logevent("Requesting agent forwarding");
2599 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2603 if (pktin.type != SSH1_SMSG_SUCCESS
2604 && pktin.type != SSH1_SMSG_FAILURE) {
2605 bombout(("Protocol confusion"));
2607 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2608 logevent("Agent forwarding refused");
2610 logevent("Agent forwarding enabled");
2611 ssh_agentfwd_enabled = TRUE;
2615 if (cfg.x11_forward) {
2616 char proto[20], data[64];
2617 logevent("Requesting X11 forwarding");
2618 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2619 if (ssh1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
2620 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2621 PKT_STR, proto, PKT_STR, data,
2622 PKT_INT, 0, PKT_END);
2624 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2625 PKT_STR, proto, PKT_STR, data, PKT_END);
2630 if (pktin.type != SSH1_SMSG_SUCCESS
2631 && pktin.type != SSH1_SMSG_FAILURE) {
2632 bombout(("Protocol confusion"));
2634 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2635 logevent("X11 forwarding refused");
2637 logevent("X11 forwarding enabled");
2638 ssh_X11_fwd_enabled = TRUE;
2646 char sports[256], dports[256], host[256];
2649 ssh_rportfwds = newtree234(ssh_rportcmp_ssh1);
2650 /* Add port forwardings. */
2655 while (*e && *e != '\t')
2661 while (*e && *e != ':')
2671 dport = atoi(dports);
2672 sport = atoi(sports);
2673 if (sport && dport) {
2675 pfd_addforward(host, dport, sport);
2676 sprintf(buf, "Local port %d forwarding to %s:%d",
2677 sport, host, dport);
2680 struct ssh_rportfwd *pf;
2681 pf = smalloc(sizeof(*pf));
2682 strcpy(pf->dhost, host);
2684 if (add234(ssh_rportfwds, pf) != pf) {
2686 "Duplicate remote port forwarding to %s:%d",
2691 sprintf(buf, "Requesting remote port %d forward to %s:%d",
2692 sport, host, dport);
2694 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST,
2706 send_packet(SSH1_CMSG_REQUEST_PTY,
2707 PKT_STR, cfg.termtype,
2708 PKT_INT, rows, PKT_INT, cols,
2709 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
2710 ssh_state = SSH_STATE_INTERMED;
2714 if (pktin.type != SSH1_SMSG_SUCCESS
2715 && pktin.type != SSH1_SMSG_FAILURE) {
2716 bombout(("Protocol confusion"));
2718 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2719 c_write_str("Server refused to allocate pty\r\n");
2720 ssh_editing = ssh_echoing = 1;
2722 logevent("Allocated pty");
2724 ssh_editing = ssh_echoing = 1;
2727 if (cfg.compression) {
2728 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
2732 if (pktin.type != SSH1_SMSG_SUCCESS
2733 && pktin.type != SSH1_SMSG_FAILURE) {
2734 bombout(("Protocol confusion"));
2736 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2737 c_write_str("Server refused to compress\r\n");
2739 logevent("Started compression");
2740 ssh1_compressing = TRUE;
2741 zlib_compress_init();
2742 zlib_decompress_init();
2746 * Start the shell or command.
2748 * Special case: if the first-choice command is an SSH2
2749 * subsystem (hence not usable here) and the second choice
2750 * exists, we fall straight back to that.
2753 char *cmd = cfg.remote_cmd_ptr;
2755 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
2756 cmd = cfg.remote_cmd_ptr2;
2757 ssh_fallback_cmd = TRUE;
2760 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
2762 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
2763 logevent("Started session");
2766 ssh_state = SSH_STATE_SESSION;
2770 ssh_special(TS_EOF);
2772 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
2774 ssh_channels = newtree234(ssh_channelcmp);
2778 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
2779 pktin.type == SSH1_SMSG_STDERR_DATA) {
2780 long len = GET_32BIT(pktin.body);
2782 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
2783 pktin.body + 4, len);
2784 if (!ssh1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
2785 ssh1_stdout_throttling = 1;
2788 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2789 ssh_state = SSH_STATE_CLOSED;
2790 logevent("Received disconnect request");
2792 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
2793 /* Remote side is trying to open a channel to talk to our
2794 * X-Server. Give them back a local channel number. */
2795 struct ssh_channel *c;
2797 logevent("Received X11 connect request");
2798 /* Refuse if X11 forwarding is disabled. */
2799 if (!ssh_X11_fwd_enabled) {
2800 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2801 PKT_INT, GET_32BIT(pktin.body), PKT_END);
2802 logevent("Rejected X11 connect request");
2804 c = smalloc(sizeof(struct ssh_channel));
2806 if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
2807 logevent("opening X11 forward connection failed");
2809 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2810 PKT_INT, GET_32BIT(pktin.body),
2814 ("opening X11 forward connection succeeded");
2815 c->remoteid = GET_32BIT(pktin.body);
2816 c->localid = alloc_channel_id();
2818 c->v.v1.throttling = 0;
2819 c->type = CHAN_X11; /* identify channel type */
2820 add234(ssh_channels, c);
2821 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2822 PKT_INT, c->remoteid, PKT_INT,
2823 c->localid, PKT_END);
2824 logevent("Opened X11 forward channel");
2827 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
2828 /* Remote side is trying to open a channel to talk to our
2829 * agent. Give them back a local channel number. */
2830 struct ssh_channel *c;
2832 /* Refuse if agent forwarding is disabled. */
2833 if (!ssh_agentfwd_enabled) {
2834 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2835 PKT_INT, GET_32BIT(pktin.body), PKT_END);
2837 c = smalloc(sizeof(struct ssh_channel));
2838 c->remoteid = GET_32BIT(pktin.body);
2839 c->localid = alloc_channel_id();
2841 c->v.v1.throttling = 0;
2842 c->type = CHAN_AGENT; /* identify channel type */
2843 c->u.a.lensofar = 0;
2844 add234(ssh_channels, c);
2845 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2846 PKT_INT, c->remoteid, PKT_INT, c->localid,
2849 } else if (pktin.type == SSH1_MSG_PORT_OPEN) {
2850 /* Remote side is trying to open a channel to talk to a
2851 * forwarded port. Give them back a local channel number. */
2852 struct ssh_channel *c;
2853 struct ssh_rportfwd pf;
2855 char host[256], buf[1024];
2857 c = smalloc(sizeof(struct ssh_channel));
2859 hostsize = GET_32BIT(pktin.body+4);
2860 for(h = host, p = pktin.body+8; hostsize != 0; hostsize--) {
2861 if (h+1 < host+sizeof(host))
2866 port = GET_32BIT(p);
2868 strcpy(pf.dhost, host);
2871 if (find234(ssh_rportfwds, &pf, NULL) == NULL) {
2872 sprintf(buf, "Rejected remote port open request for %s:%d",
2875 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2876 PKT_INT, GET_32BIT(pktin.body), PKT_END);
2878 sprintf(buf, "Received remote port open request for %s:%d",
2881 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
2884 sprintf(buf, "Port open failed: %s", e);
2887 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2888 PKT_INT, GET_32BIT(pktin.body),
2891 c->remoteid = GET_32BIT(pktin.body);
2892 c->localid = alloc_channel_id();
2894 c->v.v1.throttling = 0;
2895 c->type = CHAN_SOCKDATA; /* identify channel type */
2896 add234(ssh_channels, c);
2897 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2898 PKT_INT, c->remoteid, PKT_INT,
2899 c->localid, PKT_END);
2900 logevent("Forwarded port opened successfully");
2904 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
2905 unsigned int remoteid = GET_32BIT(pktin.body);
2906 unsigned int localid = GET_32BIT(pktin.body+4);
2907 struct ssh_channel *c;
2909 c = find234(ssh_channels, &remoteid, ssh_channelfind);
2910 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
2911 c->remoteid = localid;
2912 c->type = CHAN_SOCKDATA;
2913 c->v.v1.throttling = 0;
2914 pfd_confirm(c->u.pfd.s);
2917 if (c && c->closes) {
2919 * We have a pending close on this channel,
2920 * which we decided on before the server acked
2921 * the channel open. So now we know the
2922 * remoteid, we can close it again.
2924 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2928 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
2929 unsigned int remoteid = GET_32BIT(pktin.body);
2930 unsigned int localid = GET_32BIT(pktin.body+4);
2931 struct ssh_channel *c;
2933 c = find234(ssh_channels, &remoteid, ssh_channelfind);
2934 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
2935 logevent("Forwarded connection refused by server");
2936 pfd_close(c->u.pfd.s);
2937 del234(ssh_channels, c);
2941 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2942 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
2943 /* Remote side closes a channel. */
2944 unsigned i = GET_32BIT(pktin.body);
2945 struct ssh_channel *c;
2946 c = find234(ssh_channels, &i, ssh_channelfind);
2950 (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2951 if (!(c->closes & closetype))
2952 send_packet(pktin.type, PKT_INT, c->remoteid,
2954 if ((c->closes == 0) && (c->type == CHAN_X11)) {
2955 logevent("Forwarded X11 connection terminated");
2956 assert(c->u.x11.s != NULL);
2957 x11_close(c->u.x11.s);
2960 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
2961 logevent("Forwarded port closed");
2962 assert(c->u.pfd.s != NULL);
2963 pfd_close(c->u.pfd.s);
2966 c->closes |= closetype;
2967 if (c->closes == 3) {
2968 del234(ssh_channels, c);
2972 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2973 /* Data sent down one of our channels. */
2974 int i = GET_32BIT(pktin.body);
2975 int len = GET_32BIT(pktin.body + 4);
2976 unsigned char *p = pktin.body + 8;
2977 struct ssh_channel *c;
2978 c = find234(ssh_channels, &i, ssh_channelfind);
2983 bufsize = x11_send(c->u.x11.s, p, len);
2986 bufsize = pfd_send(c->u.pfd.s, p, len);
2989 /* Data for an agent message. Buffer it. */
2991 if (c->u.a.lensofar < 4) {
2992 int l = min(4 - c->u.a.lensofar, len);
2993 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
2997 c->u.a.lensofar += l;
2999 if (c->u.a.lensofar == 4) {
3001 4 + GET_32BIT(c->u.a.msglen);
3002 c->u.a.message = smalloc(c->u.a.totallen);
3003 memcpy(c->u.a.message, c->u.a.msglen, 4);
3005 if (c->u.a.lensofar >= 4 && len > 0) {
3007 min(c->u.a.totallen - c->u.a.lensofar,
3009 memcpy(c->u.a.message + c->u.a.lensofar, p,
3013 c->u.a.lensofar += l;
3015 if (c->u.a.lensofar == c->u.a.totallen) {
3016 void *reply, *sentreply;
3018 agent_query(c->u.a.message,
3019 c->u.a.totallen, &reply,
3024 /* Fake SSH_AGENT_FAILURE. */
3025 sentreply = "\0\0\0\1\5";
3028 send_packet(SSH1_MSG_CHANNEL_DATA,
3029 PKT_INT, c->remoteid,
3031 PKT_DATA, sentreply, replylen,
3035 sfree(c->u.a.message);
3036 c->u.a.lensofar = 0;
3039 bufsize = 0; /* agent channels never back up */
3042 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3043 c->v.v1.throttling = 1;
3047 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
3048 /* may be from EXEC_SHELL on some servers */
3049 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3050 /* may be from EXEC_SHELL on some servers
3051 * if no pty is available or in other odd cases. Ignore */
3052 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
3053 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3055 * In case `helpful' firewalls or proxies tack
3056 * extra human-readable text on the end of the
3057 * session which we might mistake for another
3058 * encrypted packet, we close the session once
3059 * we've sent EXIT_CONFIRMATION.
3061 ssh_state = SSH_STATE_CLOSED;
3064 bombout(("Strange packet received: type %d", pktin.type));
3069 int len = min(inlen, 512);
3070 send_packet(SSH1_CMSG_STDIN_DATA,
3071 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3082 * Utility routine for decoding comma-separated strings in KEXINIT.
3084 static int in_commasep_string(char *needle, char *haystack, int haylen)
3086 int needlen = strlen(needle);
3089 * Is it at the start of the string?
3091 if (haylen >= needlen && /* haystack is long enough */
3092 !memcmp(needle, haystack, needlen) && /* initial match */
3093 (haylen == needlen || haystack[needlen] == ',')
3094 /* either , or EOS follows */
3098 * If not, search for the next comma and resume after that.
3099 * If no comma found, terminate.
3101 while (haylen > 0 && *haystack != ',')
3102 haylen--, haystack++;
3105 haylen--, haystack++; /* skip over comma itself */
3110 * SSH2 key creation method.
3112 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr,
3116 /* First 20 bytes. */
3119 SHA_Bytes(&s, H, 20);
3120 SHA_Bytes(&s, &chr, 1);
3121 SHA_Bytes(&s, sessid, 20);
3122 SHA_Final(&s, keyspace);
3123 /* Next 20 bytes. */
3126 SHA_Bytes(&s, H, 20);
3127 SHA_Bytes(&s, keyspace, 20);
3128 SHA_Final(&s, keyspace + 20);
3132 * Handle the SSH2 transport layer.
3134 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
3136 static int i, j, len, nbits, pbits, warn;
3138 static Bignum p, g, e, f, K;
3139 static int kex_init_value, kex_reply_value;
3140 static const struct ssh_mac **maclist;
3142 static const struct ssh2_cipher *cscipher_tobe = NULL;
3143 static const struct ssh2_cipher *sccipher_tobe = NULL;
3144 static const struct ssh_mac *csmac_tobe = NULL;
3145 static const struct ssh_mac *scmac_tobe = NULL;
3146 static const struct ssh_compress *cscomp_tobe = NULL;
3147 static const struct ssh_compress *sccomp_tobe = NULL;
3148 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
3149 static int hostkeylen, siglen;
3150 static void *hkey; /* actual host key */
3151 static unsigned char exchange_hash[20];
3152 static unsigned char keyspace[40];
3153 static int n_preferred_ciphers;
3154 static const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3155 static const struct ssh_compress *preferred_comp;
3156 static int first_kex;
3163 * Set up the preferred ciphers. (NULL => warn below here)
3165 n_preferred_ciphers = 0;
3166 for (i = 0; i < CIPHER_MAX; i++) {
3167 switch (cfg.ssh_cipherlist[i]) {
3168 case CIPHER_BLOWFISH:
3169 preferred_ciphers[n_preferred_ciphers] = &ssh2_blowfish;
3170 n_preferred_ciphers++;
3173 preferred_ciphers[n_preferred_ciphers] = &ssh2_des;
3174 n_preferred_ciphers++;
3177 preferred_ciphers[n_preferred_ciphers] = &ssh2_3des;
3178 n_preferred_ciphers++;
3181 preferred_ciphers[n_preferred_ciphers] = &ssh2_aes;
3182 n_preferred_ciphers++;
3185 /* Flag for later. Don't bother if it's the last in
3187 if (i < CIPHER_MAX - 1) {
3188 preferred_ciphers[n_preferred_ciphers] = NULL;
3189 n_preferred_ciphers++;
3196 * Set up preferred compression.
3198 if (cfg.compression)
3199 preferred_comp = &ssh_zlib;
3201 preferred_comp = &ssh_comp_none;
3204 * Be prepared to work around the buggy MAC problem.
3206 if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
3207 maclist = buggymacs, nmacs = lenof(buggymacs);
3209 maclist = macs, nmacs = lenof(macs);
3213 * Construct and send our key exchange packet.
3215 ssh2_pkt_init(SSH2_MSG_KEXINIT);
3216 for (i = 0; i < 16; i++)
3217 ssh2_pkt_addbyte((unsigned char) random_byte());
3218 /* List key exchange algorithms. */
3219 ssh2_pkt_addstring_start();
3220 for (i = 0; i < lenof(kex_algs); i++) {
3221 ssh2_pkt_addstring_str(kex_algs[i]->name);
3222 if (i < lenof(kex_algs) - 1)
3223 ssh2_pkt_addstring_str(",");
3225 /* List server host key algorithms. */
3226 ssh2_pkt_addstring_start();
3227 for (i = 0; i < lenof(hostkey_algs); i++) {
3228 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
3229 if (i < lenof(hostkey_algs) - 1)
3230 ssh2_pkt_addstring_str(",");
3232 /* List client->server encryption algorithms. */
3233 ssh2_pkt_addstring_start();
3234 for (i = 0; i < n_preferred_ciphers; i++) {
3235 const struct ssh2_ciphers *c = preferred_ciphers[i];
3236 if (!c) continue; /* warning flag */
3237 for (j = 0; j < c->nciphers; j++) {
3238 ssh2_pkt_addstring_str(c->list[j]->name);
3239 if (i < n_preferred_ciphers || j < c->nciphers - 1)
3240 ssh2_pkt_addstring_str(",");
3243 /* List server->client encryption algorithms. */
3244 ssh2_pkt_addstring_start();
3245 for (i = 0; i < n_preferred_ciphers; i++) {
3246 const struct ssh2_ciphers *c = preferred_ciphers[i];
3247 if (!c) continue; /* warning flag */
3248 for (j = 0; j < c->nciphers; j++) {
3249 ssh2_pkt_addstring_str(c->list[j]->name);
3250 if (i < n_preferred_ciphers || j < c->nciphers - 1)
3251 ssh2_pkt_addstring_str(",");
3254 /* List client->server MAC algorithms. */
3255 ssh2_pkt_addstring_start();
3256 for (i = 0; i < nmacs; i++) {
3257 ssh2_pkt_addstring_str(maclist[i]->name);
3259 ssh2_pkt_addstring_str(",");
3261 /* List server->client MAC algorithms. */
3262 ssh2_pkt_addstring_start();
3263 for (i = 0; i < nmacs; i++) {
3264 ssh2_pkt_addstring_str(maclist[i]->name);
3266 ssh2_pkt_addstring_str(",");
3268 /* List client->server compression algorithms. */
3269 ssh2_pkt_addstring_start();
3270 for (i = 0; i < lenof(compressions) + 1; i++) {
3271 const struct ssh_compress *c =
3272 i == 0 ? preferred_comp : compressions[i - 1];
3273 ssh2_pkt_addstring_str(c->name);
3274 if (i < lenof(compressions))
3275 ssh2_pkt_addstring_str(",");
3277 /* List server->client compression algorithms. */
3278 ssh2_pkt_addstring_start();
3279 for (i = 0; i < lenof(compressions) + 1; i++) {
3280 const struct ssh_compress *c =
3281 i == 0 ? preferred_comp : compressions[i - 1];
3282 ssh2_pkt_addstring_str(c->name);
3283 if (i < lenof(compressions))
3284 ssh2_pkt_addstring_str(",");
3286 /* List client->server languages. Empty list. */
3287 ssh2_pkt_addstring_start();
3288 /* List server->client languages. Empty list. */
3289 ssh2_pkt_addstring_start();
3290 /* First KEX packet does _not_ follow, because we're not that brave. */
3291 ssh2_pkt_addbool(FALSE);
3293 ssh2_pkt_adduint32(0);
3295 exhash = exhashbase;
3296 sha_string(&exhash, pktout.data + 5, pktout.length - 5);
3302 sha_string(&exhash, pktin.data + 5, pktin.length - 5);
3305 * Now examine the other side's KEXINIT to see what we're up
3308 if (pktin.type != SSH2_MSG_KEXINIT) {
3309 bombout(("expected key exchange packet from server"));
3314 cscipher_tobe = NULL;
3315 sccipher_tobe = NULL;
3320 pktin.savedpos += 16; /* skip garbage cookie */
3321 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
3322 for (i = 0; i < lenof(kex_algs); i++) {
3323 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3328 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
3329 for (i = 0; i < lenof(hostkey_algs); i++) {
3330 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3331 hostkey = hostkey_algs[i];
3335 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
3337 for (i = 0; i < n_preferred_ciphers; i++) {
3338 const struct ssh2_ciphers *c = preferred_ciphers[i];
3342 for (j = 0; j < c->nciphers; j++) {
3343 if (in_commasep_string(c->list[j]->name, str, len)) {
3344 cscipher_tobe = c->list[j];
3349 if (cscipher_tobe) {
3351 askcipher(cscipher_tobe->name, 1);
3355 if (!cscipher_tobe) {
3356 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str));
3360 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
3362 for (i = 0; i < n_preferred_ciphers; i++) {
3363 const struct ssh2_ciphers *c = preferred_ciphers[i];
3367 for (j = 0; j < c->nciphers; j++) {
3368 if (in_commasep_string(c->list[j]->name, str, len)) {
3369 sccipher_tobe = c->list[j];
3374 if (sccipher_tobe) {
3376 askcipher(sccipher_tobe->name, 2);
3380 if (!sccipher_tobe) {
3381 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str));
3385 ssh2_pkt_getstring(&str, &len); /* client->server mac */
3386 for (i = 0; i < nmacs; i++) {
3387 if (in_commasep_string(maclist[i]->name, str, len)) {
3388 csmac_tobe = maclist[i];
3392 ssh2_pkt_getstring(&str, &len); /* server->client mac */
3393 for (i = 0; i < nmacs; i++) {
3394 if (in_commasep_string(maclist[i]->name, str, len)) {
3395 scmac_tobe = maclist[i];
3399 ssh2_pkt_getstring(&str, &len); /* client->server compression */
3400 for (i = 0; i < lenof(compressions) + 1; i++) {
3401 const struct ssh_compress *c =
3402 i == 0 ? preferred_comp : compressions[i - 1];
3403 if (in_commasep_string(c->name, str, len)) {
3408 ssh2_pkt_getstring(&str, &len); /* server->client compression */
3409 for (i = 0; i < lenof(compressions) + 1; i++) {
3410 const struct ssh_compress *c =
3411 i == 0 ? preferred_comp : compressions[i - 1];
3412 if (in_commasep_string(c->name, str, len)) {
3419 * Work out the number of bits of key we will need from the key
3420 * exchange. We start with the maximum key length of either
3426 csbits = cscipher_tobe->keylen;
3427 scbits = sccipher_tobe->keylen;
3428 nbits = (csbits > scbits ? csbits : scbits);
3430 /* The keys only have 160-bit entropy, since they're based on
3431 * a SHA-1 hash. So cap the key size at 160 bits. */
3436 * If we're doing Diffie-Hellman group exchange, start by
3437 * requesting a group.
3439 if (kex == &ssh_diffiehellman_gex) {
3440 logevent("Doing Diffie-Hellman group exchange");
3442 * Work out how big a DH group we will need to allow that
3445 pbits = 512 << ((nbits - 1) / 64);
3446 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
3447 ssh2_pkt_adduint32(pbits);
3451 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3452 bombout(("expected key exchange group packet from server"));
3455 p = ssh2_pkt_getmp();
3456 g = ssh2_pkt_getmp();
3457 dh_setup_group(p, g);
3458 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3459 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3462 kex_init_value = SSH2_MSG_KEXDH_INIT;
3463 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3466 logevent("Doing Diffie-Hellman key exchange");
3468 * Now generate and send e for Diffie-Hellman.
3470 e = dh_create_e(nbits * 2);
3471 ssh2_pkt_init(kex_init_value);
3476 if (pktin.type != kex_reply_value) {
3477 bombout(("expected key exchange reply packet from server"));
3480 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
3481 f = ssh2_pkt_getmp();
3482 ssh2_pkt_getstring(&sigdata, &siglen);
3486 sha_string(&exhash, hostkeydata, hostkeylen);
3487 if (kex == &ssh_diffiehellman_gex) {
3488 sha_uint32(&exhash, pbits);
3489 sha_mpint(&exhash, p);
3490 sha_mpint(&exhash, g);
3492 sha_mpint(&exhash, e);
3493 sha_mpint(&exhash, f);
3494 sha_mpint(&exhash, K);
3495 SHA_Final(&exhash, exchange_hash);
3500 debug(("Exchange hash is:\n"));
3501 dmemdump(exchange_hash, 20);
3504 hkey = hostkey->newkey(hostkeydata, hostkeylen);
3506 !hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
3507 bombout(("Server's host key did not match the signature supplied"));
3512 * Authenticate remote host: verify host key. (We've already
3513 * checked the signature of the exchange hash.)
3515 keystr = hostkey->fmtkey(hkey);
3516 fingerprint = hostkey->fingerprint(hkey);
3517 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
3518 keystr, fingerprint);
3519 if (first_kex) { /* don't bother logging this in rekeys */
3520 logevent("Host key fingerprint is:");
3521 logevent(fingerprint);
3525 hostkey->freekey(hkey);
3528 * Send SSH2_MSG_NEWKEYS.
3530 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
3534 * Expect SSH2_MSG_NEWKEYS from server.
3537 if (pktin.type != SSH2_MSG_NEWKEYS) {
3538 bombout(("expected new-keys packet from server"));
3543 * Create and initialise session keys.
3545 cscipher = cscipher_tobe;
3546 sccipher = sccipher_tobe;
3549 cscomp = cscomp_tobe;
3550 sccomp = sccomp_tobe;
3551 cscomp->compress_init();
3552 sccomp->decompress_init();
3554 * Set IVs after keys. Here we use the exchange hash from the
3555 * _first_ key exchange.
3558 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
3559 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
3560 cscipher->setcskey(keyspace);
3561 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
3562 sccipher->setsckey(keyspace);
3563 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
3564 cscipher->setcsiv(keyspace);
3565 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
3566 sccipher->setsciv(keyspace);
3567 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
3568 csmac->setcskey(keyspace);
3569 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
3570 scmac->setsckey(keyspace);
3573 * If this is the first key exchange phase, we must pass the
3574 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3575 * wants to see it but because it will need time to initialise
3576 * itself before it sees an actual packet. In subsequent key
3577 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3578 * it would only confuse the layer above.
3586 * Now we're encrypting. Begin returning 1 to the protocol main
3587 * function so that other things can run on top of the
3588 * transport. If we ever see a KEXINIT, we must go back to the
3591 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
3594 logevent("Server initiated key re-exchange");
3595 goto begin_key_exchange;
3601 * Add data to an SSH2 channel output buffer.
3603 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
3606 bufchain_add(&c->v.v2.outbuffer, buf, len);
3610 * Attempt to send data on an SSH2 channel.
3612 static int ssh2_try_send(struct ssh_channel *c)
3614 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
3617 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
3618 if ((unsigned)len > c->v.v2.remwindow)
3619 len = c->v.v2.remwindow;
3620 if ((unsigned)len > c->v.v2.remmaxpkt)
3621 len = c->v.v2.remmaxpkt;
3622 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
3623 ssh2_pkt_adduint32(c->remoteid);
3624 ssh2_pkt_addstring_start();
3625 ssh2_pkt_addstring_data(data, len);
3627 bufchain_consume(&c->v.v2.outbuffer, len);
3628 c->v.v2.remwindow -= len;
3632 * After having sent as much data as we can, return the amount
3635 return bufchain_size(&c->v.v2.outbuffer);
3639 * Potentially enlarge the window on an SSH2 channel.
3641 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
3643 if (newwin > c->v.v2.locwindow) {
3644 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3645 ssh2_pkt_adduint32(c->remoteid);
3646 ssh2_pkt_adduint32(newwin - c->v.v2.locwindow);
3648 c->v.v2.locwindow = newwin;
3653 * Handle the SSH2 userauth and connection layers.
3655 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
3658 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
3660 AUTH_KEYBOARD_INTERACTIVE
3664 AUTH_TYPE_PUBLICKEY,
3665 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
3666 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
3668 AUTH_TYPE_KEYBOARD_INTERACTIVE,
3669 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
3671 static int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
3672 static int tried_pubkey_config, tried_agent, tried_keyb_inter;
3673 static int kbd_inter_running;
3674 static int we_are_in;
3675 static int num_prompts, echo;
3676 static char username[100];
3677 static char pwprompt[200];
3678 static char password[100];
3683 * Request userauth protocol, and await a response to it.
3685 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
3686 ssh2_pkt_addstring("ssh-userauth");
3688 crWaitUntilV(ispkt);
3689 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
3690 bombout(("Server refused user authentication protocol"));
3695 * We repeat this whole loop, including the username prompt,
3696 * until we manage a successful authentication. If the user
3697 * types the wrong _password_, they are sent back to the
3698 * beginning to try another username. (If they specify a
3699 * username in the config, they are never asked, even if they
3700 * do give a wrong password.)
3702 * I think this best serves the needs of
3704 * - the people who have no configuration, no keys, and just
3705 * want to try repeated (username,password) pairs until they
3706 * type both correctly
3708 * - people who have keys and configuration but occasionally
3709 * need to fall back to passwords
3711 * - people with a key held in Pageant, who might not have
3712 * logged in to a particular machine before; so they want to
3713 * type a username, and then _either_ their key will be
3714 * accepted, _or_ they will type a password. If they mistype
3715 * the username they will want to be able to get back and
3726 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
3728 if (!ssh_get_line("login as: ",
3729 username, sizeof(username), FALSE)) {
3731 * get_line failed to get a username.
3734 logevent("No username provided. Abandoning session.");
3735 ssh_state = SSH_STATE_CLOSED;
3739 c_write_str("login as: ");
3742 crWaitUntilV(!ispkt);
3744 switch (c = *in++) {
3753 c_write_str("\b \b");
3760 c_write_str("\b \b");
3770 if (((c >= ' ' && c <= '~') ||
3771 ((unsigned char) c >= 160))
3772 && pos < sizeof(username)-1) {
3773 username[pos++] = c;
3780 c_write_str("\r\n");
3781 username[strcspn(username, "\n\r")] = '\0';
3784 strncpy(username, cfg.username, 99);
3785 username[99] = '\0';
3786 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3787 sprintf(stuff, "Using username \"%s\".\r\n", username);
3793 * Send an authentication request using method "none": (a)
3794 * just in case it succeeds, and (b) so that we know what
3795 * authentication methods we can usefully try next.
3797 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3798 ssh2_pkt_addstring(username);
3799 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3800 ssh2_pkt_addstring("none"); /* method */
3802 type = AUTH_TYPE_NONE;
3806 tried_pubkey_config = FALSE;
3807 tried_agent = FALSE;
3808 tried_keyb_inter = FALSE;
3809 kbd_inter_running = FALSE;
3813 * Wait for the result of the last authentication request.
3816 crWaitUntilV(ispkt);
3817 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
3821 * Don't show the banner if we're operating in
3822 * non-verbose non-interactive mode. (It's probably
3823 * a script, which means nobody will read the
3824 * banner _anyway_, and moreover the printing of
3825 * the banner will screw up processing on the
3826 * output of (say) plink.)
3828 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
3829 ssh2_pkt_getstring(&banner, &size);
3831 c_write_untrusted(banner, size);
3833 crWaitUntilV(ispkt);
3835 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
3836 logevent("Access granted");
3841 if (kbd_inter_running &&
3842 pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
3844 * This is a further prompt in keyboard-interactive
3845 * authentication. Do nothing.
3847 } else if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
3848 bombout(("Strange packet received during authentication: type %d",
3856 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3857 * we can look at the string in it and know what we can
3858 * helpfully try next.
3860 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
3863 ssh2_pkt_getstring(&methods, &methlen);
3864 kbd_inter_running = FALSE;
3865 if (!ssh2_pkt_getbool()) {
3867 * We have received an unequivocal Access
3868 * Denied. This can translate to a variety of
3871 * - if we'd just tried "none" authentication,
3872 * it's not worth printing anything at all
3874 * - if we'd just tried a public key _offer_,
3875 * the message should be "Server refused our
3876 * key" (or no message at all if the key
3877 * came from Pageant)
3879 * - if we'd just tried anything else, the
3880 * message really should be "Access denied".
3882 * Additionally, if we'd just tried password
3883 * authentication, we should break out of this
3884 * whole loop so as to go back to the username
3887 if (type == AUTH_TYPE_NONE) {
3889 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
3890 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
3891 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
3892 c_write_str("Server refused our key\r\n");
3893 logevent("Server refused public key");
3894 } else if (type == AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
3895 /* server declined keyboard-interactive; ignore */
3897 c_write_str("Access denied\r\n");
3898 logevent("Access denied");
3899 if (type == AUTH_TYPE_PASSWORD) {
3905 c_write_str("Further authentication required\r\n");
3906 logevent("Further authentication required");
3910 in_commasep_string("publickey", methods, methlen);
3912 in_commasep_string("password", methods, methlen);
3914 in_commasep_string("keyboard-interactive", methods, methlen);
3919 if (!method && can_pubkey && agent_exists() && !tried_agent) {
3921 * Attempt public-key authentication using Pageant.
3923 static unsigned char request[5], *response, *p;
3924 static int responselen;
3925 static int i, nkeys;
3926 static int authed = FALSE;
3931 logevent("Pageant is running. Requesting keys.");
3933 /* Request the keys held by the agent. */
3934 PUT_32BIT(request, 1);
3935 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
3936 agent_query(request, 5, &r, &responselen);
3937 response = (unsigned char *) r;
3938 if (response && responselen >= 5 &&
3939 response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
3941 nkeys = GET_32BIT(p);
3945 sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
3948 for (i = 0; i < nkeys; i++) {
3949 static char *pkblob, *alg, *commentp;
3950 static int pklen, alglen, commentlen;
3951 static int siglen, retlen, len;
3952 static char *q, *agentreq, *ret;
3957 sprintf(buf, "Trying Pageant key #%d", i);
3960 pklen = GET_32BIT(p);
3964 alglen = GET_32BIT(pkblob);
3966 commentlen = GET_32BIT(p);
3970 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3971 ssh2_pkt_addstring(username);
3972 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3973 ssh2_pkt_addstring("publickey"); /* method */
3974 ssh2_pkt_addbool(FALSE); /* no signature included */
3975 ssh2_pkt_addstring_start();
3976 ssh2_pkt_addstring_data(alg, alglen);
3977 ssh2_pkt_addstring_start();
3978 ssh2_pkt_addstring_data(pkblob, pklen);
3981 crWaitUntilV(ispkt);
3982 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3983 logevent("Key refused");
3987 if (flags & FLAG_VERBOSE) {
3989 ("Authenticating with public key \"");
3990 c_write(commentp, commentlen);
3991 c_write_str("\" from agent\r\n");
3995 * Server is willing to accept the key.
3996 * Construct a SIGN_REQUEST.
3998 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3999 ssh2_pkt_addstring(username);
4000 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4001 ssh2_pkt_addstring("publickey"); /* method */
4002 ssh2_pkt_addbool(TRUE);
4003 ssh2_pkt_addstring_start();
4004 ssh2_pkt_addstring_data(alg, alglen);
4005 ssh2_pkt_addstring_start();
4006 ssh2_pkt_addstring_data(pkblob, pklen);
4008 siglen = pktout.length - 5 + 4 + 20;
4009 len = 1; /* message type */
4010 len += 4 + pklen; /* key blob */
4011 len += 4 + siglen; /* data to sign */
4012 len += 4; /* flags */
4013 agentreq = smalloc(4 + len);
4014 PUT_32BIT(agentreq, len);
4016 *q++ = SSH2_AGENTC_SIGN_REQUEST;
4017 PUT_32BIT(q, pklen);
4019 memcpy(q, pkblob, pklen);
4021 PUT_32BIT(q, siglen);
4023 /* Now the data to be signed... */
4026 memcpy(q, ssh2_session_id, 20);
4028 memcpy(q, pktout.data + 5, pktout.length - 5);
4029 q += pktout.length - 5;
4030 /* And finally the (zero) flags word. */
4032 agent_query(agentreq, len + 4, &vret, &retlen);
4036 if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4037 logevent("Sending Pageant's response");
4038 ssh2_pkt_addstring_start();
4039 ssh2_pkt_addstring_data(ret + 9,
4047 ("Pageant failed to answer challenge");
4057 if (!method && can_pubkey && *cfg.keyfile
4058 && !tried_pubkey_config) {
4059 unsigned char *pub_blob;
4060 char *algorithm, *comment;
4063 tried_pubkey_config = TRUE;
4066 * Try the public key supplied in the configuration.
4068 * First, offer the public blob to see if the server is
4069 * willing to accept it.
4071 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4074 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4075 ssh2_pkt_addstring(username);
4076 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4077 ssh2_pkt_addstring("publickey"); /* method */
4078 ssh2_pkt_addbool(FALSE); /* no signature included */
4079 ssh2_pkt_addstring(algorithm);
4080 ssh2_pkt_addstring_start();
4081 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
4083 logevent("Offered public key"); /* FIXME */
4085 crWaitUntilV(ispkt);
4086 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4088 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4089 continue; /* key refused; give up on it */
4092 logevent("Offer of public key accepted");
4094 * Actually attempt a serious authentication using
4097 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4099 "Passphrase for key \"%.100s\": ",
4105 c_write_str("Authenticating with public key \"");
4106 c_write_str(comment);
4107 c_write_str("\"\r\n");
4108 method = AUTH_PUBLICKEY_FILE;
4112 if (!method && can_keyb_inter && !tried_keyb_inter) {
4113 method = AUTH_KEYBOARD_INTERACTIVE;
4114 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4115 tried_keyb_inter = TRUE;
4117 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4118 ssh2_pkt_addstring(username);
4119 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4120 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4121 ssh2_pkt_addstring(""); /* lang */
4122 ssh2_pkt_addstring("");
4125 crWaitUntilV(ispkt);
4126 if (pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4127 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4129 logevent("Keyboard-interactive authentication refused");
4130 type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4134 kbd_inter_running = TRUE;
4137 if (kbd_inter_running) {
4138 method = AUTH_KEYBOARD_INTERACTIVE;
4139 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4140 tried_keyb_inter = TRUE;
4142 /* We've got packet with that "interactive" info
4143 dump banners, and set its prompt as ours */
4145 char *name, *inst, *lang, *prompt;
4146 int name_len, inst_len, lang_len, prompt_len;
4147 ssh2_pkt_getstring(&name, &name_len);
4148 ssh2_pkt_getstring(&inst, &inst_len);
4149 ssh2_pkt_getstring(&lang, &lang_len);
4151 c_write_untrusted(name, name_len);
4153 c_write_untrusted(inst, inst_len);
4154 num_prompts = ssh2_pkt_getuint32();
4156 ssh2_pkt_getstring(&prompt, &prompt_len);
4157 strncpy(pwprompt, prompt, sizeof(pwprompt));
4158 pwprompt[prompt_len < sizeof(pwprompt) ?
4159 prompt_len : sizeof(pwprompt)-1] = '\0';
4162 echo = ssh2_pkt_getbool();
4166 if (!method && can_passwd) {
4167 method = AUTH_PASSWORD;
4168 sprintf(pwprompt, "%.90s@%.90s's password: ", username,
4175 if (!ssh_get_line(pwprompt, password,
4176 sizeof(password), TRUE)) {
4178 * get_line failed to get a password (for
4179 * example because one was supplied on the
4180 * command line which has already failed to
4183 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4184 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4186 ("No more passwords available to try");
4187 ssh2_pkt_addstring("en"); /* language tag */
4189 connection_fatal("Unable to authenticate");
4190 ssh_state = SSH_STATE_CLOSED;
4197 c_write_untrusted(pwprompt, strlen(pwprompt));
4202 crWaitUntilV(!ispkt);
4204 switch (c = *in++) {
4225 if (pos < sizeof(password)-1)
4226 password[pos++] = c;
4230 c_write_str("\r\n");
4234 if (method == AUTH_PUBLICKEY_FILE) {
4236 * We have our passphrase. Now try the actual authentication.
4238 struct ssh2_userkey *key;
4240 key = ssh2_load_userkey(cfg.keyfile, password);
4241 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4242 if (key == SSH2_WRONG_PASSPHRASE) {
4243 c_write_str("Wrong passphrase\r\n");
4244 tried_pubkey_config = FALSE;
4246 c_write_str("Unable to load private key\r\n");
4247 tried_pubkey_config = TRUE;
4249 /* Send a spurious AUTH_NONE to return to the top. */
4250 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4251 ssh2_pkt_addstring(username);
4252 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4253 ssh2_pkt_addstring("none"); /* method */
4255 type = AUTH_TYPE_NONE;
4257 unsigned char *blob, *sigdata;
4258 int blob_len, sigdata_len;
4261 * We have loaded the private key and the server
4262 * has announced that it's willing to accept it.
4263 * Hallelujah. Generate a signature and send it.
4265 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4266 ssh2_pkt_addstring(username);
4267 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4268 ssh2_pkt_addstring("publickey"); /* method */
4269 ssh2_pkt_addbool(TRUE);
4270 ssh2_pkt_addstring(key->alg->name);
4271 blob = key->alg->public_blob(key->data, &blob_len);
4272 ssh2_pkt_addstring_start();
4273 ssh2_pkt_addstring_data(blob, blob_len);
4277 * The data to be signed is:
4281 * followed by everything so far placed in the
4284 sigdata_len = pktout.length - 5 + 4 + 20;
4285 sigdata = smalloc(sigdata_len);
4286 PUT_32BIT(sigdata, 20);
4287 memcpy(sigdata + 4, ssh2_session_id, 20);
4288 memcpy(sigdata + 24, pktout.data + 5,
4291 key->alg->sign(key->data, sigdata, sigdata_len,
4293 ssh2_pkt_addstring_start();
4294 ssh2_pkt_addstring_data(blob, blob_len);
4299 type = AUTH_TYPE_PUBLICKEY;
4301 } else if (method == AUTH_PASSWORD) {
4303 * We send the password packet lumped tightly together with
4304 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4305 * string long enough to make the total length of the two
4306 * packets constant. This should ensure that a passive
4307 * listener doing traffic analyis can't work out the length
4310 * For this to work, we need an assumption about the
4311 * maximum length of the password packet. I think 256 is
4312 * pretty conservative. Anyone using a password longer than
4313 * that probably doesn't have much to worry about from
4314 * people who find out how long their password is!
4316 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4317 ssh2_pkt_addstring(username);
4318 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4319 ssh2_pkt_addstring("password");
4320 ssh2_pkt_addbool(FALSE);
4321 ssh2_pkt_addstring(password);
4324 * We'll include a string that's an exact multiple of the
4325 * cipher block size. If the cipher is NULL for some
4326 * reason, we don't do this trick at all because we gain
4332 stringlen = (256 - deferred_len);
4333 stringlen += cscipher->blksize - 1;
4334 stringlen -= (stringlen % cscipher->blksize);
4337 * Temporarily disable actual compression,
4338 * so we can guarantee to get this string
4339 * exactly the length we want it. The
4340 * compression-disabling routine should
4341 * return an integer indicating how many
4342 * bytes we should adjust our string length
4345 stringlen -= cscomp->disable_compression();
4347 ssh2_pkt_init(SSH2_MSG_IGNORE);
4348 ssh2_pkt_addstring_start();
4349 for (i = 0; i < stringlen; i++) {
4350 char c = (char) random_byte();
4351 ssh2_pkt_addstring_data(&c, 1);
4355 ssh_pkt_defersend();
4356 logevent("Sent password");
4357 type = AUTH_TYPE_PASSWORD;
4358 } else if (method == AUTH_KEYBOARD_INTERACTIVE) {
4359 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
4360 ssh2_pkt_adduint32(num_prompts);
4361 ssh2_pkt_addstring(password);
4362 memset(password, 0, sizeof(password));
4364 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4367 ("No supported authentication methods left to try!\r\n");
4369 ("No supported authentications offered. Disconnecting");
4370 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4371 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4373 ("No supported authentication methods available");
4374 ssh2_pkt_addstring("en"); /* language tag */
4376 ssh_state = SSH_STATE_CLOSED;
4380 } while (!we_are_in);
4383 * Now we're authenticated for the connection protocol. The
4384 * connection protocol will automatically have started at this
4385 * point; there's no need to send SERVICE_REQUEST.
4389 * So now create a channel with a session in it.
4391 ssh_channels = newtree234(ssh_channelcmp);
4392 mainchan = smalloc(sizeof(struct ssh_channel));
4393 mainchan->localid = alloc_channel_id();
4394 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
4395 ssh2_pkt_addstring("session");
4396 ssh2_pkt_adduint32(mainchan->localid);
4397 mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
4398 ssh2_pkt_adduint32(mainchan->v.v2.locwindow); /* our window size */
4399 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
4401 crWaitUntilV(ispkt);
4402 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4403 bombout(("Server refused to open a session"));
4405 /* FIXME: error data comes back in FAILURE packet */
4407 if (ssh2_pkt_getuint32() != mainchan->localid) {
4408 bombout(("Server's channel confirmation cited wrong channel"));
4411 mainchan->remoteid = ssh2_pkt_getuint32();
4412 mainchan->type = CHAN_MAINSESSION;
4413 mainchan->closes = 0;
4414 mainchan->v.v2.remwindow = ssh2_pkt_getuint32();
4415 mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4416 bufchain_init(&mainchan->v.v2.outbuffer);
4417 add234(ssh_channels, mainchan);
4418 logevent("Opened channel for session");
4421 * Potentially enable X11 forwarding.
4423 if (cfg.x11_forward) {
4424 char proto[20], data[64];
4425 logevent("Requesting X11 forwarding");
4426 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
4427 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4428 ssh2_pkt_adduint32(mainchan->remoteid);
4429 ssh2_pkt_addstring("x11-req");
4430 ssh2_pkt_addbool(1); /* want reply */
4431 ssh2_pkt_addbool(0); /* many connections */
4432 ssh2_pkt_addstring(proto);
4433 ssh2_pkt_addstring(data);
4434 ssh2_pkt_adduint32(0); /* screen number */
4438 crWaitUntilV(ispkt);
4439 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4440 unsigned i = ssh2_pkt_getuint32();
4441 struct ssh_channel *c;
4442 c = find234(ssh_channels, &i, ssh_channelfind);
4444 continue; /* nonexistent channel */
4445 c->v.v2.remwindow += ssh2_pkt_getuint32();
4447 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4449 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4450 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4451 bombout(("Unexpected response to X11 forwarding request:"
4452 " packet type %d", pktin.type));
4455 logevent("X11 forwarding refused");
4457 logevent("X11 forwarding enabled");
4458 ssh_X11_fwd_enabled = TRUE;
4463 * Enable port forwardings.
4466 static char *e; /* preserve across crReturn */
4470 char sports[256], dports[256], host[256];
4473 ssh_rportfwds = newtree234(ssh_rportcmp_ssh2);
4474 /* Add port forwardings. */
4479 while (*e && *e != '\t')
4485 while (*e && *e != ':')
4495 dport = atoi(dports);
4496 sport = atoi(sports);
4497 if (sport && dport) {
4499 pfd_addforward(host, dport, sport);
4500 sprintf(buf, "Local port %d forwarding to %s:%d",
4501 sport, host, dport);
4504 struct ssh_rportfwd *pf;
4505 pf = smalloc(sizeof(*pf));
4506 strcpy(pf->dhost, host);
4509 if (add234(ssh_rportfwds, pf) != pf) {
4511 "Duplicate remote port forwarding to %s:%d",
4516 sprintf(buf, "Requesting remote port %d (forwarded to %s:%d)",
4517 sport, host, dport);
4519 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4520 ssh2_pkt_addstring("tcpip-forward");
4521 ssh2_pkt_addbool(1);/* want reply */
4522 ssh2_pkt_addstring("127.0.0.1");
4523 ssh2_pkt_adduint32(sport);
4527 crWaitUntilV(ispkt);
4528 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4529 unsigned i = ssh2_pkt_getuint32();
4530 struct ssh_channel *c;
4531 c = find234(ssh_channels, &i, ssh_channelfind);
4533 continue;/* nonexistent channel */
4534 c->v.v2.remwindow += ssh2_pkt_getuint32();
4536 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4538 if (pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
4539 if (pktin.type != SSH2_MSG_REQUEST_FAILURE) {
4540 bombout(("Unexpected response to port "
4541 "forwarding request: packet type %d",
4545 logevent("Server refused this port forwarding");
4547 logevent("Remote port forwarding enabled");
4556 * Potentially enable agent forwarding.
4558 if (cfg.agentfwd && agent_exists()) {
4559 logevent("Requesting OpenSSH-style agent forwarding");
4560 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4561 ssh2_pkt_adduint32(mainchan->remoteid);
4562 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4563 ssh2_pkt_addbool(1); /* want reply */
4567 crWaitUntilV(ispkt);
4568 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4569 unsigned i = ssh2_pkt_getuint32();
4570 struct ssh_channel *c;
4571 c = find234(ssh_channels, &i, ssh_channelfind);
4573 continue; /* nonexistent channel */
4574 c->v.v2.remwindow += ssh2_pkt_getuint32();
4576 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4578 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4579 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4580 bombout(("Unexpected response to agent forwarding request:"
4581 " packet type %d", pktin.type));
4584 logevent("Agent forwarding refused");
4586 logevent("Agent forwarding enabled");
4587 ssh_agentfwd_enabled = TRUE;
4592 * Now allocate a pty for the session.
4595 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4596 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
4597 ssh2_pkt_addstring("pty-req");
4598 ssh2_pkt_addbool(1); /* want reply */
4599 ssh2_pkt_addstring(cfg.termtype);
4600 ssh2_pkt_adduint32(cols);
4601 ssh2_pkt_adduint32(rows);
4602 ssh2_pkt_adduint32(0); /* pixel width */
4603 ssh2_pkt_adduint32(0); /* pixel height */
4604 ssh2_pkt_addstring_start();
4605 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4607 ssh_state = SSH_STATE_INTERMED;
4610 crWaitUntilV(ispkt);
4611 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4612 unsigned i = ssh2_pkt_getuint32();
4613 struct ssh_channel *c;
4614 c = find234(ssh_channels, &i, ssh_channelfind);
4616 continue; /* nonexistent channel */
4617 c->v.v2.remwindow += ssh2_pkt_getuint32();
4619 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4621 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4622 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4623 bombout(("Unexpected response to pty request:"
4624 " packet type %d", pktin.type));
4627 c_write_str("Server refused to allocate pty\r\n");
4628 ssh_editing = ssh_echoing = 1;
4630 logevent("Allocated pty");
4633 ssh_editing = ssh_echoing = 1;
4637 * Start a shell or a remote command. We may have to attempt
4638 * this twice if the config data has provided a second choice
4645 if (ssh_fallback_cmd) {
4646 subsys = cfg.ssh_subsys2;
4647 cmd = cfg.remote_cmd_ptr2;
4649 subsys = cfg.ssh_subsys;
4650 cmd = cfg.remote_cmd_ptr;
4653 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4654 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
4656 ssh2_pkt_addstring("subsystem");
4657 ssh2_pkt_addbool(1); /* want reply */
4658 ssh2_pkt_addstring(cmd);
4660 ssh2_pkt_addstring("exec");
4661 ssh2_pkt_addbool(1); /* want reply */
4662 ssh2_pkt_addstring(cmd);
4664 ssh2_pkt_addstring("shell");
4665 ssh2_pkt_addbool(1); /* want reply */
4669 crWaitUntilV(ispkt);
4670 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4671 unsigned i = ssh2_pkt_getuint32();
4672 struct ssh_channel *c;
4673 c = find234(ssh_channels, &i, ssh_channelfind);
4675 continue; /* nonexistent channel */
4676 c->v.v2.remwindow += ssh2_pkt_getuint32();
4678 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4679 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4680 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4681 bombout(("Unexpected response to shell/command request:"
4682 " packet type %d", pktin.type));
4686 * We failed to start the command. If this is the
4687 * fallback command, we really are finished; if it's
4688 * not, and if the fallback command exists, try falling
4689 * back to it before complaining.
4691 if (!ssh_fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
4692 logevent("Primary command failed; attempting fallback");
4693 ssh_fallback_cmd = TRUE;
4696 bombout(("Server refused to start a shell/command"));
4699 logevent("Started a shell/command");
4704 ssh_state = SSH_STATE_SESSION;
4708 ssh_special(TS_EOF);
4713 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
4716 static int try_send;
4720 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
4721 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
4724 unsigned i = ssh2_pkt_getuint32();
4725 struct ssh_channel *c;
4726 c = find234(ssh_channels, &i, ssh_channelfind);
4728 continue; /* nonexistent channel */
4729 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
4730 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
4731 continue; /* extended but not stderr */
4732 ssh2_pkt_getstring(&data, &length);
4735 c->v.v2.locwindow -= length;
4737 case CHAN_MAINSESSION:
4739 from_backend(pktin.type ==
4740 SSH2_MSG_CHANNEL_EXTENDED_DATA,
4744 bufsize = x11_send(c->u.x11.s, data, length);
4747 bufsize = pfd_send(c->u.pfd.s, data, length);
4750 while (length > 0) {
4751 if (c->u.a.lensofar < 4) {
4752 int l = min(4 - c->u.a.lensofar, length);
4753 memcpy(c->u.a.msglen + c->u.a.lensofar,
4757 c->u.a.lensofar += l;
4759 if (c->u.a.lensofar == 4) {
4761 4 + GET_32BIT(c->u.a.msglen);
4762 c->u.a.message = smalloc(c->u.a.totallen);
4763 memcpy(c->u.a.message, c->u.a.msglen, 4);
4765 if (c->u.a.lensofar >= 4 && length > 0) {
4767 min(c->u.a.totallen - c->u.a.lensofar,
4769 memcpy(c->u.a.message + c->u.a.lensofar,
4773 c->u.a.lensofar += l;
4775 if (c->u.a.lensofar == c->u.a.totallen) {
4776 void *reply, *sentreply;
4778 agent_query(c->u.a.message,
4779 c->u.a.totallen, &reply,
4784 /* Fake SSH_AGENT_FAILURE. */
4785 sentreply = "\0\0\0\1\5";
4788 ssh2_add_channel_data(c, sentreply,
4793 sfree(c->u.a.message);
4794 c->u.a.lensofar = 0;
4801 * If we are not buffering too much data,
4802 * enlarge the window again at the remote side.
4804 if (bufsize < OUR_V2_WINSIZE)
4805 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
4807 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
4808 ssh_state = SSH_STATE_CLOSED;
4809 logevent("Received disconnect message");
4811 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
4812 unsigned i = ssh2_pkt_getuint32();
4813 struct ssh_channel *c;
4815 c = find234(ssh_channels, &i, ssh_channelfind);
4817 continue; /* nonexistent channel */
4819 if (c->type == CHAN_X11) {
4821 * Remote EOF on an X11 channel means we should
4822 * wrap up and close the channel ourselves.
4824 x11_close(c->u.x11.s);
4826 } else if (c->type == CHAN_AGENT) {
4828 } else if (c->type == CHAN_SOCKDATA) {
4829 pfd_close(c->u.pfd.s);
4832 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
4833 unsigned i = ssh2_pkt_getuint32();
4834 struct ssh_channel *c;
4836 c = find234(ssh_channels, &i, ssh_channelfind);
4838 continue; /* nonexistent channel */
4839 /* Do pre-close processing on the channel. */
4841 case CHAN_MAINSESSION:
4842 break; /* nothing to see here, move along */
4844 if (c->u.x11.s != NULL)
4845 x11_close(c->u.x11.s);
4852 if (c->u.pfd.s != NULL)
4853 pfd_close(c->u.pfd.s);
4857 if (c->closes == 0) {
4858 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4859 ssh2_pkt_adduint32(c->remoteid);
4862 del234(ssh_channels, c);
4863 bufchain_clear(&c->v.v2.outbuffer);
4867 * See if that was the last channel left open.
4869 if (count234(ssh_channels) == 0) {
4870 logevent("All channels closed. Disconnecting");
4871 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4872 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4873 ssh2_pkt_addstring("All open channels closed");
4874 ssh2_pkt_addstring("en"); /* language tag */
4876 ssh_state = SSH_STATE_CLOSED;
4879 continue; /* remote sends close; ignore (FIXME) */
4880 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4881 unsigned i = ssh2_pkt_getuint32();
4882 struct ssh_channel *c;
4883 c = find234(ssh_channels, &i, ssh_channelfind);
4885 continue; /* nonexistent channel */
4886 c->v.v2.remwindow += ssh2_pkt_getuint32();
4888 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4889 unsigned i = ssh2_pkt_getuint32();
4890 struct ssh_channel *c;
4891 c = find234(ssh_channels, &i, ssh_channelfind);
4893 continue; /* nonexistent channel */
4894 if (c->type != CHAN_SOCKDATA_DORMANT)
4895 continue; /* dunno why they're confirming this */
4896 c->remoteid = ssh2_pkt_getuint32();
4897 c->type = CHAN_SOCKDATA;
4898 c->v.v2.remwindow = ssh2_pkt_getuint32();
4899 c->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4900 bufchain_init(&c->v.v2.outbuffer);
4902 pfd_confirm(c->u.pfd.s);
4905 * We have a pending close on this channel,
4906 * which we decided on before the server acked
4907 * the channel open. So now we know the
4908 * remoteid, we can close it again.
4910 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4911 ssh2_pkt_adduint32(c->remoteid);
4914 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
4915 unsigned i = ssh2_pkt_getuint32();
4916 struct ssh_channel *c;
4917 c = find234(ssh_channels, &i, ssh_channelfind);
4919 continue; /* nonexistent channel */
4920 if (c->type != CHAN_SOCKDATA_DORMANT)
4921 continue; /* dunno why they're failing this */
4923 logevent("Forwarded connection refused by server");
4925 pfd_close(c->u.pfd.s);
4927 del234(ssh_channels, c);
4929 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
4932 int typelen, want_reply;
4933 struct ssh_channel *c;
4935 localid = ssh2_pkt_getuint32();
4936 ssh2_pkt_getstring(&type, &typelen);
4937 want_reply = ssh2_pkt_getbool();
4940 * First, check that the channel exists. Otherwise,
4941 * we can instantly disconnect with a rude message.
4943 c = find234(ssh_channels, &localid, ssh_channelfind);
4946 sprintf(buf, "Received channel request for nonexistent"
4947 " channel %d", localid);
4949 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4950 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4951 ssh2_pkt_addstring(buf);
4952 ssh2_pkt_addstring("en"); /* language tag */
4954 connection_fatal(buf);
4955 ssh_state = SSH_STATE_CLOSED;
4960 * We don't recognise any form of channel request,
4961 * so we now either ignore the request or respond
4962 * with CHANNEL_FAILURE, depending on want_reply.
4965 ssh2_pkt_init(SSH2_MSG_CHANNEL_FAILURE);
4966 ssh2_pkt_adduint32(c->remoteid);
4969 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
4973 struct ssh_channel *c;
4974 unsigned remid, winsize, pktsize;
4975 ssh2_pkt_getstring(&type, &typelen);
4976 c = smalloc(sizeof(struct ssh_channel));
4978 remid = ssh2_pkt_getuint32();
4979 winsize = ssh2_pkt_getuint32();
4980 pktsize = ssh2_pkt_getuint32();
4982 if (typelen == 3 && !memcmp(type, "x11", 3)) {
4983 if (!ssh_X11_fwd_enabled)
4984 error = "X11 forwarding is not enabled";
4985 else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
4987 error = "Unable to open an X11 connection";
4991 } else if (typelen == 15 &&
4992 !memcmp(type, "forwarded-tcpip", 15)) {
4993 struct ssh_rportfwd pf, *realpf;
4996 ssh2_pkt_getstring(&dummy, &dummylen);/* skip address */
4997 pf.sport = ssh2_pkt_getuint32();
4998 realpf = find234(ssh_rportfwds, &pf, NULL);
4999 if (realpf == NULL) {
5000 error = "Remote port is not recognised";
5002 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5005 sprintf(buf, "Received remote port open request for %s:%d",
5006 realpf->dhost, realpf->dport);
5009 sprintf(buf, "Port open failed: %s", e);
5011 error = "Port open failed";
5013 logevent("Forwarded port opened successfully");
5014 c->type = CHAN_SOCKDATA;
5017 } else if (typelen == 22 &&
5018 !memcmp(type, "auth-agent@openssh.com", 3)) {
5019 if (!ssh_agentfwd_enabled)
5020 error = "Agent forwarding is not enabled";
5022 c->type = CHAN_AGENT; /* identify channel type */
5023 c->u.a.lensofar = 0;
5026 error = "Unsupported channel type requested";
5029 c->remoteid = remid;
5031 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
5032 ssh2_pkt_adduint32(c->remoteid);
5033 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
5034 ssh2_pkt_addstring(error);
5035 ssh2_pkt_addstring("en"); /* language tag */
5039 c->localid = alloc_channel_id();
5041 c->v.v2.locwindow = OUR_V2_WINSIZE;
5042 c->v.v2.remwindow = winsize;
5043 c->v.v2.remmaxpkt = pktsize;
5044 bufchain_init(&c->v.v2.outbuffer);
5045 add234(ssh_channels, c);
5046 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5047 ssh2_pkt_adduint32(c->remoteid);
5048 ssh2_pkt_adduint32(c->localid);
5049 ssh2_pkt_adduint32(c->v.v2.locwindow);
5050 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5054 bombout(("Strange packet received: type %d", pktin.type));
5059 * We have spare data. Add it to the channel buffer.
5061 ssh2_add_channel_data(mainchan, in, inlen);
5066 struct ssh_channel *c;
5068 * Try to send data on all channels if we can.
5070 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
5071 int bufsize = ssh2_try_send(c);
5074 case CHAN_MAINSESSION:
5075 /* stdin need not receive an unthrottle
5076 * notification since it will be polled */
5079 x11_unthrottle(c->u.x11.s);
5082 /* agent sockets are request/response and need no
5083 * buffer management */
5086 pfd_unthrottle(c->u.pfd.s);
5098 * Handle the top-level SSH2 protocol.
5100 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
5102 if (do_ssh2_transport(in, inlen, ispkt) == 0)
5104 do_ssh2_authconn(in, inlen, ispkt);
5108 * Called to set up the connection.
5110 * Returns an error message, or NULL on success.
5112 static char *ssh_init(char *host, int port, char **realhost)
5117 if (crypto_startup() == 0)
5118 return "Microsoft high encryption pack not installed!";
5124 ssh1_throttle_count = 0;
5125 ssh_overall_bufsize = 0;
5126 ssh_fallback_cmd = 0;
5128 p = connect_to_host(host, port, realhost);
5136 * Called to send data down the Telnet connection.
5138 static int ssh_send(char *buf, int len)
5140 if (s == NULL || ssh_protocol == NULL)
5143 ssh_protocol(buf, len, 0);
5145 return ssh_sendbuffer();
5149 * Called to query the current amount of buffered stdin data.
5151 static int ssh_sendbuffer(void)
5155 if (s == NULL || ssh_protocol == NULL)
5159 * If the SSH socket itself has backed up, add the total backup
5160 * size on that to any individual buffer on the stdin channel.
5163 if (ssh_throttled_all)
5164 override_value = ssh_overall_bufsize;
5166 if (ssh_version == 1) {
5167 return override_value;
5168 } else if (ssh_version == 2) {
5169 if (!mainchan || mainchan->closes > 0)
5170 return override_value;
5172 return override_value + bufchain_size(&mainchan->v.v2.outbuffer);
5179 * Called to set the size of the window from SSH's POV.
5181 static void ssh_size(void)
5183 switch (ssh_state) {
5184 case SSH_STATE_BEFORE_SIZE:
5185 case SSH_STATE_PREPACKET:
5186 case SSH_STATE_CLOSED:
5187 break; /* do nothing */
5188 case SSH_STATE_INTERMED:
5189 size_needed = TRUE; /* buffer for later */
5191 case SSH_STATE_SESSION:
5193 if (ssh_version == 1) {
5194 send_packet(SSH1_CMSG_WINDOW_SIZE,
5195 PKT_INT, rows, PKT_INT, cols,
5196 PKT_INT, 0, PKT_INT, 0, PKT_END);
5198 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5199 ssh2_pkt_adduint32(mainchan->remoteid);
5200 ssh2_pkt_addstring("window-change");
5201 ssh2_pkt_addbool(0);
5202 ssh2_pkt_adduint32(cols);
5203 ssh2_pkt_adduint32(rows);
5204 ssh2_pkt_adduint32(0);
5205 ssh2_pkt_adduint32(0);
5214 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5215 * can send an EOF and collect resulting output (e.g. `plink
5218 static void ssh_special(Telnet_Special code)
5220 if (code == TS_EOF) {
5221 if (ssh_state != SSH_STATE_SESSION) {
5223 * Buffer the EOF in case we are pre-SESSION, so we can
5224 * send it as soon as we reach SESSION.
5230 if (ssh_version == 1) {
5231 send_packet(SSH1_CMSG_EOF, PKT_END);
5233 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
5234 ssh2_pkt_adduint32(mainchan->remoteid);
5237 logevent("Sent EOF message");
5238 } else if (code == TS_PING) {
5239 if (ssh_state == SSH_STATE_CLOSED
5240 || ssh_state == SSH_STATE_PREPACKET) return;
5241 if (ssh_version == 1) {
5242 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
5244 ssh2_pkt_init(SSH2_MSG_IGNORE);
5245 ssh2_pkt_addstring_start();
5253 void *new_sock_channel(Socket s)
5255 struct ssh_channel *c;
5256 c = smalloc(sizeof(struct ssh_channel));
5259 c->remoteid = -1; /* to be set when open confirmed */
5260 c->localid = alloc_channel_id();
5262 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
5264 add234(ssh_channels, c);
5270 * This is called when stdout/stderr (the entity to which
5271 * from_backend sends data) manages to clear some backlog.
5273 void ssh_unthrottle(int bufsize)
5275 if (ssh_version == 1) {
5276 if (ssh1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
5277 ssh1_stdout_throttling = 0;
5281 if (mainchan && mainchan->closes == 0)
5282 ssh2_set_window(mainchan, OUR_V2_WINSIZE - bufsize);
5286 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
5288 struct ssh_channel *c = (struct ssh_channel *)channel;
5291 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
5294 if (ssh_version == 1) {
5295 send_packet(SSH1_MSG_PORT_OPEN,
5296 PKT_INT, c->localid,
5299 //PKT_STR, <org:orgport>,
5302 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
5303 ssh2_pkt_addstring("direct-tcpip");
5304 ssh2_pkt_adduint32(c->localid);
5305 c->v.v2.locwindow = OUR_V2_WINSIZE;
5306 ssh2_pkt_adduint32(c->v.v2.locwindow);/* our window size */
5307 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5308 ssh2_pkt_addstring(hostname);
5309 ssh2_pkt_adduint32(port);
5311 * We make up values for the originator data; partly it's
5312 * too much hassle to keep track, and partly I'm not
5313 * convinced the server should be told details like that
5314 * about my local network configuration.
5316 ssh2_pkt_addstring("client-side-connection");
5317 ssh2_pkt_adduint32(0);
5323 static Socket ssh_socket(void)
5328 static int ssh_sendok(void)
5333 static int ssh_ldisc(int option)
5335 if (option == LD_ECHO)
5337 if (option == LD_EDIT)
5342 Backend ssh_backend = {