18 /* uncomment this for packet level debugging */
19 /* #define DUMP_PACKETS */
21 #define logevent(s) { logevent(s); \
22 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
23 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
25 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
26 (s ? sk_close(s), s = NULL : 0), \
27 connection_fatal msg )
29 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
30 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
31 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
32 #define SSH1_CMSG_USER 4 /* 0x4 */
33 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
34 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
35 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
36 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
37 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
38 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
39 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
40 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
41 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
42 #define SSH1_SMSG_FAILURE 15 /* 0xf */
43 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
44 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
45 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
46 #define SSH1_CMSG_EOF 19 /* 0x13 */
47 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
48 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
49 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
50 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
51 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
52 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
53 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
54 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
55 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
56 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
57 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
58 #define SSH1_MSG_IGNORE 32 /* 0x20 */
59 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
60 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
61 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
62 #define SSH1_MSG_DEBUG 36 /* 0x24 */
63 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
64 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
65 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
66 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
67 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
68 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
69 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
71 #define SSH1_AUTH_TIS 5 /* 0x5 */
72 #define SSH1_AUTH_CCARD 16 /* 0x10 */
74 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
75 /* Mask for protoflags we will echo back to server if seen */
76 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
78 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
79 #define SSH2_MSG_IGNORE 2 /* 0x2 */
80 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
81 #define SSH2_MSG_DEBUG 4 /* 0x4 */
82 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
83 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
84 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
85 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
86 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
87 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
88 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
89 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
90 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
91 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
92 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
93 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
94 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
95 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
96 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
97 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
98 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
99 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
100 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
101 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
102 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
103 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
104 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
105 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
106 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
107 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
108 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
109 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
110 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
111 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
112 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
113 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
115 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
116 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
117 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
118 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
119 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
120 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
121 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
122 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
123 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
124 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
125 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
126 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
127 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
128 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
129 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
131 static const char *const ssh2_disconnect_reasons[] = {
133 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
134 "SSH_DISCONNECT_PROTOCOL_ERROR",
135 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
136 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
137 "SSH_DISCONNECT_MAC_ERROR",
138 "SSH_DISCONNECT_COMPRESSION_ERROR",
139 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
140 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
141 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
142 "SSH_DISCONNECT_CONNECTION_LOST",
143 "SSH_DISCONNECT_BY_APPLICATION",
144 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
145 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
146 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
147 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
150 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
151 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
152 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
153 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
155 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
158 * Various remote-bug flags.
160 #define BUG_CHOKES_ON_SSH1_IGNORE 1
161 #define BUG_SSH2_HMAC 2
163 #define GET_32BIT(cp) \
164 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
165 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
166 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
167 ((unsigned long)(unsigned char)(cp)[3]))
169 #define PUT_32BIT(cp, value) { \
170 (cp)[0] = (unsigned char)((value) >> 24); \
171 (cp)[1] = (unsigned char)((value) >> 16); \
172 (cp)[2] = (unsigned char)((value) >> 8); \
173 (cp)[3] = (unsigned char)(value); }
175 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
177 /* Coroutine mechanics for the sillier bits of the code */
178 #define crBegin1 static int crLine = 0;
179 #define crBegin2 switch(crLine) { case 0:;
180 #define crBegin crBegin1; crBegin2;
181 #define crFinish(z) } crLine = 0; return (z)
182 #define crFinishV } crLine = 0; return
183 #define crReturn(z) \
185 crLine=__LINE__; return (z); case __LINE__:;\
189 crLine=__LINE__; return; case __LINE__:;\
191 #define crStop(z) do{ crLine = 0; return (z); }while(0)
192 #define crStopV do{ crLine = 0; return; }while(0)
193 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
194 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
196 extern char *x11_init(Socket *, char *, void *);
197 extern void x11_close(Socket);
198 extern int x11_send(Socket, char *, int);
199 extern void x11_invent_auth(char *, int, char *, int);
200 extern void x11_unthrottle(Socket s);
201 extern void x11_override_throttle(Socket s, int enable);
203 extern char *pfd_newconnect(Socket * s, char *hostname, int port, void *c);
204 extern char *pfd_addforward(char *desthost, int destport, int port);
205 extern void pfd_close(Socket s);
206 extern int pfd_send(Socket s, char *data, int len);
207 extern void pfd_confirm(Socket s);
208 extern void pfd_unthrottle(Socket s);
209 extern void pfd_override_throttle(Socket s, int enable);
212 * Buffer management constants. There are several of these for
213 * various different purposes:
215 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
216 * on a local data stream before we throttle the whole SSH
217 * connection (in SSH1 only). Throttling the whole connection is
218 * pretty drastic so we set this high in the hope it won't
221 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
222 * on the SSH connection itself before we defensively throttle
223 * _all_ local data streams. This is pretty drastic too (though
224 * thankfully unlikely in SSH2 since the window mechanism should
225 * ensure that the server never has any need to throttle its end
226 * of the connection), so we set this high as well.
228 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
232 #define SSH1_BUFFER_LIMIT 32768
233 #define SSH_MAX_BACKLOG 32768
234 #define OUR_V2_WINSIZE 16384
237 * Ciphers for SSH2. We miss out single-DES because it isn't
238 * supported; also 3DES and Blowfish are both done differently from
239 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
240 * endianness and different-sized keys.)
242 const static struct ssh2_ciphers *ciphers[] = {
248 const static struct ssh_kex *kex_algs[] = {
249 &ssh_diffiehellman_gex,
253 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
255 static void nullmac_key(unsigned char *key)
258 static void nullmac_generate(unsigned char *blk, int len,
262 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq)
266 const static struct ssh_mac ssh_mac_none = {
267 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
269 const static struct ssh_mac *macs[] = {
270 &ssh_sha1, &ssh_md5, &ssh_mac_none
272 const static struct ssh_mac *buggymacs[] = {
273 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
276 static void ssh_comp_none_init(void)
279 static int ssh_comp_none_block(unsigned char *block, int len,
280 unsigned char **outblock, int *outlen)
284 static int ssh_comp_none_disable(void)
288 const static struct ssh_compress ssh_comp_none = {
290 ssh_comp_none_init, ssh_comp_none_block,
291 ssh_comp_none_init, ssh_comp_none_block,
292 ssh_comp_none_disable
294 extern const struct ssh_compress ssh_zlib;
295 const static struct ssh_compress *compressions[] = {
296 &ssh_zlib, &ssh_comp_none
299 enum { /* channel types */
304 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
308 * 2-3-4 tree storing channels.
311 unsigned remoteid, localid;
315 struct ssh1_data_channel {
318 struct ssh2_data_channel {
320 unsigned remwindow, remmaxpkt;
325 struct ssh_agent_channel {
326 unsigned char *message;
327 unsigned char msglen[4];
328 int lensofar, totallen;
330 struct ssh_x11_channel {
333 struct ssh_pfd_channel {
340 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
341 * 2 use this structure in different ways, reflecting SSH 2's
342 * altogether saner approach to port forwarding.
344 * In SSH 1, you arrange a remote forwarding by sending the server
345 * the remote port number, and the local destination host:port.
346 * When a connection comes in, the server sends you back that
347 * host:port pair, and you connect to it. This is a ready-made
348 * security hole if you're not on the ball: a malicious server
349 * could send you back _any_ host:port pair, so if you trustingly
350 * connect to the address it gives you then you've just opened the
351 * entire inside of your corporate network just by connecting
352 * through it to a dodgy SSH server. Hence, we must store a list of
353 * host:port pairs we _are_ trying to forward to, and reject a
354 * connection request from the server if it's not in the list.
356 * In SSH 2, each side of the connection minds its own business and
357 * doesn't send unnecessary information to the other. You arrange a
358 * remote forwarding by sending the server just the remote port
359 * number. When a connection comes in, the server tells you which
360 * of its ports was connected to; and _you_ have to remember what
361 * local host:port pair went with that port number.
363 * Hence: in SSH 1 this structure stores host:port pairs we intend
364 * to allow connections to, and is indexed by those host:port
365 * pairs. In SSH 2 it stores a mapping from source port to
366 * destination host:port pair, and is indexed by source port.
368 struct ssh_rportfwd {
369 unsigned sport, dport;
382 static SHA_State exhash, exhashbase;
384 static Socket s = NULL;
386 static unsigned char session_key[32];
387 static int ssh1_compressing;
388 static int ssh1_remote_protoflags;
389 static int ssh1_local_protoflags;
390 static int ssh_agentfwd_enabled;
391 static int ssh_X11_fwd_enabled;
392 static int ssh_remote_bugs;
393 static const struct ssh_cipher *cipher = NULL;
394 static const struct ssh2_cipher *cscipher = NULL;
395 static const struct ssh2_cipher *sccipher = NULL;
396 static const struct ssh_mac *csmac = NULL;
397 static const struct ssh_mac *scmac = NULL;
398 static const struct ssh_compress *cscomp = NULL;
399 static const struct ssh_compress *sccomp = NULL;
400 static const struct ssh_kex *kex = NULL;
401 static const struct ssh_signkey *hostkey = NULL;
402 static unsigned char ssh2_session_id[20];
403 int (*ssh_get_line) (const char *prompt, char *str, int maxlen,
406 static char *savedhost;
407 static int savedport;
408 static int ssh_send_ok;
409 static int ssh_echoing, ssh_editing;
411 static tree234 *ssh_channels; /* indexed by local id */
412 static struct ssh_channel *mainchan; /* primary session channel */
414 static tree234 *ssh_rportfwds;
418 SSH_STATE_BEFORE_SIZE,
422 } ssh_state = SSH_STATE_PREPACKET;
424 static int size_needed = FALSE, eof_needed = FALSE;
426 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
427 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
428 static unsigned char *deferred_send_data = NULL;
429 static int deferred_len = 0, deferred_size = 0;
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)--;
611 if (st->len == 0x52656d6f) { /* "Remo"te server has closed ... */
612 st->len = 0x300; /* big enough to carry to end */
616 st->pad = 8 - (st->len % 8);
617 st->biglen = st->len + st->pad;
618 pktin.length = st->len - 5;
620 if (pktin.maxlen < st->biglen) {
621 pktin.maxlen = st->biglen;
622 pktin.data = (pktin.data == NULL ? smalloc(st->biglen + APIEXTRA) :
623 srealloc(pktin.data, st->biglen + APIEXTRA));
625 fatalbox("Out of memory");
628 st->to_read = st->biglen;
630 while (st->to_read > 0) {
631 st->chunk = st->to_read;
632 while ((*datalen) == 0)
633 crReturn(st->to_read);
634 if (st->chunk > (*datalen))
635 st->chunk = (*datalen);
636 memcpy(st->p, *data, st->chunk);
638 *datalen -= st->chunk;
640 st->to_read -= st->chunk;
644 cipher->decrypt(pktin.data, st->biglen);
646 debug(("Got packet len=%d pad=%d\n", st->len, st->pad));
647 dmemdump(pktin.data, st->biglen);
650 st->realcrc = crc32(pktin.data, st->biglen - 4);
651 st->gotcrc = GET_32BIT(pktin.data + st->biglen - 4);
652 if (st->gotcrc != st->realcrc) {
653 bombout(("Incorrect CRC received on packet"));
657 pktin.body = pktin.data + st->pad + 1;
659 if (ssh1_compressing) {
660 unsigned char *decompblk;
663 debug(("Packet payload pre-decompression:\n"));
664 dmemdump(pktin.body - 1, pktin.length + 1);
666 zlib_decompress_block(pktin.body - 1, pktin.length + 1,
667 &decompblk, &decomplen);
669 if (pktin.maxlen < st->pad + decomplen) {
670 pktin.maxlen = st->pad + decomplen;
671 pktin.data = srealloc(pktin.data, pktin.maxlen + APIEXTRA);
672 pktin.body = pktin.data + st->pad + 1;
674 fatalbox("Out of memory");
677 memcpy(pktin.body - 1, decompblk, decomplen);
679 pktin.length = decomplen - 1;
681 debug(("Packet payload post-decompression:\n"));
682 dmemdump(pktin.body - 1, pktin.length + 1);
686 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
687 pktin.type == SSH1_SMSG_STDERR_DATA ||
688 pktin.type == SSH1_MSG_DEBUG ||
689 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
690 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
691 long strlen = GET_32BIT(pktin.body);
692 if (strlen + 4 != pktin.length) {
693 bombout(("Received data packet with bogus string length"));
698 pktin.type = pktin.body[-1];
700 if (pktin.type == SSH1_MSG_DEBUG) {
701 /* log debug message */
703 int strlen = GET_32BIT(pktin.body);
704 strcpy(buf, "Remote: ");
707 memcpy(buf + 8, pktin.body + 4, strlen);
708 buf[8 + strlen] = '\0';
711 } else if (pktin.type == SSH1_MSG_IGNORE) {
716 if (pktin.type == SSH1_MSG_DISCONNECT) {
717 /* log reason code in disconnect message */
719 unsigned msglen = GET_32BIT(pktin.body);
721 strcpy(buf, "Remote sent disconnect: ");
722 nowlen = strlen(buf);
723 if (msglen > sizeof(buf) - nowlen - 1)
724 msglen = sizeof(buf) - nowlen - 1;
725 memcpy(buf + nowlen, pktin.body + 4, msglen);
726 buf[nowlen + msglen] = '\0';
728 bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
735 static int ssh2_rdpkt(unsigned char **data, int *datalen)
737 struct rdpkt2_state_tag *st = &rdpkt2_state;
745 st->cipherblk = sccipher->blksize;
748 if (st->cipherblk < 8)
751 if (pktin.maxlen < st->cipherblk) {
752 pktin.maxlen = st->cipherblk;
755 NULL ? smalloc(st->cipherblk +
756 APIEXTRA) : srealloc(pktin.data,
760 fatalbox("Out of memory");
764 * Acquire and decrypt the first block of the packet. This will
765 * contain the length and padding details.
767 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
768 while ((*datalen) == 0)
769 crReturn(st->cipherblk - st->i);
770 pktin.data[st->i] = *(*data)++;
774 if (!memcmp(pktin.data, "Remo", 4)) { /* "Remo"te server has closed ... */
779 sccipher->decrypt(pktin.data, st->cipherblk);
782 * Now get the length and padding figures.
784 st->len = GET_32BIT(pktin.data);
785 st->pad = pktin.data[4];
788 * This enables us to deduce the payload length.
790 st->payload = st->len - st->pad - 1;
792 pktin.length = st->payload + 5;
795 * So now we can work out the total packet length.
797 st->packetlen = st->len + 4;
798 st->maclen = scmac ? scmac->len : 0;
801 * Adjust memory allocation if packet is too big.
803 if (pktin.maxlen < st->packetlen + st->maclen) {
804 pktin.maxlen = st->packetlen + st->maclen;
807 NULL ? smalloc(pktin.maxlen + APIEXTRA) : srealloc(pktin.data,
812 fatalbox("Out of memory");
816 * Read and decrypt the remainder of the packet.
818 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
820 while ((*datalen) == 0)
821 crReturn(st->packetlen + st->maclen - st->i);
822 pktin.data[st->i] = *(*data)++;
825 /* Decrypt everything _except_ the MAC. */
827 sccipher->decrypt(pktin.data + st->cipherblk,
828 st->packetlen - st->cipherblk);
831 debug(("Got packet len=%d pad=%d\n", st->len, st->pad));
832 dmemdump(pktin.data, st->packetlen);
839 && !scmac->verify(pktin.data, st->len + 4,
840 st->incoming_sequence)) {
841 bombout(("Incorrect MAC received on packet"));
844 st->incoming_sequence++; /* whether or not we MACed */
847 * Decompress packet payload.
850 unsigned char *newpayload;
852 if (sccomp && sccomp->decompress(pktin.data + 5, pktin.length - 5,
853 &newpayload, &newlen)) {
854 if (pktin.maxlen < newlen + 5) {
855 pktin.maxlen = newlen + 5;
858 NULL ? smalloc(pktin.maxlen +
859 APIEXTRA) : srealloc(pktin.data,
863 fatalbox("Out of memory");
865 pktin.length = 5 + newlen;
866 memcpy(pktin.data + 5, newpayload, newlen);
868 debug(("Post-decompression payload:\n"));
869 dmemdump(pktin.data + 5, newlen);
877 pktin.type = pktin.data[5];
879 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
880 goto next_packet; /* FIXME: print DEBUG message */
882 if (pktin.type == SSH2_MSG_DISCONNECT) {
883 /* log reason code in disconnect message */
885 int reason = GET_32BIT(pktin.data + 6);
886 unsigned msglen = GET_32BIT(pktin.data + 10);
888 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
889 sprintf(buf, "Received disconnect message (%s)",
890 ssh2_disconnect_reasons[reason]);
892 sprintf(buf, "Received disconnect message (unknown type %d)",
896 strcpy(buf, "Disconnection message text: ");
897 nowlen = strlen(buf);
898 if (msglen > sizeof(buf) - nowlen - 1)
899 msglen = sizeof(buf) - nowlen - 1;
900 memcpy(buf + nowlen, pktin.data + 14, msglen);
901 buf[nowlen + msglen] = '\0';
903 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
905 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
906 ssh2_disconnect_reasons[reason] : "unknown",
914 static void ssh1_pktout_size(int len)
918 len += 5; /* type and CRC */
922 pktout.length = len - 5;
923 if (pktout.maxlen < biglen) {
924 pktout.maxlen = biglen;
926 /* Allocate enough buffer space for extra block
927 * for MS CryptEncrypt() */
928 pktout.data = (pktout.data == NULL ? smalloc(biglen + 12) :
929 srealloc(pktout.data, biglen + 12));
931 pktout.data = (pktout.data == NULL ? smalloc(biglen + 4) :
932 srealloc(pktout.data, biglen + 4));
935 fatalbox("Out of memory");
937 pktout.body = pktout.data + 4 + pad + 1;
940 static void s_wrpkt_start(int type, int len)
942 ssh1_pktout_size(len);
946 static int s_wrpkt_prepare(void)
948 int pad, len, biglen, i;
951 pktout.body[-1] = pktout.type;
954 debug(("Packet payload pre-compression:\n"));
955 dmemdump(pktout.body - 1, pktout.length + 1);
958 if (ssh1_compressing) {
959 unsigned char *compblk;
961 zlib_compress_block(pktout.body - 1, pktout.length + 1,
963 ssh1_pktout_size(complen - 1);
964 memcpy(pktout.body - 1, compblk, complen);
967 debug(("Packet payload post-compression:\n"));
968 dmemdump(pktout.body - 1, pktout.length + 1);
972 len = pktout.length + 5; /* type and CRC */
976 for (i = 0; i < pad; i++)
977 pktout.data[i + 4] = random_byte();
978 crc = crc32(pktout.data + 4, biglen - 4);
979 PUT_32BIT(pktout.data + biglen, crc);
980 PUT_32BIT(pktout.data, len);
983 debug(("Sending packet len=%d\n", biglen + 4));
984 dmemdump(pktout.data, biglen + 4);
987 cipher->encrypt(pktout.data + 4, biglen);
992 static void s_wrpkt(void)
995 len = s_wrpkt_prepare();
996 backlog = sk_write(s, pktout.data, len);
997 if (backlog > SSH_MAX_BACKLOG)
998 ssh_throttle_all(1, backlog);
1001 static void s_wrpkt_defer(void)
1004 len = s_wrpkt_prepare();
1005 if (deferred_len + len > deferred_size) {
1006 deferred_size = deferred_len + len + 128;
1007 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1009 memcpy(deferred_send_data + deferred_len, pktout.data, len);
1010 deferred_len += len;
1014 * Construct a packet with the specified contents.
1016 static void construct_packet(int pkttype, va_list ap1, va_list ap2)
1018 unsigned char *p, *argp, argchar;
1019 unsigned long argint;
1020 int pktlen, argtype, arglen;
1024 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1027 (void) va_arg(ap1, int);
1031 (void) va_arg(ap1, char);
1035 (void) va_arg(ap1, unsigned char *);
1036 arglen = va_arg(ap1, int);
1040 argp = va_arg(ap1, unsigned char *);
1041 arglen = strlen(argp);
1042 pktlen += 4 + arglen;
1045 bn = va_arg(ap1, Bignum);
1046 pktlen += ssh1_bignum_length(bn);
1053 s_wrpkt_start(pkttype, pktlen);
1056 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1059 argint = va_arg(ap2, int);
1060 PUT_32BIT(p, argint);
1064 argchar = va_arg(ap2, unsigned char);
1069 argp = va_arg(ap2, unsigned char *);
1070 arglen = va_arg(ap2, int);
1071 memcpy(p, argp, arglen);
1075 argp = va_arg(ap2, unsigned char *);
1076 arglen = strlen(argp);
1077 PUT_32BIT(p, arglen);
1078 memcpy(p + 4, argp, arglen);
1082 bn = va_arg(ap2, Bignum);
1083 p += ssh1_write_bignum(p, bn);
1089 static void send_packet(int pkttype, ...)
1092 va_start(ap1, pkttype);
1093 va_start(ap2, pkttype);
1094 construct_packet(pkttype, ap1, ap2);
1098 static void defer_packet(int pkttype, ...)
1101 va_start(ap1, pkttype);
1102 va_start(ap2, pkttype);
1103 construct_packet(pkttype, ap1, ap2);
1107 static int ssh_versioncmp(char *a, char *b)
1110 unsigned long av, bv;
1112 av = strtoul(a, &ae, 10);
1113 bv = strtoul(b, &be, 10);
1115 return (av < bv ? -1 : +1);
1120 av = strtoul(ae, &ae, 10);
1121 bv = strtoul(be, &be, 10);
1123 return (av < bv ? -1 : +1);
1129 * Utility routines for putting an SSH-protocol `string' and
1130 * `uint32' into a SHA state.
1133 static void sha_string(SHA_State * s, void *str, int len)
1135 unsigned char lenblk[4];
1136 PUT_32BIT(lenblk, len);
1137 SHA_Bytes(s, lenblk, 4);
1138 SHA_Bytes(s, str, len);
1141 static void sha_uint32(SHA_State * s, unsigned i)
1143 unsigned char intblk[4];
1144 PUT_32BIT(intblk, i);
1145 SHA_Bytes(s, intblk, 4);
1149 * SSH2 packet construction functions.
1151 static void ssh2_pkt_ensure(int length)
1153 if (pktout.maxlen < length) {
1154 pktout.maxlen = length + 256;
1157 NULL ? smalloc(pktout.maxlen +
1158 APIEXTRA) : srealloc(pktout.data,
1162 fatalbox("Out of memory");
1165 static void ssh2_pkt_adddata(void *data, int len)
1167 pktout.length += len;
1168 ssh2_pkt_ensure(pktout.length);
1169 memcpy(pktout.data + pktout.length - len, data, len);
1171 static void ssh2_pkt_addbyte(unsigned char byte)
1173 ssh2_pkt_adddata(&byte, 1);
1175 static void ssh2_pkt_init(int pkt_type)
1178 ssh2_pkt_addbyte((unsigned char) pkt_type);
1180 static void ssh2_pkt_addbool(unsigned char value)
1182 ssh2_pkt_adddata(&value, 1);
1184 static void ssh2_pkt_adduint32(unsigned long value)
1187 PUT_32BIT(x, value);
1188 ssh2_pkt_adddata(x, 4);
1190 static void ssh2_pkt_addstring_start(void)
1192 ssh2_pkt_adduint32(0);
1193 pktout.savedpos = pktout.length;
1195 static void ssh2_pkt_addstring_str(char *data)
1197 ssh2_pkt_adddata(data, strlen(data));
1198 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1199 pktout.length - pktout.savedpos);
1201 static void ssh2_pkt_addstring_data(char *data, int len)
1203 ssh2_pkt_adddata(data, len);
1204 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1205 pktout.length - pktout.savedpos);
1207 static void ssh2_pkt_addstring(char *data)
1209 ssh2_pkt_addstring_start();
1210 ssh2_pkt_addstring_str(data);
1212 static char *ssh2_mpint_fmt(Bignum b, int *len)
1215 int i, n = (bignum_bitcount(b) + 7) / 8;
1218 fatalbox("out of memory");
1220 for (i = 1; i <= n; i++)
1221 p[i] = bignum_byte(b, n - i);
1223 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1225 memmove(p, p + i, n + 1 - i);
1229 static void ssh2_pkt_addmp(Bignum b)
1233 p = ssh2_mpint_fmt(b, &len);
1234 ssh2_pkt_addstring_start();
1235 ssh2_pkt_addstring_data(p, len);
1240 * Construct an SSH2 final-form packet: compress it, encrypt it,
1241 * put the MAC on it. Final packet, ready to be sent, is stored in
1242 * pktout.data. Total length is returned.
1244 static int ssh2_pkt_construct(void)
1246 int cipherblk, maclen, padding, i;
1247 static unsigned long outgoing_sequence = 0;
1250 * Compress packet payload.
1253 debug(("Pre-compression payload:\n"));
1254 dmemdump(pktout.data + 5, pktout.length - 5);
1257 unsigned char *newpayload;
1259 if (cscomp && cscomp->compress(pktout.data + 5, pktout.length - 5,
1260 &newpayload, &newlen)) {
1262 ssh2_pkt_adddata(newpayload, newlen);
1268 * Add padding. At least four bytes, and must also bring total
1269 * length (minus MAC) up to a multiple of the block size.
1271 cipherblk = cscipher ? cscipher->blksize : 8; /* block size */
1272 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1275 (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
1276 maclen = csmac ? csmac->len : 0;
1277 ssh2_pkt_ensure(pktout.length + padding + maclen);
1278 pktout.data[4] = padding;
1279 for (i = 0; i < padding; i++)
1280 pktout.data[pktout.length + i] = random_byte();
1281 PUT_32BIT(pktout.data, pktout.length + padding - 4);
1283 csmac->generate(pktout.data, pktout.length + padding,
1285 outgoing_sequence++; /* whether or not we MACed */
1288 debug(("Sending packet len=%d\n", pktout.length + padding));
1289 dmemdump(pktout.data, pktout.length + padding);
1293 cscipher->encrypt(pktout.data, pktout.length + padding);
1295 /* Ready-to-send packet starts at pktout.data. We return length. */
1296 return pktout.length + padding + maclen;
1300 * Construct and send an SSH2 packet immediately.
1302 static void ssh2_pkt_send(void)
1306 len = ssh2_pkt_construct();
1307 backlog = sk_write(s, pktout.data, len);
1308 if (backlog > SSH_MAX_BACKLOG)
1309 ssh_throttle_all(1, backlog);
1313 * Construct an SSH2 packet and add it to a deferred data block.
1314 * Useful for sending multiple packets in a single sk_write() call,
1315 * to prevent a traffic-analysing listener from being able to work
1316 * out the length of any particular packet (such as the password
1319 * Note that because SSH2 sequence-numbers its packets, this can
1320 * NOT be used as an m4-style `defer' allowing packets to be
1321 * constructed in one order and sent in another.
1323 static void ssh2_pkt_defer(void)
1325 int len = ssh2_pkt_construct();
1326 if (deferred_len + len > deferred_size) {
1327 deferred_size = deferred_len + len + 128;
1328 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1330 memcpy(deferred_send_data + deferred_len, pktout.data, len);
1331 deferred_len += len;
1335 * Send the whole deferred data block constructed by
1336 * ssh2_pkt_defer() or SSH1's defer_packet().
1338 static void ssh_pkt_defersend(void)
1341 backlog = sk_write(s, deferred_send_data, deferred_len);
1342 deferred_len = deferred_size = 0;
1343 sfree(deferred_send_data);
1344 deferred_send_data = NULL;
1345 if (backlog > SSH_MAX_BACKLOG)
1346 ssh_throttle_all(1, backlog);
1350 void bndebug(char *string, Bignum b)
1354 p = ssh2_mpint_fmt(b, &len);
1355 debug(("%s", string));
1356 for (i = 0; i < len; i++)
1357 debug((" %02x", p[i]));
1363 static void sha_mpint(SHA_State * s, Bignum b)
1367 p = ssh2_mpint_fmt(b, &len);
1368 sha_string(s, p, len);
1373 * SSH2 packet decode functions.
1375 static unsigned long ssh2_pkt_getuint32(void)
1377 unsigned long value;
1378 if (pktin.length - pktin.savedpos < 4)
1379 return 0; /* arrgh, no way to decline (FIXME?) */
1380 value = GET_32BIT(pktin.data + pktin.savedpos);
1381 pktin.savedpos += 4;
1384 static int ssh2_pkt_getbool(void)
1386 unsigned long value;
1387 if (pktin.length - pktin.savedpos < 1)
1388 return 0; /* arrgh, no way to decline (FIXME?) */
1389 value = pktin.data[pktin.savedpos] != 0;
1393 static void ssh2_pkt_getstring(char **p, int *length)
1396 if (pktin.length - pktin.savedpos < 4)
1398 *length = GET_32BIT(pktin.data + pktin.savedpos);
1399 pktin.savedpos += 4;
1400 if (pktin.length - pktin.savedpos < *length)
1402 *p = pktin.data + pktin.savedpos;
1403 pktin.savedpos += *length;
1405 static Bignum ssh2_pkt_getmp(void)
1411 ssh2_pkt_getstring(&p, &length);
1415 bombout(("internal error: Can't handle negative mpints"));
1418 b = bignum_from_bytes(p, length);
1423 * Examine the remote side's version string and compare it against
1424 * a list of known buggy implementations.
1426 static void ssh_detect_bugs(char *vstring)
1428 char *imp; /* pointer to implementation part */
1430 imp += strcspn(imp, "-");
1433 imp += strcspn(imp, "-");
1437 ssh_remote_bugs = 0;
1439 if (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1440 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1441 !strcmp(imp, "1.2.22")) {
1443 * These versions don't support SSH1_MSG_IGNORE, so we have
1444 * to use a different defence against password length
1447 ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1448 logevent("We believe remote version has SSH1 ignore bug");
1451 if (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1452 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1453 !strncmp(imp, "2.1 ", 4)) {
1455 * These versions have the HMAC bug.
1457 ssh_remote_bugs |= BUG_SSH2_HMAC;
1458 logevent("We believe remote version has SSH2 HMAC bug");
1462 static int do_ssh_init(unsigned char c)
1465 static char version[10];
1466 static char *vstring;
1467 static int vstrsize;
1473 /* Search for the string "SSH-" in the input. */
1476 static const int transS[] = { 1, 2, 2, 1 };
1477 static const int transH[] = { 0, 0, 3, 0 };
1478 static const int transminus[] = { 0, 0, 0, -1 };
1489 crReturn(1); /* get another character */
1492 vstring = smalloc(16);
1494 strcpy(vstring, "SSH-");
1498 crReturn(1); /* get another char */
1499 if (vslen >= vstrsize - 1) {
1501 vstring = srealloc(vstring, vstrsize);
1503 vstring[vslen++] = c;
1508 } else if (i < sizeof(version) - 1)
1510 } else if (c == '\n')
1514 ssh_agentfwd_enabled = FALSE;
1515 rdpkt2_state.incoming_sequence = 0;
1518 vlog = smalloc(20 + vslen);
1519 sprintf(vlog, "Server version: %s", vstring);
1520 ssh_detect_bugs(vstring);
1521 vlog[strcspn(vlog, "\r\n")] = '\0';
1526 * Server version "1.99" means we can choose whether we use v1
1527 * or v2 protocol. Choice is based on cfg.sshprot.
1529 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1531 * This is a v2 server. Begin v2 protocol.
1533 char verstring[80], vlog[100];
1534 sprintf(verstring, "SSH-2.0-%s", sshver);
1535 SHA_Init(&exhashbase);
1537 * Hash our version string and their version string.
1539 sha_string(&exhashbase, verstring, strlen(verstring));
1540 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1541 sprintf(vlog, "We claim version: %s", verstring);
1543 strcat(verstring, "\n");
1544 logevent("Using SSH protocol version 2");
1545 sk_write(s, verstring, strlen(verstring));
1546 ssh_protocol = ssh2_protocol;
1548 s_rdpkt = ssh2_rdpkt;
1551 * This is a v1 server. Begin v1 protocol.
1553 char verstring[80], vlog[100];
1554 sprintf(verstring, "SSH-%s-%s",
1555 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"),
1557 sprintf(vlog, "We claim version: %s", verstring);
1559 strcat(verstring, "\n");
1560 logevent("Using SSH protocol version 1");
1561 sk_write(s, verstring, strlen(verstring));
1562 ssh_protocol = ssh1_protocol;
1564 s_rdpkt = ssh1_rdpkt;
1566 ssh_state = SSH_STATE_BEFORE_SIZE;
1573 static void ssh_gotdata(unsigned char *data, int datalen)
1578 * To begin with, feed the characters one by one to the
1579 * protocol initialisation / selection function do_ssh_init().
1580 * When that returns 0, we're done with the initial greeting
1581 * exchange and can move on to packet discipline.
1586 crReturnV; /* more data please */
1587 ret = do_ssh_init(*data);
1595 * We emerge from that loop when the initial negotiation is
1596 * over and we have selected an s_rdpkt function. Now pass
1597 * everything to s_rdpkt, and then pass the resulting packets
1598 * to the proper protocol handler.
1603 while (datalen > 0) {
1604 if (s_rdpkt(&data, &datalen) == 0) {
1605 if (ssh_state == SSH_STATE_CLOSED) {
1608 ssh_protocol(NULL, 0, 1);
1609 if (ssh_state == SSH_STATE_CLOSED) {
1619 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1622 ssh_state = SSH_STATE_CLOSED;
1628 /* A socket error has occurred. */
1629 connection_fatal(error_msg);
1631 /* Otherwise, the remote side closed the connection normally. */
1636 static int ssh_receive(Plug plug, int urgent, char *data, int len)
1638 ssh_gotdata(data, len);
1639 if (ssh_state == SSH_STATE_CLOSED) {
1649 static void ssh_sent(Plug plug, int bufsize)
1652 * If the send backlog on the SSH socket itself clears, we
1653 * should unthrottle the whole world if it was throttled.
1655 if (bufsize < SSH_MAX_BACKLOG)
1656 ssh_throttle_all(0, bufsize);
1660 * Connect to specified host and port.
1661 * Returns an error message, or NULL on success.
1662 * Also places the canonical host name into `realhost'. It must be
1663 * freed by the caller.
1665 static char *connect_to_host(char *host, int port, char **realhost)
1667 static struct plug_function_table fn_table = {
1672 }, *fn_table_ptr = &fn_table;
1681 savedhost = smalloc(1 + strlen(host));
1683 fatalbox("Out of memory");
1684 strcpy(savedhost, host);
1687 port = 22; /* default ssh port */
1702 sprintf(buf, "Looking up host \"%.170s\"", host);
1705 addr = sk_namelookup(host, realhost);
1706 if ((err = sk_addr_error(addr)))
1710 *realhost = strdup(FWhost);
1717 char buf[200], addrbuf[100];
1718 sk_getaddr(addr, addrbuf, 100);
1719 sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
1722 s = sk_new(addr, port, 0, 1, &fn_table_ptr);
1723 if ((err = sk_socket_error(s)))
1727 sk_write(s, "connect ", 8);
1728 sk_write(s, FWhost, strlen(FWhost));
1731 sprintf(buf, " %d\n", FWport);
1732 sk_write(s, buf, strlen(buf));
1740 * Throttle or unthrottle the SSH connection.
1742 static void ssh1_throttle(int adjust)
1744 int old_count = ssh1_throttle_count;
1745 ssh1_throttle_count += adjust;
1746 assert(ssh1_throttle_count >= 0);
1747 if (ssh1_throttle_count && !old_count) {
1748 sk_set_frozen(s, 1);
1749 } else if (!ssh1_throttle_count && old_count) {
1750 sk_set_frozen(s, 0);
1755 * Throttle or unthrottle _all_ local data streams (for when sends
1756 * on the SSH connection itself back up).
1758 static void ssh_throttle_all(int enable, int bufsize)
1761 struct ssh_channel *c;
1763 if (enable == ssh_throttled_all)
1765 ssh_throttled_all = enable;
1766 ssh_overall_bufsize = bufsize;
1769 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
1771 case CHAN_MAINSESSION:
1773 * This is treated separately, outside the switch.
1777 x11_override_throttle(c->u.x11.s, enable);
1780 /* Agent channels require no buffer management. */
1783 pfd_override_throttle(c->u.x11.s, enable);
1790 * Handle the key exchange and user authentication phases.
1792 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1796 static unsigned char *rsabuf, *keystr1, *keystr2;
1797 unsigned char cookie[8];
1798 struct RSAKey servkey, hostkey;
1799 struct MD5Context md5c;
1800 static unsigned long supported_ciphers_mask, supported_auths_mask;
1801 static int tried_publickey;
1802 static int tis_auth_refused, ccard_auth_refused;
1803 static unsigned char session_id[16];
1804 static int cipher_type;
1805 static char username[100];
1812 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1813 bombout(("Public key packet not received"));
1817 logevent("Received public keys");
1819 memcpy(cookie, pktin.body, 8);
1821 i = makekey(pktin.body + 8, &servkey, &keystr1, 0);
1822 j = makekey(pktin.body + 8 + i, &hostkey, &keystr2, 0);
1825 * Log the host key fingerprint.
1829 logevent("Host key fingerprint is:");
1830 strcpy(logmsg, " ");
1831 hostkey.comment = NULL;
1832 rsa_fingerprint(logmsg + strlen(logmsg),
1833 sizeof(logmsg) - strlen(logmsg), &hostkey);
1837 ssh1_remote_protoflags = GET_32BIT(pktin.body + 8 + i + j);
1838 supported_ciphers_mask = GET_32BIT(pktin.body + 12 + i + j);
1839 supported_auths_mask = GET_32BIT(pktin.body + 16 + i + j);
1841 ssh1_local_protoflags =
1842 ssh1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
1843 ssh1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
1846 MD5Update(&md5c, keystr2, hostkey.bytes);
1847 MD5Update(&md5c, keystr1, servkey.bytes);
1848 MD5Update(&md5c, pktin.body, 8);
1849 MD5Final(session_id, &md5c);
1851 for (i = 0; i < 32; i++)
1852 session_key[i] = random_byte();
1854 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1856 rsabuf = smalloc(len);
1858 fatalbox("Out of memory");
1861 * Verify the host key.
1865 * First format the key into a string.
1867 int len = rsastr_len(&hostkey);
1868 char fingerprint[100];
1869 char *keystr = smalloc(len);
1871 fatalbox("Out of memory");
1872 rsastr_fmt(keystr, &hostkey);
1873 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
1874 verify_ssh_host_key(savedhost, savedport, "rsa", keystr,
1879 for (i = 0; i < 32; i++) {
1880 rsabuf[i] = session_key[i];
1882 rsabuf[i] ^= session_id[i];
1885 if (hostkey.bytes > servkey.bytes) {
1886 rsaencrypt(rsabuf, 32, &servkey);
1887 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1889 rsaencrypt(rsabuf, 32, &hostkey);
1890 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1893 logevent("Encrypted session key");
1896 int cipher_chosen = 0, warn = 0;
1897 char *cipher_string = NULL;
1898 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
1899 int next_cipher = cfg.ssh_cipherlist[i];
1900 if (next_cipher == CIPHER_WARN) {
1901 /* If/when we choose a cipher, warn about it */
1903 } else if (next_cipher == CIPHER_AES) {
1904 /* XXX Probably don't need to mention this. */
1905 logevent("AES not supported in SSH1, skipping");
1907 switch (next_cipher) {
1908 case CIPHER_3DES: cipher_type = SSH_CIPHER_3DES;
1909 cipher_string = "3DES"; break;
1910 case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH;
1911 cipher_string = "Blowfish"; break;
1912 case CIPHER_DES: cipher_type = SSH_CIPHER_DES;
1913 cipher_string = "single-DES"; break;
1915 if (supported_ciphers_mask & (1 << cipher_type))
1919 if (!cipher_chosen) {
1920 if ((supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
1921 bombout(("Server violates SSH 1 protocol by not "
1922 "supporting 3DES encryption"));
1924 /* shouldn't happen */
1925 bombout(("No supported ciphers found"));
1929 /* Warn about chosen cipher if necessary. */
1931 askcipher(cipher_string, 0);
1934 switch (cipher_type) {
1935 case SSH_CIPHER_3DES:
1936 logevent("Using 3DES encryption");
1938 case SSH_CIPHER_DES:
1939 logevent("Using single-DES encryption");
1941 case SSH_CIPHER_BLOWFISH:
1942 logevent("Using Blowfish encryption");
1946 send_packet(SSH1_CMSG_SESSION_KEY,
1947 PKT_CHAR, cipher_type,
1948 PKT_DATA, cookie, 8,
1949 PKT_CHAR, (len * 8) >> 8, PKT_CHAR, (len * 8) & 0xFF,
1950 PKT_DATA, rsabuf, len,
1951 PKT_INT, ssh1_local_protoflags, PKT_END);
1953 logevent("Trying to enable encryption...");
1957 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1958 cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des;
1959 cipher->sesskey(session_key);
1963 if (pktin.type != SSH1_SMSG_SUCCESS) {
1964 bombout(("Encryption not successfully enabled"));
1968 logevent("Successfully started encryption");
1974 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1976 if (!ssh_get_line("login as: ",
1977 username, sizeof(username), FALSE)) {
1979 * get_line failed to get a username.
1982 logevent("No username provided. Abandoning session.");
1983 ssh_state = SSH_STATE_CLOSED;
1987 c_write_str("login as: ");
1990 crWaitUntil(!ispkt);
1992 switch (c = *in++) {
2001 c_write_str("\b \b");
2008 c_write_str("\b \b");
2018 if (((c >= ' ' && c <= '~') ||
2019 ((unsigned char) c >= 160))
2020 && pos < sizeof(username)-1) {
2021 username[pos++] = c;
2027 c_write_str("\r\n");
2028 username[strcspn(username, "\n\r")] = '\0';
2031 strncpy(username, cfg.username, 99);
2032 username[99] = '\0';
2035 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
2037 char userlog[22 + sizeof(username)];
2038 sprintf(userlog, "Sent username \"%s\"", username);
2040 if (flags & FLAG_INTERACTIVE &&
2041 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2042 strcat(userlog, "\r\n");
2043 c_write_str(userlog);
2050 tried_publickey = 0;
2051 tis_auth_refused = ccard_auth_refused = 0;
2053 while (pktin.type == SSH1_SMSG_FAILURE) {
2054 static char password[100];
2055 static char prompt[200];
2058 static int pwpkt_type;
2059 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2061 if (agent_exists()) {
2063 * Attempt RSA authentication using Pageant.
2065 static unsigned char request[5], *response, *p;
2066 static int responselen;
2067 static int i, nkeys;
2068 static int authed = FALSE;
2071 logevent("Pageant is running. Requesting keys.");
2073 /* Request the keys held by the agent. */
2074 PUT_32BIT(request, 1);
2075 request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2076 agent_query(request, 5, &r, &responselen);
2077 response = (unsigned char *) r;
2078 if (response && responselen >= 5 &&
2079 response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2081 nkeys = GET_32BIT(p);
2085 sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
2088 for (i = 0; i < nkeys; i++) {
2089 static struct RSAKey key;
2090 static Bignum challenge;
2091 static char *commentp;
2092 static int commentlen;
2096 sprintf(buf, "Trying Pageant key #%d", i);
2100 p += ssh1_read_bignum(p, &key.exponent);
2101 p += ssh1_read_bignum(p, &key.modulus);
2102 commentlen = GET_32BIT(p);
2106 send_packet(SSH1_CMSG_AUTH_RSA,
2107 PKT_BIGNUM, key.modulus, PKT_END);
2109 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2110 logevent("Key refused");
2113 logevent("Received RSA challenge");
2114 ssh1_read_bignum(pktin.body, &challenge);
2116 char *agentreq, *q, *ret;
2119 len = 1 + 4; /* message type, bit count */
2120 len += ssh1_bignum_length(key.exponent);
2121 len += ssh1_bignum_length(key.modulus);
2122 len += ssh1_bignum_length(challenge);
2123 len += 16; /* session id */
2124 len += 4; /* response format */
2125 agentreq = smalloc(4 + len);
2126 PUT_32BIT(agentreq, len);
2128 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2129 PUT_32BIT(q, bignum_bitcount(key.modulus));
2131 q += ssh1_write_bignum(q, key.exponent);
2132 q += ssh1_write_bignum(q, key.modulus);
2133 q += ssh1_write_bignum(q, challenge);
2134 memcpy(q, session_id, 16);
2136 PUT_32BIT(q, 1); /* response format */
2137 agent_query(agentreq, len + 4, &vret, &retlen);
2141 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2142 logevent("Sending Pageant's response");
2143 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2144 PKT_DATA, ret + 5, 16,
2148 if (pktin.type == SSH1_SMSG_SUCCESS) {
2150 ("Pageant's response accepted");
2151 if (flags & FLAG_VERBOSE) {
2153 ("Authenticated using RSA key \"");
2154 c_write(commentp, commentlen);
2155 c_write_str("\" from agent\r\n");
2160 ("Pageant's response not accepted");
2163 ("Pageant failed to answer challenge");
2167 logevent("No reply received from Pageant");
2170 freebn(key.exponent);
2171 freebn(key.modulus);
2180 if (*cfg.keyfile && !tried_publickey)
2181 pwpkt_type = SSH1_CMSG_AUTH_RSA;
2183 if (cfg.try_tis_auth &&
2184 (supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2185 !tis_auth_refused) {
2186 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2187 logevent("Requested TIS authentication");
2188 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
2190 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2191 logevent("TIS authentication declined");
2192 if (flags & FLAG_INTERACTIVE)
2193 c_write_str("TIS authentication refused.\r\n");
2194 tis_auth_refused = 1;
2197 int challengelen = ((pktin.body[0] << 24) |
2198 (pktin.body[1] << 16) |
2199 (pktin.body[2] << 8) |
2201 logevent("Received TIS challenge");
2202 if (challengelen > sizeof(prompt) - 1)
2203 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2204 memcpy(prompt, pktin.body + 4, challengelen);
2205 /* Prompt heuristic comes from OpenSSH */
2206 strncpy(prompt + challengelen,
2207 memchr(prompt, '\n', challengelen) ?
2208 "": "\r\nResponse: ",
2209 (sizeof prompt) - challengelen);
2210 prompt[(sizeof prompt) - 1] = '\0';
2213 if (cfg.try_tis_auth &&
2214 (supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2215 !ccard_auth_refused) {
2216 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2217 logevent("Requested CryptoCard authentication");
2218 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
2220 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2221 logevent("CryptoCard authentication declined");
2222 c_write_str("CryptoCard authentication refused.\r\n");
2223 ccard_auth_refused = 1;
2226 int challengelen = ((pktin.body[0] << 24) |
2227 (pktin.body[1] << 16) |
2228 (pktin.body[2] << 8) |
2230 logevent("Received CryptoCard challenge");
2231 if (challengelen > sizeof(prompt) - 1)
2232 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2233 memcpy(prompt, pktin.body + 4, challengelen);
2234 strncpy(prompt + challengelen,
2235 memchr(prompt, '\n', challengelen) ?
2236 "" : "\r\nResponse: ",
2237 sizeof(prompt) - challengelen);
2238 prompt[sizeof(prompt) - 1] = '\0';
2241 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2242 sprintf(prompt, "%.90s@%.90s's password: ",
2243 username, savedhost);
2245 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2246 char *comment = NULL;
2247 if (flags & FLAG_VERBOSE)
2248 c_write_str("Trying public key authentication.\r\n");
2249 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2250 if (flags & FLAG_VERBOSE)
2251 c_write_str("No passphrase required.\r\n");
2254 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
2259 * Show password prompt, having first obtained it via a TIS
2260 * or CryptoCard exchange if we're doing TIS or CryptoCard
2264 if (!ssh_get_line(prompt, password, sizeof(password), TRUE)) {
2266 * get_line failed to get a password (for example
2267 * because one was supplied on the command line
2268 * which has already failed to work). Terminate.
2270 send_packet(SSH1_MSG_DISCONNECT,
2271 PKT_STR, "No more passwords available to try",
2273 connection_fatal("Unable to authenticate");
2274 ssh_state = SSH_STATE_CLOSED;
2278 /* Prompt may have come from server. We've munged it a bit, so
2279 * we know it to be zero-terminated at least once. */
2280 c_write_untrusted(prompt, strlen(prompt));
2284 crWaitUntil(!ispkt);
2286 switch (c = *in++) {
2307 if (pos < sizeof(password)-1)
2308 password[pos++] = c;
2312 c_write_str("\r\n");
2316 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2318 * Try public key authentication with the specified
2321 static struct RSAKey pubkey;
2322 static Bignum challenge, response;
2324 static unsigned char buffer[32];
2326 tried_publickey = 1;
2327 i = loadrsakey(cfg.keyfile, &pubkey, password);
2329 c_write_str("Couldn't load private key from ");
2330 c_write_str(cfg.keyfile);
2331 c_write_str(".\r\n");
2332 continue; /* go and try password */
2335 c_write_str("Wrong passphrase.\r\n");
2336 tried_publickey = 0;
2337 continue; /* try again */
2341 * Send a public key attempt.
2343 send_packet(SSH1_CMSG_AUTH_RSA,
2344 PKT_BIGNUM, pubkey.modulus, PKT_END);
2347 if (pktin.type == SSH1_SMSG_FAILURE) {
2348 c_write_str("Server refused our public key.\r\n");
2349 continue; /* go and try password */
2351 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2352 bombout(("Bizarre response to offer of public key"));
2355 ssh1_read_bignum(pktin.body, &challenge);
2356 response = rsadecrypt(challenge, &pubkey);
2357 freebn(pubkey.private_exponent); /* burn the evidence */
2359 for (i = 0; i < 32; i++) {
2360 buffer[i] = bignum_byte(response, 31 - i);
2364 MD5Update(&md5c, buffer, 32);
2365 MD5Update(&md5c, session_id, 16);
2366 MD5Final(buffer, &md5c);
2368 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2369 PKT_DATA, buffer, 16, PKT_END);
2372 if (pktin.type == SSH1_SMSG_FAILURE) {
2373 if (flags & FLAG_VERBOSE)
2375 ("Failed to authenticate with our public key.\r\n");
2376 continue; /* go and try password */
2377 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2379 ("Bizarre response to RSA authentication response"));
2383 break; /* we're through! */
2385 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2387 * Defence against traffic analysis: we send a
2388 * whole bunch of packets containing strings of
2389 * different lengths. One of these strings is the
2390 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2391 * The others are all random data in
2392 * SSH1_MSG_IGNORE packets. This way a passive
2393 * listener can't tell which is the password, and
2394 * hence can't deduce the password length.
2396 * Anybody with a password length greater than 16
2397 * bytes is going to have enough entropy in their
2398 * password that a listener won't find it _that_
2399 * much help to know how long it is. So what we'll
2402 * - if password length < 16, we send 15 packets
2403 * containing string lengths 1 through 15
2405 * - otherwise, we let N be the nearest multiple
2406 * of 8 below the password length, and send 8
2407 * packets containing string lengths N through
2408 * N+7. This won't obscure the order of
2409 * magnitude of the password length, but it will
2410 * introduce a bit of extra uncertainty.
2412 * A few servers (the old 1.2.18 through 1.2.22)
2413 * can't deal with SSH1_MSG_IGNORE. For these
2414 * servers, we need an alternative defence. We make
2415 * use of the fact that the password is interpreted
2416 * as a C string: so we can append a NUL, then some
2419 if (ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) {
2424 len = strlen(password);
2425 if (len < sizeof(string)) {
2427 strcpy(string, password);
2428 len++; /* cover the zero byte */
2429 while (len < sizeof(string)) {
2430 string[len++] = (char) random_byte();
2435 send_packet(pwpkt_type, PKT_INT, len,
2436 PKT_DATA, s, len, PKT_END);
2438 int bottom, top, pwlen, i;
2441 pwlen = strlen(password);
2443 bottom = 0; /* zero length passwords are OK! :-) */
2446 bottom = pwlen & ~7;
2450 assert(pwlen >= bottom && pwlen <= top);
2452 randomstr = smalloc(top + 1);
2454 for (i = bottom; i <= top; i++) {
2456 defer_packet(pwpkt_type, PKT_STR, password,
2459 for (j = 0; j < i; j++) {
2461 randomstr[j] = random_byte();
2462 } while (randomstr[j] == '\0');
2464 randomstr[i] = '\0';
2465 defer_packet(SSH1_MSG_IGNORE,
2466 PKT_STR, randomstr, PKT_END);
2469 ssh_pkt_defersend();
2472 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
2475 logevent("Sent password");
2476 memset(password, 0, strlen(password));
2478 if (pktin.type == SSH1_SMSG_FAILURE) {
2479 if (flags & FLAG_VERBOSE)
2480 c_write_str("Access denied\r\n");
2481 logevent("Authentication refused");
2482 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2483 logevent("Received disconnect request");
2484 ssh_state = SSH_STATE_CLOSED;
2486 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2487 bombout(("Strange packet received, type %d", pktin.type));
2492 logevent("Authentication successful");
2497 void sshfwd_close(struct ssh_channel *c)
2499 if (c && !c->closes) {
2500 if (ssh_version == 1) {
2501 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2504 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2505 ssh2_pkt_adduint32(c->remoteid);
2509 if (c->type == CHAN_X11) {
2511 logevent("Forwarded X11 connection terminated");
2512 } else if (c->type == CHAN_SOCKDATA) {
2514 logevent("Forwarded port closed");
2519 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2521 if (ssh_version == 1) {
2522 send_packet(SSH1_MSG_CHANNEL_DATA,
2523 PKT_INT, c->remoteid,
2524 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2526 * In SSH1 we can return 0 here - implying that forwarded
2527 * connections are never individually throttled - because
2528 * the only circumstance that can cause throttling will be
2529 * the whole SSH connection backing up, in which case
2530 * _everything_ will be throttled as a whole.
2534 ssh2_add_channel_data(c, buf, len);
2535 return ssh2_try_send(c);
2539 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2541 if (ssh_version == 1) {
2542 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2543 c->v.v1.throttling = 0;
2547 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2551 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt)
2557 while (!do_ssh1_login(in, inlen, ispkt)) {
2560 if (ssh_state == SSH_STATE_CLOSED)
2563 if (cfg.agentfwd && agent_exists()) {
2564 logevent("Requesting agent forwarding");
2565 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2569 if (pktin.type != SSH1_SMSG_SUCCESS
2570 && pktin.type != SSH1_SMSG_FAILURE) {
2571 bombout(("Protocol confusion"));
2573 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2574 logevent("Agent forwarding refused");
2576 logevent("Agent forwarding enabled");
2577 ssh_agentfwd_enabled = TRUE;
2581 if (cfg.x11_forward) {
2582 char proto[20], data[64];
2583 logevent("Requesting X11 forwarding");
2584 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2585 if (ssh1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
2586 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2587 PKT_STR, proto, PKT_STR, data,
2588 PKT_INT, 0, PKT_END);
2590 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2591 PKT_STR, proto, PKT_STR, data, PKT_END);
2596 if (pktin.type != SSH1_SMSG_SUCCESS
2597 && pktin.type != SSH1_SMSG_FAILURE) {
2598 bombout(("Protocol confusion"));
2600 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2601 logevent("X11 forwarding refused");
2603 logevent("X11 forwarding enabled");
2604 ssh_X11_fwd_enabled = TRUE;
2612 char sports[256], dports[256], host[256];
2615 ssh_rportfwds = newtree234(ssh_rportcmp_ssh1);
2616 /* Add port forwardings. */
2621 while (*e && *e != '\t')
2627 while (*e && *e != ':')
2637 dport = atoi(dports);
2638 sport = atoi(sports);
2639 if (sport && dport) {
2641 pfd_addforward(host, dport, sport);
2642 sprintf(buf, "Local port %d forwarding to %s:%d",
2643 sport, host, dport);
2646 struct ssh_rportfwd *pf;
2647 pf = smalloc(sizeof(*pf));
2648 strcpy(pf->dhost, host);
2650 if (add234(ssh_rportfwds, pf) != pf) {
2652 "Duplicate remote port forwarding to %s:%d",
2657 sprintf(buf, "Requesting remote port %d forward to %s:%d",
2658 sport, host, dport);
2660 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST,
2672 send_packet(SSH1_CMSG_REQUEST_PTY,
2673 PKT_STR, cfg.termtype,
2674 PKT_INT, rows, PKT_INT, cols,
2675 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
2676 ssh_state = SSH_STATE_INTERMED;
2680 if (pktin.type != SSH1_SMSG_SUCCESS
2681 && pktin.type != SSH1_SMSG_FAILURE) {
2682 bombout(("Protocol confusion"));
2684 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2685 c_write_str("Server refused to allocate pty\r\n");
2686 ssh_editing = ssh_echoing = 1;
2688 logevent("Allocated pty");
2690 ssh_editing = ssh_echoing = 1;
2693 if (cfg.compression) {
2694 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
2698 if (pktin.type != SSH1_SMSG_SUCCESS
2699 && pktin.type != SSH1_SMSG_FAILURE) {
2700 bombout(("Protocol confusion"));
2702 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2703 c_write_str("Server refused to compress\r\n");
2705 logevent("Started compression");
2706 ssh1_compressing = TRUE;
2707 zlib_compress_init();
2708 zlib_decompress_init();
2712 * Start the shell or command.
2714 * Special case: if the first-choice command is an SSH2
2715 * subsystem (hence not usable here) and the second choice
2716 * exists, we fall straight back to that.
2719 char *cmd = cfg.remote_cmd_ptr;
2721 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
2722 cmd = cfg.remote_cmd_ptr2;
2723 ssh_fallback_cmd = TRUE;
2726 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
2728 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
2729 logevent("Started session");
2732 ssh_state = SSH_STATE_SESSION;
2736 ssh_special(TS_EOF);
2738 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
2740 ssh_channels = newtree234(ssh_channelcmp);
2744 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
2745 pktin.type == SSH1_SMSG_STDERR_DATA) {
2746 long len = GET_32BIT(pktin.body);
2748 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
2749 pktin.body + 4, len);
2750 if (!ssh1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
2751 ssh1_stdout_throttling = 1;
2754 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2755 ssh_state = SSH_STATE_CLOSED;
2756 logevent("Received disconnect request");
2758 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
2759 /* Remote side is trying to open a channel to talk to our
2760 * X-Server. Give them back a local channel number. */
2761 struct ssh_channel *c;
2763 logevent("Received X11 connect request");
2764 /* Refuse if X11 forwarding is disabled. */
2765 if (!ssh_X11_fwd_enabled) {
2766 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2767 PKT_INT, GET_32BIT(pktin.body), PKT_END);
2768 logevent("Rejected X11 connect request");
2770 c = smalloc(sizeof(struct ssh_channel));
2772 if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
2773 logevent("opening X11 forward connection failed");
2775 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2776 PKT_INT, GET_32BIT(pktin.body),
2780 ("opening X11 forward connection succeeded");
2781 c->remoteid = GET_32BIT(pktin.body);
2782 c->localid = alloc_channel_id();
2784 c->v.v1.throttling = 0;
2785 c->type = CHAN_X11; /* identify channel type */
2786 add234(ssh_channels, c);
2787 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2788 PKT_INT, c->remoteid, PKT_INT,
2789 c->localid, PKT_END);
2790 logevent("Opened X11 forward channel");
2793 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
2794 /* Remote side is trying to open a channel to talk to our
2795 * agent. Give them back a local channel number. */
2796 struct ssh_channel *c;
2798 /* Refuse if agent forwarding is disabled. */
2799 if (!ssh_agentfwd_enabled) {
2800 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2801 PKT_INT, GET_32BIT(pktin.body), PKT_END);
2803 c = smalloc(sizeof(struct ssh_channel));
2804 c->remoteid = GET_32BIT(pktin.body);
2805 c->localid = alloc_channel_id();
2807 c->v.v1.throttling = 0;
2808 c->type = CHAN_AGENT; /* identify channel type */
2809 c->u.a.lensofar = 0;
2810 add234(ssh_channels, c);
2811 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2812 PKT_INT, c->remoteid, PKT_INT, c->localid,
2815 } else if (pktin.type == SSH1_MSG_PORT_OPEN) {
2816 /* Remote side is trying to open a channel to talk to a
2817 * forwarded port. Give them back a local channel number. */
2818 struct ssh_channel *c;
2819 struct ssh_rportfwd pf;
2821 char host[256], buf[1024];
2823 c = smalloc(sizeof(struct ssh_channel));
2825 hostsize = GET_32BIT(pktin.body+4);
2826 for(h = host, p = pktin.body+8; hostsize != 0; hostsize--) {
2827 if (h+1 < host+sizeof(host))
2832 port = GET_32BIT(p);
2834 strcpy(pf.dhost, host);
2837 if (find234(ssh_rportfwds, &pf, NULL) == NULL) {
2838 sprintf(buf, "Rejected remote port open request for %s:%d",
2841 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2842 PKT_INT, GET_32BIT(pktin.body), PKT_END);
2844 sprintf(buf, "Received remote port open request for %s:%d",
2847 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
2850 sprintf(buf, "Port open failed: %s", e);
2853 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2854 PKT_INT, GET_32BIT(pktin.body),
2857 c->remoteid = GET_32BIT(pktin.body);
2858 c->localid = alloc_channel_id();
2860 c->v.v1.throttling = 0;
2861 c->type = CHAN_SOCKDATA; /* identify channel type */
2862 add234(ssh_channels, c);
2863 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2864 PKT_INT, c->remoteid, PKT_INT,
2865 c->localid, PKT_END);
2866 logevent("Forwarded port opened successfully");
2870 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
2871 unsigned int remoteid = GET_32BIT(pktin.body);
2872 unsigned int localid = GET_32BIT(pktin.body+4);
2873 struct ssh_channel *c;
2875 c = find234(ssh_channels, &remoteid, ssh_channelfind);
2876 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
2877 c->remoteid = localid;
2878 c->type = CHAN_SOCKDATA;
2879 pfd_confirm(c->u.pfd.s);
2882 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
2883 unsigned int remoteid = GET_32BIT(pktin.body);
2884 unsigned int localid = GET_32BIT(pktin.body+4);
2885 struct ssh_channel *c;
2887 c = find234(ssh_channels, &remoteid, ssh_channelfind);
2888 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
2889 logevent("Forwarded connection refused by server");
2890 pfd_close(c->u.pfd.s);
2891 del234(ssh_channels, c);
2895 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2896 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
2897 /* Remote side closes a channel. */
2898 unsigned i = GET_32BIT(pktin.body);
2899 struct ssh_channel *c;
2900 c = find234(ssh_channels, &i, ssh_channelfind);
2904 (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2905 if (!(c->closes & closetype))
2906 send_packet(pktin.type, PKT_INT, c->remoteid,
2908 if ((c->closes == 0) && (c->type == CHAN_X11)) {
2909 logevent("Forwarded X11 connection terminated");
2910 assert(c->u.x11.s != NULL);
2911 x11_close(c->u.x11.s);
2914 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
2915 logevent("Forwarded port closed");
2916 assert(c->u.pfd.s != NULL);
2917 pfd_close(c->u.pfd.s);
2920 c->closes |= closetype;
2921 if (c->closes == 3) {
2922 del234(ssh_channels, c);
2926 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2927 /* Data sent down one of our channels. */
2928 int i = GET_32BIT(pktin.body);
2929 int len = GET_32BIT(pktin.body + 4);
2930 unsigned char *p = pktin.body + 8;
2931 struct ssh_channel *c;
2932 c = find234(ssh_channels, &i, ssh_channelfind);
2937 bufsize = x11_send(c->u.x11.s, p, len);
2940 bufsize = pfd_send(c->u.pfd.s, p, len);
2943 /* Data for an agent message. Buffer it. */
2945 if (c->u.a.lensofar < 4) {
2946 int l = min(4 - c->u.a.lensofar, len);
2947 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
2951 c->u.a.lensofar += l;
2953 if (c->u.a.lensofar == 4) {
2955 4 + GET_32BIT(c->u.a.msglen);
2956 c->u.a.message = smalloc(c->u.a.totallen);
2957 memcpy(c->u.a.message, c->u.a.msglen, 4);
2959 if (c->u.a.lensofar >= 4 && len > 0) {
2961 min(c->u.a.totallen - c->u.a.lensofar,
2963 memcpy(c->u.a.message + c->u.a.lensofar, p,
2967 c->u.a.lensofar += l;
2969 if (c->u.a.lensofar == c->u.a.totallen) {
2970 void *reply, *sentreply;
2972 agent_query(c->u.a.message,
2973 c->u.a.totallen, &reply,
2978 /* Fake SSH_AGENT_FAILURE. */
2979 sentreply = "\0\0\0\1\5";
2982 send_packet(SSH1_MSG_CHANNEL_DATA,
2983 PKT_INT, c->remoteid,
2985 PKT_DATA, sentreply, replylen,
2989 sfree(c->u.a.message);
2990 c->u.a.lensofar = 0;
2993 bufsize = 0; /* agent channels never back up */
2996 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
2997 c->v.v1.throttling = 1;
3001 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
3002 /* may be from EXEC_SHELL on some servers */
3003 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3004 /* may be from EXEC_SHELL on some servers
3005 * if no pty is available or in other odd cases. Ignore */
3006 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
3007 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3009 bombout(("Strange packet received: type %d", pktin.type));
3014 int len = min(inlen, 512);
3015 send_packet(SSH1_CMSG_STDIN_DATA,
3016 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3027 * Utility routine for decoding comma-separated strings in KEXINIT.
3029 static int in_commasep_string(char *needle, char *haystack, int haylen)
3031 int needlen = strlen(needle);
3034 * Is it at the start of the string?
3036 if (haylen >= needlen && /* haystack is long enough */
3037 !memcmp(needle, haystack, needlen) && /* initial match */
3038 (haylen == needlen || haystack[needlen] == ',')
3039 /* either , or EOS follows */
3043 * If not, search for the next comma and resume after that.
3044 * If no comma found, terminate.
3046 while (haylen > 0 && *haystack != ',')
3047 haylen--, haystack++;
3050 haylen--, haystack++; /* skip over comma itself */
3055 * SSH2 key creation method.
3057 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr,
3061 /* First 20 bytes. */
3064 SHA_Bytes(&s, H, 20);
3065 SHA_Bytes(&s, &chr, 1);
3066 SHA_Bytes(&s, sessid, 20);
3067 SHA_Final(&s, keyspace);
3068 /* Next 20 bytes. */
3071 SHA_Bytes(&s, H, 20);
3072 SHA_Bytes(&s, keyspace, 20);
3073 SHA_Final(&s, keyspace + 20);
3077 * Handle the SSH2 transport layer.
3079 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
3081 static int i, j, len, nbits, pbits, warn;
3083 static Bignum p, g, e, f, K;
3084 static int kex_init_value, kex_reply_value;
3085 static const struct ssh_mac **maclist;
3087 static const struct ssh2_cipher *cscipher_tobe = NULL;
3088 static const struct ssh2_cipher *sccipher_tobe = NULL;
3089 static const struct ssh_mac *csmac_tobe = NULL;
3090 static const struct ssh_mac *scmac_tobe = NULL;
3091 static const struct ssh_compress *cscomp_tobe = NULL;
3092 static const struct ssh_compress *sccomp_tobe = NULL;
3093 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
3094 static int hostkeylen, siglen;
3095 static void *hkey; /* actual host key */
3096 static unsigned char exchange_hash[20];
3097 static unsigned char keyspace[40];
3098 static int n_preferred_ciphers;
3099 static const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3100 static const struct ssh_compress *preferred_comp;
3101 static int first_kex;
3108 * Set up the preferred ciphers. (NULL => warn below here)
3110 n_preferred_ciphers = 0;
3111 for (i = 0; i < CIPHER_MAX; i++) {
3112 switch (cfg.ssh_cipherlist[i]) {
3113 case CIPHER_BLOWFISH:
3114 preferred_ciphers[n_preferred_ciphers] = &ssh2_blowfish;
3115 n_preferred_ciphers++;
3118 /* Not supported in SSH2; silently drop */
3121 preferred_ciphers[n_preferred_ciphers] = &ssh2_3des;
3122 n_preferred_ciphers++;
3125 preferred_ciphers[n_preferred_ciphers] = &ssh2_aes;
3126 n_preferred_ciphers++;
3129 /* Flag for later. Don't bother if it's the last in
3131 if (i < CIPHER_MAX - 1) {
3132 preferred_ciphers[n_preferred_ciphers] = NULL;
3133 n_preferred_ciphers++;
3140 * Set up preferred compression.
3142 if (cfg.compression)
3143 preferred_comp = &ssh_zlib;
3145 preferred_comp = &ssh_comp_none;
3148 * Be prepared to work around the buggy MAC problem.
3150 if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
3151 maclist = buggymacs, nmacs = lenof(buggymacs);
3153 maclist = macs, nmacs = lenof(macs);
3157 * Construct and send our key exchange packet.
3159 ssh2_pkt_init(SSH2_MSG_KEXINIT);
3160 for (i = 0; i < 16; i++)
3161 ssh2_pkt_addbyte((unsigned char) random_byte());
3162 /* List key exchange algorithms. */
3163 ssh2_pkt_addstring_start();
3164 for (i = 0; i < lenof(kex_algs); i++) {
3165 ssh2_pkt_addstring_str(kex_algs[i]->name);
3166 if (i < lenof(kex_algs) - 1)
3167 ssh2_pkt_addstring_str(",");
3169 /* List server host key algorithms. */
3170 ssh2_pkt_addstring_start();
3171 for (i = 0; i < lenof(hostkey_algs); i++) {
3172 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
3173 if (i < lenof(hostkey_algs) - 1)
3174 ssh2_pkt_addstring_str(",");
3176 /* List client->server encryption algorithms. */
3177 ssh2_pkt_addstring_start();
3178 for (i = 0; i < n_preferred_ciphers; i++) {
3179 const struct ssh2_ciphers *c = preferred_ciphers[i];
3180 if (!c) continue; /* warning flag */
3181 for (j = 0; j < c->nciphers; j++) {
3182 ssh2_pkt_addstring_str(c->list[j]->name);
3183 if (i < n_preferred_ciphers || j < c->nciphers - 1)
3184 ssh2_pkt_addstring_str(",");
3187 /* List server->client encryption algorithms. */
3188 ssh2_pkt_addstring_start();
3189 for (i = 0; i < n_preferred_ciphers; i++) {
3190 const struct ssh2_ciphers *c = preferred_ciphers[i];
3191 if (!c) continue; /* warning flag */
3192 for (j = 0; j < c->nciphers; j++) {
3193 ssh2_pkt_addstring_str(c->list[j]->name);
3194 if (i < n_preferred_ciphers || j < c->nciphers - 1)
3195 ssh2_pkt_addstring_str(",");
3198 /* List client->server MAC algorithms. */
3199 ssh2_pkt_addstring_start();
3200 for (i = 0; i < nmacs; i++) {
3201 ssh2_pkt_addstring_str(maclist[i]->name);
3203 ssh2_pkt_addstring_str(",");
3205 /* List server->client MAC algorithms. */
3206 ssh2_pkt_addstring_start();
3207 for (i = 0; i < nmacs; i++) {
3208 ssh2_pkt_addstring_str(maclist[i]->name);
3210 ssh2_pkt_addstring_str(",");
3212 /* List client->server compression algorithms. */
3213 ssh2_pkt_addstring_start();
3214 for (i = 0; i < lenof(compressions) + 1; i++) {
3215 const struct ssh_compress *c =
3216 i == 0 ? preferred_comp : compressions[i - 1];
3217 ssh2_pkt_addstring_str(c->name);
3218 if (i < lenof(compressions))
3219 ssh2_pkt_addstring_str(",");
3221 /* List server->client compression algorithms. */
3222 ssh2_pkt_addstring_start();
3223 for (i = 0; i < lenof(compressions) + 1; i++) {
3224 const struct ssh_compress *c =
3225 i == 0 ? preferred_comp : compressions[i - 1];
3226 ssh2_pkt_addstring_str(c->name);
3227 if (i < lenof(compressions))
3228 ssh2_pkt_addstring_str(",");
3230 /* List client->server languages. Empty list. */
3231 ssh2_pkt_addstring_start();
3232 /* List server->client languages. Empty list. */
3233 ssh2_pkt_addstring_start();
3234 /* First KEX packet does _not_ follow, because we're not that brave. */
3235 ssh2_pkt_addbool(FALSE);
3237 ssh2_pkt_adduint32(0);
3239 exhash = exhashbase;
3240 sha_string(&exhash, pktout.data + 5, pktout.length - 5);
3246 sha_string(&exhash, pktin.data + 5, pktin.length - 5);
3249 * Now examine the other side's KEXINIT to see what we're up
3252 if (pktin.type != SSH2_MSG_KEXINIT) {
3253 bombout(("expected key exchange packet from server"));
3258 cscipher_tobe = NULL;
3259 sccipher_tobe = NULL;
3264 pktin.savedpos += 16; /* skip garbage cookie */
3265 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
3266 for (i = 0; i < lenof(kex_algs); i++) {
3267 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3272 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
3273 for (i = 0; i < lenof(hostkey_algs); i++) {
3274 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3275 hostkey = hostkey_algs[i];
3279 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
3281 for (i = 0; i < n_preferred_ciphers; i++) {
3282 const struct ssh2_ciphers *c = preferred_ciphers[i];
3286 for (j = 0; j < c->nciphers; j++) {
3287 if (in_commasep_string(c->list[j]->name, str, len)) {
3288 cscipher_tobe = c->list[j];
3293 if (cscipher_tobe) {
3295 askcipher(cscipher_tobe->name, 1);
3299 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
3301 for (i = 0; i < n_preferred_ciphers; i++) {
3302 const struct ssh2_ciphers *c = preferred_ciphers[i];
3306 for (j = 0; j < c->nciphers; j++) {
3307 if (in_commasep_string(c->list[j]->name, str, len)) {
3308 sccipher_tobe = c->list[j];
3313 if (sccipher_tobe) {
3315 askcipher(sccipher_tobe->name, 2);
3319 ssh2_pkt_getstring(&str, &len); /* client->server mac */
3320 for (i = 0; i < nmacs; i++) {
3321 if (in_commasep_string(maclist[i]->name, str, len)) {
3322 csmac_tobe = maclist[i];
3326 ssh2_pkt_getstring(&str, &len); /* server->client mac */
3327 for (i = 0; i < nmacs; i++) {
3328 if (in_commasep_string(maclist[i]->name, str, len)) {
3329 scmac_tobe = maclist[i];
3333 ssh2_pkt_getstring(&str, &len); /* client->server compression */
3334 for (i = 0; i < lenof(compressions) + 1; i++) {
3335 const struct ssh_compress *c =
3336 i == 0 ? preferred_comp : compressions[i - 1];
3337 if (in_commasep_string(c->name, str, len)) {
3342 ssh2_pkt_getstring(&str, &len); /* server->client compression */
3343 for (i = 0; i < lenof(compressions) + 1; i++) {
3344 const struct ssh_compress *c =
3345 i == 0 ? preferred_comp : compressions[i - 1];
3346 if (in_commasep_string(c->name, str, len)) {
3353 * Work out the number of bits of key we will need from the key
3354 * exchange. We start with the maximum key length of either
3360 csbits = cscipher_tobe->keylen;
3361 scbits = sccipher_tobe->keylen;
3362 nbits = (csbits > scbits ? csbits : scbits);
3364 /* The keys only have 160-bit entropy, since they're based on
3365 * a SHA-1 hash. So cap the key size at 160 bits. */
3370 * If we're doing Diffie-Hellman group exchange, start by
3371 * requesting a group.
3373 if (kex == &ssh_diffiehellman_gex) {
3374 logevent("Doing Diffie-Hellman group exchange");
3376 * Work out how big a DH group we will need to allow that
3379 pbits = 512 << ((nbits - 1) / 64);
3380 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
3381 ssh2_pkt_adduint32(pbits);
3385 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3386 bombout(("expected key exchange group packet from server"));
3389 p = ssh2_pkt_getmp();
3390 g = ssh2_pkt_getmp();
3391 dh_setup_group(p, g);
3392 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3393 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3396 kex_init_value = SSH2_MSG_KEXDH_INIT;
3397 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3400 logevent("Doing Diffie-Hellman key exchange");
3402 * Now generate and send e for Diffie-Hellman.
3404 e = dh_create_e(nbits * 2);
3405 ssh2_pkt_init(kex_init_value);
3410 if (pktin.type != kex_reply_value) {
3411 bombout(("expected key exchange reply packet from server"));
3414 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
3415 f = ssh2_pkt_getmp();
3416 ssh2_pkt_getstring(&sigdata, &siglen);
3420 sha_string(&exhash, hostkeydata, hostkeylen);
3421 if (kex == &ssh_diffiehellman_gex) {
3422 sha_uint32(&exhash, pbits);
3423 sha_mpint(&exhash, p);
3424 sha_mpint(&exhash, g);
3426 sha_mpint(&exhash, e);
3427 sha_mpint(&exhash, f);
3428 sha_mpint(&exhash, K);
3429 SHA_Final(&exhash, exchange_hash);
3434 debug(("Exchange hash is:\n"));
3435 dmemdump(exchange_hash, 20);
3438 hkey = hostkey->newkey(hostkeydata, hostkeylen);
3440 !hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
3441 bombout(("Server's host key did not match the signature supplied"));
3446 * Expect SSH2_MSG_NEWKEYS from server.
3449 if (pktin.type != SSH2_MSG_NEWKEYS) {
3450 bombout(("expected new-keys packet from server"));
3455 * Authenticate remote host: verify host key. (We've already
3456 * checked the signature of the exchange hash.)
3458 keystr = hostkey->fmtkey(hkey);
3459 fingerprint = hostkey->fingerprint(hkey);
3460 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
3461 keystr, fingerprint);
3462 if (first_kex) { /* don't bother logging this in rekeys */
3463 logevent("Host key fingerprint is:");
3464 logevent(fingerprint);
3468 hostkey->freekey(hkey);
3471 * Send SSH2_MSG_NEWKEYS.
3473 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
3477 * Create and initialise session keys.
3479 cscipher = cscipher_tobe;
3480 sccipher = sccipher_tobe;
3483 cscomp = cscomp_tobe;
3484 sccomp = sccomp_tobe;
3485 cscomp->compress_init();
3486 sccomp->decompress_init();
3488 * Set IVs after keys. Here we use the exchange hash from the
3489 * _first_ key exchange.
3492 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
3493 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
3494 cscipher->setcskey(keyspace);
3495 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
3496 sccipher->setsckey(keyspace);
3497 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
3498 cscipher->setcsiv(keyspace);
3499 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
3500 sccipher->setsciv(keyspace);
3501 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
3502 csmac->setcskey(keyspace);
3503 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
3504 scmac->setsckey(keyspace);
3507 * If this is the first key exchange phase, we must pass the
3508 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3509 * wants to see it but because it will need time to initialise
3510 * itself before it sees an actual packet. In subsequent key
3511 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3512 * it would only confuse the layer above.
3520 * Now we're encrypting. Begin returning 1 to the protocol main
3521 * function so that other things can run on top of the
3522 * transport. If we ever see a KEXINIT, we must go back to the
3525 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
3528 logevent("Server initiated key re-exchange");
3529 goto begin_key_exchange;
3535 * Add data to an SSH2 channel output buffer.
3537 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
3540 bufchain_add(&c->v.v2.outbuffer, buf, len);
3544 * Attempt to send data on an SSH2 channel.
3546 static int ssh2_try_send(struct ssh_channel *c)
3548 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
3551 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
3552 if ((unsigned)len > c->v.v2.remwindow)
3553 len = c->v.v2.remwindow;
3554 if ((unsigned)len > c->v.v2.remmaxpkt)
3555 len = c->v.v2.remmaxpkt;
3556 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
3557 ssh2_pkt_adduint32(c->remoteid);
3558 ssh2_pkt_addstring_start();
3559 ssh2_pkt_addstring_data(data, len);
3561 bufchain_consume(&c->v.v2.outbuffer, len);
3562 c->v.v2.remwindow -= len;
3566 * After having sent as much data as we can, return the amount
3569 return bufchain_size(&c->v.v2.outbuffer);
3573 * Potentially enlarge the window on an SSH2 channel.
3575 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
3577 if (newwin > c->v.v2.locwindow) {
3578 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3579 ssh2_pkt_adduint32(c->remoteid);
3580 ssh2_pkt_adduint32(newwin - c->v.v2.locwindow);
3582 c->v.v2.locwindow = newwin;
3587 * Handle the SSH2 userauth and connection layers.
3589 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
3592 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
3594 AUTH_KEYBOARD_INTERACTIVE
3598 AUTH_TYPE_PUBLICKEY,
3599 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
3600 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
3602 AUTH_TYPE_KEYBOARD_INTERACTIVE,
3603 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
3605 static int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
3606 static int tried_pubkey_config, tried_agent, tried_keyb_inter;
3607 static int kbd_inter_running;
3608 static int we_are_in;
3609 static int num_prompts, echo;
3610 static char username[100];
3611 static char pwprompt[200];
3612 static char password[100];
3617 * Request userauth protocol, and await a response to it.
3619 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
3620 ssh2_pkt_addstring("ssh-userauth");
3622 crWaitUntilV(ispkt);
3623 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
3624 bombout(("Server refused user authentication protocol"));
3629 * We repeat this whole loop, including the username prompt,
3630 * until we manage a successful authentication. If the user
3631 * types the wrong _password_, they are sent back to the
3632 * beginning to try another username. (If they specify a
3633 * username in the config, they are never asked, even if they
3634 * do give a wrong password.)
3636 * I think this best serves the needs of
3638 * - the people who have no configuration, no keys, and just
3639 * want to try repeated (username,password) pairs until they
3640 * type both correctly
3642 * - people who have keys and configuration but occasionally
3643 * need to fall back to passwords
3645 * - people with a key held in Pageant, who might not have
3646 * logged in to a particular machine before; so they want to
3647 * type a username, and then _either_ their key will be
3648 * accepted, _or_ they will type a password. If they mistype
3649 * the username they will want to be able to get back and
3660 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
3662 if (!ssh_get_line("login as: ",
3663 username, sizeof(username), FALSE)) {
3665 * get_line failed to get a username.
3668 logevent("No username provided. Abandoning session.");
3669 ssh_state = SSH_STATE_CLOSED;
3673 c_write_str("login as: ");
3676 crWaitUntilV(!ispkt);
3678 switch (c = *in++) {
3687 c_write_str("\b \b");
3694 c_write_str("\b \b");
3704 if (((c >= ' ' && c <= '~') ||
3705 ((unsigned char) c >= 160))
3706 && pos < sizeof(username)-1) {
3707 username[pos++] = c;
3714 c_write_str("\r\n");
3715 username[strcspn(username, "\n\r")] = '\0';
3718 strncpy(username, cfg.username, 99);
3719 username[99] = '\0';
3720 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3721 sprintf(stuff, "Using username \"%s\".\r\n", username);
3727 * Send an authentication request using method "none": (a)
3728 * just in case it succeeds, and (b) so that we know what
3729 * authentication methods we can usefully try next.
3731 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3732 ssh2_pkt_addstring(username);
3733 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3734 ssh2_pkt_addstring("none"); /* method */
3736 type = AUTH_TYPE_NONE;
3740 tried_pubkey_config = FALSE;
3741 tried_agent = FALSE;
3742 tried_keyb_inter = FALSE;
3743 kbd_inter_running = FALSE;
3747 * Wait for the result of the last authentication request.
3750 crWaitUntilV(ispkt);
3751 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
3755 * Don't show the banner if we're operating in
3756 * non-verbose non-interactive mode. (It's probably
3757 * a script, which means nobody will read the
3758 * banner _anyway_, and moreover the printing of
3759 * the banner will screw up processing on the
3760 * output of (say) plink.)
3762 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
3763 ssh2_pkt_getstring(&banner, &size);
3765 c_write_untrusted(banner, size);
3767 crWaitUntilV(ispkt);
3769 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
3770 logevent("Access granted");
3775 if (kbd_inter_running &&
3776 pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
3778 * This is a further prompt in keyboard-interactive
3779 * authentication. Do nothing.
3781 } else if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
3782 bombout(("Strange packet received during authentication: type %d",
3790 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3791 * we can look at the string in it and know what we can
3792 * helpfully try next.
3794 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
3797 ssh2_pkt_getstring(&methods, &methlen);
3798 kbd_inter_running = FALSE;
3799 if (!ssh2_pkt_getbool()) {
3801 * We have received an unequivocal Access
3802 * Denied. This can translate to a variety of
3805 * - if we'd just tried "none" authentication,
3806 * it's not worth printing anything at all
3808 * - if we'd just tried a public key _offer_,
3809 * the message should be "Server refused our
3810 * key" (or no message at all if the key
3811 * came from Pageant)
3813 * - if we'd just tried anything else, the
3814 * message really should be "Access denied".
3816 * Additionally, if we'd just tried password
3817 * authentication, we should break out of this
3818 * whole loop so as to go back to the username
3821 if (type == AUTH_TYPE_NONE) {
3823 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
3824 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
3825 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
3826 c_write_str("Server refused our key\r\n");
3827 logevent("Server refused public key");
3828 } else if (type == AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
3829 /* server declined keyboard-interactive; ignore */
3831 c_write_str("Access denied\r\n");
3832 logevent("Access denied");
3833 if (type == AUTH_TYPE_PASSWORD) {
3839 c_write_str("Further authentication required\r\n");
3840 logevent("Further authentication required");
3844 in_commasep_string("publickey", methods, methlen);
3846 in_commasep_string("password", methods, methlen);
3848 in_commasep_string("keyboard-interactive", methods, methlen);
3853 if (!method && can_pubkey && agent_exists() && !tried_agent) {
3855 * Attempt public-key authentication using Pageant.
3857 static unsigned char request[5], *response, *p;
3858 static int responselen;
3859 static int i, nkeys;
3860 static int authed = FALSE;
3865 logevent("Pageant is running. Requesting keys.");
3867 /* Request the keys held by the agent. */
3868 PUT_32BIT(request, 1);
3869 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
3870 agent_query(request, 5, &r, &responselen);
3871 response = (unsigned char *) r;
3872 if (response && responselen >= 5 &&
3873 response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
3875 nkeys = GET_32BIT(p);
3879 sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
3882 for (i = 0; i < nkeys; i++) {
3883 static char *pkblob, *alg, *commentp;
3884 static int pklen, alglen, commentlen;
3885 static int siglen, retlen, len;
3886 static char *q, *agentreq, *ret;
3891 sprintf(buf, "Trying Pageant key #%d", i);
3894 pklen = GET_32BIT(p);
3898 alglen = GET_32BIT(pkblob);
3900 commentlen = GET_32BIT(p);
3904 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3905 ssh2_pkt_addstring(username);
3906 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3907 ssh2_pkt_addstring("publickey"); /* method */
3908 ssh2_pkt_addbool(FALSE); /* no signature included */
3909 ssh2_pkt_addstring_start();
3910 ssh2_pkt_addstring_data(alg, alglen);
3911 ssh2_pkt_addstring_start();
3912 ssh2_pkt_addstring_data(pkblob, pklen);
3915 crWaitUntilV(ispkt);
3916 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3917 logevent("Key refused");
3921 if (flags & FLAG_VERBOSE) {
3923 ("Authenticating with public key \"");
3924 c_write(commentp, commentlen);
3925 c_write_str("\" from agent\r\n");
3929 * Server is willing to accept the key.
3930 * Construct a SIGN_REQUEST.
3932 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3933 ssh2_pkt_addstring(username);
3934 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3935 ssh2_pkt_addstring("publickey"); /* method */
3936 ssh2_pkt_addbool(TRUE);
3937 ssh2_pkt_addstring_start();
3938 ssh2_pkt_addstring_data(alg, alglen);
3939 ssh2_pkt_addstring_start();
3940 ssh2_pkt_addstring_data(pkblob, pklen);
3942 siglen = pktout.length - 5 + 4 + 20;
3943 len = 1; /* message type */
3944 len += 4 + pklen; /* key blob */
3945 len += 4 + siglen; /* data to sign */
3946 len += 4; /* flags */
3947 agentreq = smalloc(4 + len);
3948 PUT_32BIT(agentreq, len);
3950 *q++ = SSH2_AGENTC_SIGN_REQUEST;
3951 PUT_32BIT(q, pklen);
3953 memcpy(q, pkblob, pklen);
3955 PUT_32BIT(q, siglen);
3957 /* Now the data to be signed... */
3960 memcpy(q, ssh2_session_id, 20);
3962 memcpy(q, pktout.data + 5, pktout.length - 5);
3963 q += pktout.length - 5;
3964 /* And finally the (zero) flags word. */
3966 agent_query(agentreq, len + 4, &vret, &retlen);
3970 if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
3971 logevent("Sending Pageant's response");
3972 ssh2_pkt_addstring_start();
3973 ssh2_pkt_addstring_data(ret + 9,
3981 ("Pageant failed to answer challenge");
3991 if (!method && can_pubkey && *cfg.keyfile
3992 && !tried_pubkey_config) {
3993 unsigned char *pub_blob;
3994 char *algorithm, *comment;
3997 tried_pubkey_config = TRUE;
4000 * Try the public key supplied in the configuration.
4002 * First, offer the public blob to see if the server is
4003 * willing to accept it.
4005 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4008 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4009 ssh2_pkt_addstring(username);
4010 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4011 ssh2_pkt_addstring("publickey"); /* method */
4012 ssh2_pkt_addbool(FALSE); /* no signature included */
4013 ssh2_pkt_addstring(algorithm);
4014 ssh2_pkt_addstring_start();
4015 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
4017 logevent("Offered public key"); /* FIXME */
4019 crWaitUntilV(ispkt);
4020 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4022 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4023 continue; /* key refused; give up on it */
4026 logevent("Offer of public key accepted");
4028 * Actually attempt a serious authentication using
4031 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4033 "Passphrase for key \"%.100s\": ",
4039 c_write_str("Authenticating with public key \"");
4040 c_write_str(comment);
4041 c_write_str("\"\r\n");
4042 method = AUTH_PUBLICKEY_FILE;
4046 if (!method && can_keyb_inter && !tried_keyb_inter) {
4047 method = AUTH_KEYBOARD_INTERACTIVE;
4048 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4049 tried_keyb_inter = TRUE;
4051 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4052 ssh2_pkt_addstring(username);
4053 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4054 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4055 ssh2_pkt_addstring(""); /* lang */
4056 ssh2_pkt_addstring("");
4059 crWaitUntilV(ispkt);
4060 if (pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4061 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4063 logevent("Keyboard-interactive authentication refused");
4064 type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4068 kbd_inter_running = TRUE;
4071 if (kbd_inter_running) {
4072 method = AUTH_KEYBOARD_INTERACTIVE;
4073 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4074 tried_keyb_inter = TRUE;
4076 /* We've got packet with that "interactive" info
4077 dump banners, and set its prompt as ours */
4079 char *name, *inst, *lang, *prompt;
4080 int name_len, inst_len, lang_len, prompt_len;
4081 ssh2_pkt_getstring(&name, &name_len);
4082 ssh2_pkt_getstring(&inst, &inst_len);
4083 ssh2_pkt_getstring(&lang, &lang_len);
4085 c_write_untrusted(name, name_len);
4087 c_write_untrusted(inst, inst_len);
4088 num_prompts = ssh2_pkt_getuint32();
4090 ssh2_pkt_getstring(&prompt, &prompt_len);
4091 strncpy(pwprompt, prompt, sizeof(pwprompt));
4094 echo = ssh2_pkt_getbool();
4098 if (!method && can_passwd) {
4099 method = AUTH_PASSWORD;
4100 sprintf(pwprompt, "%.90s@%.90s's password: ", username,
4107 if (!ssh_get_line(pwprompt, password,
4108 sizeof(password), TRUE)) {
4110 * get_line failed to get a password (for
4111 * example because one was supplied on the
4112 * command line which has already failed to
4115 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4116 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4118 ("No more passwords available to try");
4119 ssh2_pkt_addstring("en"); /* language tag */
4121 connection_fatal("Unable to authenticate");
4122 ssh_state = SSH_STATE_CLOSED;
4129 c_write_untrusted(pwprompt, strlen(pwprompt));
4134 crWaitUntilV(!ispkt);
4136 switch (c = *in++) {
4157 if (pos < sizeof(password)-1)
4158 password[pos++] = c;
4162 c_write_str("\r\n");
4166 if (method == AUTH_PUBLICKEY_FILE) {
4168 * We have our passphrase. Now try the actual authentication.
4170 struct ssh2_userkey *key;
4172 key = ssh2_load_userkey(cfg.keyfile, password);
4173 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4174 if (key == SSH2_WRONG_PASSPHRASE) {
4175 c_write_str("Wrong passphrase\r\n");
4176 tried_pubkey_config = FALSE;
4178 c_write_str("Unable to load private key\r\n");
4179 tried_pubkey_config = TRUE;
4181 /* Send a spurious AUTH_NONE to return to the top. */
4182 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4183 ssh2_pkt_addstring(username);
4184 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4185 ssh2_pkt_addstring("none"); /* method */
4187 type = AUTH_TYPE_NONE;
4189 unsigned char *blob, *sigdata;
4190 int blob_len, sigdata_len;
4193 * We have loaded the private key and the server
4194 * has announced that it's willing to accept it.
4195 * Hallelujah. Generate a signature and send it.
4197 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4198 ssh2_pkt_addstring(username);
4199 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4200 ssh2_pkt_addstring("publickey"); /* method */
4201 ssh2_pkt_addbool(TRUE);
4202 ssh2_pkt_addstring(key->alg->name);
4203 blob = key->alg->public_blob(key->data, &blob_len);
4204 ssh2_pkt_addstring_start();
4205 ssh2_pkt_addstring_data(blob, blob_len);
4209 * The data to be signed is:
4213 * followed by everything so far placed in the
4216 sigdata_len = pktout.length - 5 + 4 + 20;
4217 sigdata = smalloc(sigdata_len);
4218 PUT_32BIT(sigdata, 20);
4219 memcpy(sigdata + 4, ssh2_session_id, 20);
4220 memcpy(sigdata + 24, pktout.data + 5,
4223 key->alg->sign(key->data, sigdata, sigdata_len,
4225 ssh2_pkt_addstring_start();
4226 ssh2_pkt_addstring_data(blob, blob_len);
4231 type = AUTH_TYPE_PUBLICKEY;
4233 } else if (method == AUTH_PASSWORD) {
4235 * We send the password packet lumped tightly together with
4236 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4237 * string long enough to make the total length of the two
4238 * packets constant. This should ensure that a passive
4239 * listener doing traffic analyis can't work out the length
4242 * For this to work, we need an assumption about the
4243 * maximum length of the password packet. I think 256 is
4244 * pretty conservative. Anyone using a password longer than
4245 * that probably doesn't have much to worry about from
4246 * people who find out how long their password is!
4248 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4249 ssh2_pkt_addstring(username);
4250 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4251 ssh2_pkt_addstring("password");
4252 ssh2_pkt_addbool(FALSE);
4253 ssh2_pkt_addstring(password);
4256 * We'll include a string that's an exact multiple of the
4257 * cipher block size. If the cipher is NULL for some
4258 * reason, we don't do this trick at all because we gain
4264 stringlen = (256 - deferred_len);
4265 stringlen += cscipher->blksize - 1;
4266 stringlen -= (stringlen % cscipher->blksize);
4269 * Temporarily disable actual compression,
4270 * so we can guarantee to get this string
4271 * exactly the length we want it. The
4272 * compression-disabling routine should
4273 * return an integer indicating how many
4274 * bytes we should adjust our string length
4277 stringlen -= cscomp->disable_compression();
4279 ssh2_pkt_init(SSH2_MSG_IGNORE);
4280 ssh2_pkt_addstring_start();
4281 for (i = 0; i < stringlen; i++) {
4282 char c = (char) random_byte();
4283 ssh2_pkt_addstring_data(&c, 1);
4287 ssh_pkt_defersend();
4288 logevent("Sent password");
4289 type = AUTH_TYPE_PASSWORD;
4290 } else if (method == AUTH_KEYBOARD_INTERACTIVE) {
4291 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
4292 ssh2_pkt_adduint32(num_prompts);
4293 ssh2_pkt_addstring(password);
4294 memset(password, 0, sizeof(password));
4296 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4299 ("No supported authentication methods left to try!\r\n");
4301 ("No supported authentications offered. Disconnecting");
4302 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4303 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4305 ("No supported authentication methods available");
4306 ssh2_pkt_addstring("en"); /* language tag */
4308 ssh_state = SSH_STATE_CLOSED;
4312 } while (!we_are_in);
4315 * Now we're authenticated for the connection protocol. The
4316 * connection protocol will automatically have started at this
4317 * point; there's no need to send SERVICE_REQUEST.
4321 * So now create a channel with a session in it.
4323 ssh_channels = newtree234(ssh_channelcmp);
4324 mainchan = smalloc(sizeof(struct ssh_channel));
4325 mainchan->localid = alloc_channel_id();
4326 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
4327 ssh2_pkt_addstring("session");
4328 ssh2_pkt_adduint32(mainchan->localid);
4329 mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
4330 ssh2_pkt_adduint32(mainchan->v.v2.locwindow); /* our window size */
4331 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
4333 crWaitUntilV(ispkt);
4334 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4335 bombout(("Server refused to open a session"));
4337 /* FIXME: error data comes back in FAILURE packet */
4339 if (ssh2_pkt_getuint32() != mainchan->localid) {
4340 bombout(("Server's channel confirmation cited wrong channel"));
4343 mainchan->remoteid = ssh2_pkt_getuint32();
4344 mainchan->type = CHAN_MAINSESSION;
4345 mainchan->closes = 0;
4346 mainchan->v.v2.remwindow = ssh2_pkt_getuint32();
4347 mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4348 bufchain_init(&mainchan->v.v2.outbuffer);
4349 add234(ssh_channels, mainchan);
4350 logevent("Opened channel for session");
4353 * Potentially enable X11 forwarding.
4355 if (cfg.x11_forward) {
4356 char proto[20], data[64];
4357 logevent("Requesting X11 forwarding");
4358 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
4359 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4360 ssh2_pkt_adduint32(mainchan->remoteid);
4361 ssh2_pkt_addstring("x11-req");
4362 ssh2_pkt_addbool(1); /* want reply */
4363 ssh2_pkt_addbool(0); /* many connections */
4364 ssh2_pkt_addstring(proto);
4365 ssh2_pkt_addstring(data);
4366 ssh2_pkt_adduint32(0); /* screen number */
4370 crWaitUntilV(ispkt);
4371 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4372 unsigned i = ssh2_pkt_getuint32();
4373 struct ssh_channel *c;
4374 c = find234(ssh_channels, &i, ssh_channelfind);
4376 continue; /* nonexistent channel */
4377 c->v.v2.remwindow += ssh2_pkt_getuint32();
4379 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4381 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4382 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4383 bombout(("Server got confused by X11 forwarding request"));
4386 logevent("X11 forwarding refused");
4388 logevent("X11 forwarding enabled");
4389 ssh_X11_fwd_enabled = TRUE;
4394 * Enable port forwardings.
4397 static char *e; /* preserve across crReturn */
4401 char sports[256], dports[256], host[256];
4404 ssh_rportfwds = newtree234(ssh_rportcmp_ssh2);
4405 /* Add port forwardings. */
4410 while (*e && *e != '\t')
4416 while (*e && *e != ':')
4426 dport = atoi(dports);
4427 sport = atoi(sports);
4428 if (sport && dport) {
4430 pfd_addforward(host, dport, sport);
4431 sprintf(buf, "Local port %d forwarding to %s:%d",
4432 sport, host, dport);
4435 struct ssh_rportfwd *pf;
4436 pf = smalloc(sizeof(*pf));
4437 strcpy(pf->dhost, host);
4440 if (add234(ssh_rportfwds, pf) != pf) {
4442 "Duplicate remote port forwarding to %s:%d",
4447 sprintf(buf, "Requesting remote port %d (forwarded to %s:%d)",
4448 sport, host, dport);
4450 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4451 ssh2_pkt_addstring("tcpip-forward");
4452 ssh2_pkt_addbool(1);/* want reply */
4453 ssh2_pkt_addstring("127.0.0.1");
4454 ssh2_pkt_adduint32(sport);
4458 crWaitUntilV(ispkt);
4459 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4460 unsigned i = ssh2_pkt_getuint32();
4461 struct ssh_channel *c;
4462 c = find234(ssh_channels, &i, ssh_channelfind);
4464 continue;/* nonexistent channel */
4465 c->v.v2.remwindow += ssh2_pkt_getuint32();
4467 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4469 if (pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
4470 if (pktin.type != SSH2_MSG_REQUEST_FAILURE) {
4471 bombout(("Server got confused by port forwarding request"));
4474 logevent("Server refused this port forwarding");
4476 logevent("Remote port forwarding enabled");
4485 * Potentially enable agent forwarding.
4487 if (cfg.agentfwd && agent_exists()) {
4488 logevent("Requesting OpenSSH-style agent forwarding");
4489 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4490 ssh2_pkt_adduint32(mainchan->remoteid);
4491 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4492 ssh2_pkt_addbool(1); /* want reply */
4496 crWaitUntilV(ispkt);
4497 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4498 unsigned i = ssh2_pkt_getuint32();
4499 struct ssh_channel *c;
4500 c = find234(ssh_channels, &i, ssh_channelfind);
4502 continue; /* nonexistent channel */
4503 c->v.v2.remwindow += ssh2_pkt_getuint32();
4505 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4507 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4508 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4510 ("Server got confused by agent forwarding request"));
4513 logevent("Agent forwarding refused");
4515 logevent("Agent forwarding enabled");
4516 ssh_agentfwd_enabled = TRUE;
4521 * Now allocate a pty for the session.
4524 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4525 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
4526 ssh2_pkt_addstring("pty-req");
4527 ssh2_pkt_addbool(1); /* want reply */
4528 ssh2_pkt_addstring(cfg.termtype);
4529 ssh2_pkt_adduint32(cols);
4530 ssh2_pkt_adduint32(rows);
4531 ssh2_pkt_adduint32(0); /* pixel width */
4532 ssh2_pkt_adduint32(0); /* pixel height */
4533 ssh2_pkt_addstring_start();
4534 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4536 ssh_state = SSH_STATE_INTERMED;
4539 crWaitUntilV(ispkt);
4540 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4541 unsigned i = ssh2_pkt_getuint32();
4542 struct ssh_channel *c;
4543 c = find234(ssh_channels, &i, ssh_channelfind);
4545 continue; /* nonexistent channel */
4546 c->v.v2.remwindow += ssh2_pkt_getuint32();
4548 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4550 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4551 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4552 bombout(("Server got confused by pty request"));
4555 c_write_str("Server refused to allocate pty\r\n");
4556 ssh_editing = ssh_echoing = 1;
4558 logevent("Allocated pty");
4561 ssh_editing = ssh_echoing = 1;
4565 * Start a shell or a remote command. We may have to attempt
4566 * this twice if the config data has provided a second choice
4573 if (ssh_fallback_cmd) {
4574 subsys = cfg.ssh_subsys2;
4575 cmd = cfg.remote_cmd_ptr2;
4577 subsys = cfg.ssh_subsys;
4578 cmd = cfg.remote_cmd_ptr;
4581 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4582 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
4584 ssh2_pkt_addstring("subsystem");
4585 ssh2_pkt_addbool(1); /* want reply */
4586 ssh2_pkt_addstring(cmd);
4588 ssh2_pkt_addstring("exec");
4589 ssh2_pkt_addbool(1); /* want reply */
4590 ssh2_pkt_addstring(cmd);
4592 ssh2_pkt_addstring("shell");
4593 ssh2_pkt_addbool(1); /* want reply */
4597 crWaitUntilV(ispkt);
4598 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4599 unsigned i = ssh2_pkt_getuint32();
4600 struct ssh_channel *c;
4601 c = find234(ssh_channels, &i, ssh_channelfind);
4603 continue; /* nonexistent channel */
4604 c->v.v2.remwindow += ssh2_pkt_getuint32();
4606 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4607 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4608 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4609 bombout(("Server got confused by shell/command request"));
4613 * We failed to start the command. If this is the
4614 * fallback command, we really are finished; if it's
4615 * not, and if the fallback command exists, try falling
4616 * back to it before complaining.
4618 if (!ssh_fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
4619 logevent("Primary command failed; attempting fallback");
4620 ssh_fallback_cmd = TRUE;
4623 bombout(("Server refused to start a shell/command"));
4626 logevent("Started a shell/command");
4631 ssh_state = SSH_STATE_SESSION;
4635 ssh_special(TS_EOF);
4640 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
4643 static int try_send;
4647 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
4648 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
4651 unsigned i = ssh2_pkt_getuint32();
4652 struct ssh_channel *c;
4653 c = find234(ssh_channels, &i, ssh_channelfind);
4655 continue; /* nonexistent channel */
4656 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
4657 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
4658 continue; /* extended but not stderr */
4659 ssh2_pkt_getstring(&data, &length);
4662 c->v.v2.locwindow -= length;
4664 case CHAN_MAINSESSION:
4666 from_backend(pktin.type ==
4667 SSH2_MSG_CHANNEL_EXTENDED_DATA,
4671 bufsize = x11_send(c->u.x11.s, data, length);
4674 bufsize = pfd_send(c->u.pfd.s, data, length);
4677 while (length > 0) {
4678 if (c->u.a.lensofar < 4) {
4679 int l = min(4 - c->u.a.lensofar, length);
4680 memcpy(c->u.a.msglen + c->u.a.lensofar,
4684 c->u.a.lensofar += l;
4686 if (c->u.a.lensofar == 4) {
4688 4 + GET_32BIT(c->u.a.msglen);
4689 c->u.a.message = smalloc(c->u.a.totallen);
4690 memcpy(c->u.a.message, c->u.a.msglen, 4);
4692 if (c->u.a.lensofar >= 4 && length > 0) {
4694 min(c->u.a.totallen - c->u.a.lensofar,
4696 memcpy(c->u.a.message + c->u.a.lensofar,
4700 c->u.a.lensofar += l;
4702 if (c->u.a.lensofar == c->u.a.totallen) {
4703 void *reply, *sentreply;
4705 agent_query(c->u.a.message,
4706 c->u.a.totallen, &reply,
4711 /* Fake SSH_AGENT_FAILURE. */
4712 sentreply = "\0\0\0\1\5";
4715 ssh2_add_channel_data(c, sentreply,
4720 sfree(c->u.a.message);
4721 c->u.a.lensofar = 0;
4728 * If we are not buffering too much data,
4729 * enlarge the window again at the remote side.
4731 if (bufsize < OUR_V2_WINSIZE)
4732 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
4734 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
4735 ssh_state = SSH_STATE_CLOSED;
4736 logevent("Received disconnect message");
4738 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
4739 continue; /* exit status et al; ignore (FIXME?) */
4740 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
4741 unsigned i = ssh2_pkt_getuint32();
4742 struct ssh_channel *c;
4744 c = find234(ssh_channels, &i, ssh_channelfind);
4746 continue; /* nonexistent channel */
4748 if (c->type == CHAN_X11) {
4750 * Remote EOF on an X11 channel means we should
4751 * wrap up and close the channel ourselves.
4753 x11_close(c->u.x11.s);
4755 } else if (c->type == CHAN_AGENT) {
4757 } else if (c->type == CHAN_SOCKDATA) {
4758 pfd_close(c->u.pfd.s);
4761 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
4762 unsigned i = ssh2_pkt_getuint32();
4763 struct ssh_channel *c;
4765 c = find234(ssh_channels, &i, ssh_channelfind);
4767 continue; /* nonexistent channel */
4768 /* Do pre-close processing on the channel. */
4770 case CHAN_MAINSESSION:
4771 break; /* nothing to see here, move along */
4773 if (c->u.x11.s != NULL)
4774 x11_close(c->u.x11.s);
4781 if (c->u.pfd.s != NULL)
4782 pfd_close(c->u.pfd.s);
4786 if (c->closes == 0) {
4787 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4788 ssh2_pkt_adduint32(c->remoteid);
4791 del234(ssh_channels, c);
4792 bufchain_clear(&c->v.v2.outbuffer);
4796 * See if that was the last channel left open.
4798 if (count234(ssh_channels) == 0) {
4799 logevent("All channels closed. Disconnecting");
4800 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4801 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4802 ssh2_pkt_addstring("All open channels closed");
4803 ssh2_pkt_addstring("en"); /* language tag */
4805 ssh_state = SSH_STATE_CLOSED;
4808 continue; /* remote sends close; ignore (FIXME) */
4809 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4810 unsigned i = ssh2_pkt_getuint32();
4811 struct ssh_channel *c;
4812 c = find234(ssh_channels, &i, ssh_channelfind);
4814 continue; /* nonexistent channel */
4815 c->v.v2.remwindow += ssh2_pkt_getuint32();
4817 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4818 unsigned i = ssh2_pkt_getuint32();
4819 struct ssh_channel *c;
4820 c = find234(ssh_channels, &i, ssh_channelfind);
4822 continue; /* nonexistent channel */
4823 if (c->type != CHAN_SOCKDATA_DORMANT)
4824 continue; /* dunno why they're confirming this */
4825 c->remoteid = ssh2_pkt_getuint32();
4826 c->type = CHAN_SOCKDATA;
4828 c->v.v2.remwindow = ssh2_pkt_getuint32();
4829 c->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4830 bufchain_init(&c->v.v2.outbuffer);
4831 pfd_confirm(c->u.pfd.s);
4832 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
4833 unsigned i = ssh2_pkt_getuint32();
4834 struct ssh_channel *c;
4835 c = find234(ssh_channels, &i, ssh_channelfind);
4837 continue; /* nonexistent channel */
4838 if (c->type != CHAN_SOCKDATA_DORMANT)
4839 continue; /* dunno why they're failing this */
4841 logevent("Forwarded connection refused by server");
4843 pfd_close(c->u.pfd.s);
4845 del234(ssh_channels, c);
4847 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
4851 struct ssh_channel *c;
4852 unsigned remid, winsize, pktsize;
4853 ssh2_pkt_getstring(&type, &typelen);
4854 c = smalloc(sizeof(struct ssh_channel));
4856 remid = ssh2_pkt_getuint32();
4857 winsize = ssh2_pkt_getuint32();
4858 pktsize = ssh2_pkt_getuint32();
4860 if (typelen == 3 && !memcmp(type, "x11", 3)) {
4861 if (!ssh_X11_fwd_enabled)
4862 error = "X11 forwarding is not enabled";
4863 else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
4865 error = "Unable to open an X11 connection";
4869 } else if (typelen == 15 &&
4870 !memcmp(type, "forwarded-tcpip", 15)) {
4871 struct ssh_rportfwd pf, *realpf;
4874 ssh2_pkt_getstring(&dummy, &dummylen);/* skip address */
4875 pf.sport = ssh2_pkt_getuint32();
4876 realpf = find234(ssh_rportfwds, &pf, NULL);
4877 if (realpf == NULL) {
4878 error = "Remote port is not recognised";
4880 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
4883 sprintf(buf, "Received remote port open request for %s:%d",
4884 realpf->dhost, realpf->dport);
4887 sprintf(buf, "Port open failed: %s", e);
4889 error = "Port open failed";
4891 logevent("Forwarded port opened successfully");
4892 c->type = CHAN_SOCKDATA;
4895 } else if (typelen == 22 &&
4896 !memcmp(type, "auth-agent@openssh.com", 3)) {
4897 if (!ssh_agentfwd_enabled)
4898 error = "Agent forwarding is not enabled";
4900 c->type = CHAN_AGENT; /* identify channel type */
4901 c->u.a.lensofar = 0;
4904 error = "Unsupported channel type requested";
4907 c->remoteid = remid;
4909 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
4910 ssh2_pkt_adduint32(c->remoteid);
4911 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
4912 ssh2_pkt_addstring(error);
4913 ssh2_pkt_addstring("en"); /* language tag */
4917 c->localid = alloc_channel_id();
4919 c->v.v2.locwindow = OUR_V2_WINSIZE;
4920 c->v.v2.remwindow = winsize;
4921 c->v.v2.remmaxpkt = pktsize;
4922 bufchain_init(&c->v.v2.outbuffer);
4923 add234(ssh_channels, c);
4924 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
4925 ssh2_pkt_adduint32(c->remoteid);
4926 ssh2_pkt_adduint32(c->localid);
4927 ssh2_pkt_adduint32(c->v.v2.locwindow);
4928 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
4932 bombout(("Strange packet received: type %d", pktin.type));
4937 * We have spare data. Add it to the channel buffer.
4939 ssh2_add_channel_data(mainchan, in, inlen);
4944 struct ssh_channel *c;
4946 * Try to send data on all channels if we can.
4948 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
4949 int bufsize = ssh2_try_send(c);
4952 case CHAN_MAINSESSION:
4953 /* stdin need not receive an unthrottle
4954 * notification since it will be polled */
4957 x11_unthrottle(c->u.x11.s);
4960 /* agent sockets are request/response and need no
4961 * buffer management */
4964 pfd_unthrottle(c->u.pfd.s);
4976 * Handle the top-level SSH2 protocol.
4978 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
4980 if (do_ssh2_transport(in, inlen, ispkt) == 0)
4982 do_ssh2_authconn(in, inlen, ispkt);
4986 * Called to set up the connection.
4988 * Returns an error message, or NULL on success.
4990 static char *ssh_init(char *host, int port, char **realhost)
4995 if (crypto_startup() == 0)
4996 return "Microsoft high encryption pack not installed!";
5002 ssh1_throttle_count = 0;
5003 ssh_overall_bufsize = 0;
5004 ssh_fallback_cmd = 0;
5006 p = connect_to_host(host, port, realhost);
5014 * Called to send data down the Telnet connection.
5016 static int ssh_send(char *buf, int len)
5018 if (s == NULL || ssh_protocol == NULL)
5021 ssh_protocol(buf, len, 0);
5023 return ssh_sendbuffer();
5027 * Called to query the current amount of buffered stdin data.
5029 static int ssh_sendbuffer(void)
5033 if (s == NULL || ssh_protocol == NULL)
5037 * If the SSH socket itself has backed up, add the total backup
5038 * size on that to any individual buffer on the stdin channel.
5041 if (ssh_throttled_all)
5042 override_value = ssh_overall_bufsize;
5044 if (ssh_version == 1) {
5045 return override_value;
5046 } else if (ssh_version == 2) {
5047 if (!mainchan || mainchan->closes > 0)
5048 return override_value;
5050 return override_value + bufchain_size(&mainchan->v.v2.outbuffer);
5057 * Called to set the size of the window from SSH's POV.
5059 static void ssh_size(void)
5061 switch (ssh_state) {
5062 case SSH_STATE_BEFORE_SIZE:
5063 case SSH_STATE_PREPACKET:
5064 case SSH_STATE_CLOSED:
5065 break; /* do nothing */
5066 case SSH_STATE_INTERMED:
5067 size_needed = TRUE; /* buffer for later */
5069 case SSH_STATE_SESSION:
5071 if (ssh_version == 1) {
5072 send_packet(SSH1_CMSG_WINDOW_SIZE,
5073 PKT_INT, rows, PKT_INT, cols,
5074 PKT_INT, 0, PKT_INT, 0, PKT_END);
5076 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5077 ssh2_pkt_adduint32(mainchan->remoteid);
5078 ssh2_pkt_addstring("window-change");
5079 ssh2_pkt_addbool(0);
5080 ssh2_pkt_adduint32(cols);
5081 ssh2_pkt_adduint32(rows);
5082 ssh2_pkt_adduint32(0);
5083 ssh2_pkt_adduint32(0);
5092 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5093 * can send an EOF and collect resulting output (e.g. `plink
5096 static void ssh_special(Telnet_Special code)
5098 if (code == TS_EOF) {
5099 if (ssh_state != SSH_STATE_SESSION) {
5101 * Buffer the EOF in case we are pre-SESSION, so we can
5102 * send it as soon as we reach SESSION.
5108 if (ssh_version == 1) {
5109 send_packet(SSH1_CMSG_EOF, PKT_END);
5111 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
5112 ssh2_pkt_adduint32(mainchan->remoteid);
5115 logevent("Sent EOF message");
5116 } else if (code == TS_PING) {
5117 if (ssh_state == SSH_STATE_CLOSED
5118 || ssh_state == SSH_STATE_PREPACKET) return;
5119 if (ssh_version == 1) {
5120 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
5122 ssh2_pkt_init(SSH2_MSG_IGNORE);
5123 ssh2_pkt_addstring_start();
5131 void *new_sock_channel(Socket s)
5133 struct ssh_channel *c;
5134 c = smalloc(sizeof(struct ssh_channel));
5137 c->remoteid = -1; /* to be set when open confirmed */
5138 c->localid = alloc_channel_id();
5140 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
5142 add234(ssh_channels, c);
5148 * This is called when stdout/stderr (the entity to which
5149 * from_backend sends data) manages to clear some backlog.
5151 void ssh_unthrottle(int bufsize)
5153 if (ssh_version == 1) {
5154 if (ssh1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
5155 ssh1_stdout_throttling = 0;
5159 if (mainchan && mainchan->closes == 0)
5160 ssh2_set_window(mainchan, OUR_V2_WINSIZE - bufsize);
5164 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
5166 struct ssh_channel *c = (struct ssh_channel *)channel;
5169 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
5172 if (ssh_version == 1) {
5173 send_packet(SSH1_MSG_PORT_OPEN,
5174 PKT_INT, c->localid,
5177 //PKT_STR, <org:orgport>,
5180 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
5181 ssh2_pkt_addstring("direct-tcpip");
5182 ssh2_pkt_adduint32(c->localid);
5183 c->v.v2.locwindow = OUR_V2_WINSIZE;
5184 ssh2_pkt_adduint32(c->v.v2.locwindow);/* our window size */
5185 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5186 ssh2_pkt_addstring(hostname);
5187 ssh2_pkt_adduint32(port);
5189 * We make up values for the originator data; partly it's
5190 * too much hassle to keep track, and partly I'm not
5191 * convinced the server should be told details like that
5192 * about my local network configuration.
5194 ssh2_pkt_addstring("client-side-connection");
5195 ssh2_pkt_adduint32(0);
5201 static Socket ssh_socket(void)
5206 static int ssh_sendok(void)
5211 static int ssh_ldisc(int option)
5213 if (option == LD_ECHO)
5215 if (option == LD_EDIT)
5220 Backend ssh_backend = {