18 #define logevent(s) { logevent(s); \
19 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20 fprintf(stderr, "%s\n", s); }
22 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
23 (s ? sk_close(s), s = NULL : 0), \
24 connection_fatal msg )
26 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
27 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
28 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
29 #define SSH1_CMSG_USER 4 /* 0x4 */
30 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
31 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
32 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
33 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
34 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
35 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
36 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
37 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
38 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
39 #define SSH1_SMSG_FAILURE 15 /* 0xf */
40 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
41 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
42 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
43 #define SSH1_CMSG_EOF 19 /* 0x13 */
44 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
45 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
46 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
47 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
48 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
49 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
50 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
51 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
52 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
53 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
54 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
55 #define SSH1_MSG_IGNORE 32 /* 0x20 */
56 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
57 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
58 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
59 #define SSH1_MSG_DEBUG 36 /* 0x24 */
60 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
61 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
62 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
63 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
64 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
65 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
66 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
68 #define SSH1_AUTH_TIS 5 /* 0x5 */
69 #define SSH1_AUTH_CCARD 16 /* 0x10 */
71 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
72 #define SSH2_MSG_IGNORE 2 /* 0x2 */
73 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
74 #define SSH2_MSG_DEBUG 4 /* 0x4 */
75 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
76 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
77 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
78 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
79 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
80 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
81 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
82 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
83 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
84 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
85 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
86 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
87 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
88 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
89 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
90 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
91 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
92 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
93 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
94 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
95 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
96 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
97 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
98 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
99 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
100 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
101 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
102 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
103 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
104 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
106 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
107 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
108 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
109 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
110 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
111 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
112 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
113 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
114 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
115 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
116 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
118 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
119 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
120 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
121 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
123 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
125 #define GET_32BIT(cp) \
126 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
127 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
128 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
129 ((unsigned long)(unsigned char)(cp)[3]))
131 #define PUT_32BIT(cp, value) { \
132 (cp)[0] = (unsigned char)((value) >> 24); \
133 (cp)[1] = (unsigned char)((value) >> 16); \
134 (cp)[2] = (unsigned char)((value) >> 8); \
135 (cp)[3] = (unsigned char)(value); }
137 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
139 /* Coroutine mechanics for the sillier bits of the code */
140 #define crBegin1 static int crLine = 0;
141 #define crBegin2 switch(crLine) { case 0:;
142 #define crBegin crBegin1; crBegin2;
143 #define crFinish(z) } crLine = 0; return (z)
144 #define crFinishV } crLine = 0; return
145 #define crReturn(z) \
147 crLine=__LINE__; return (z); case __LINE__:;\
151 crLine=__LINE__; return; case __LINE__:;\
153 #define crStop(z) do{ crLine = 0; return (z); }while(0)
154 #define crStopV do{ crLine = 0; return; }while(0)
155 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
156 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
158 extern char *x11_init (Socket *, char *, void *);
159 extern void x11_close (Socket);
160 extern void x11_send (Socket , char *, int);
161 extern void x11_invent_auth(char *, int, char *, int);
164 * Ciphers for SSH2. We miss out single-DES because it isn't
165 * supported; also 3DES and Blowfish are both done differently from
166 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
167 * endianness and different-sized keys.)
169 const static struct ssh2_ciphers *ciphers[] = {
175 const static struct ssh_kex *kex_algs[] = {
176 #ifdef DO_DIFFIE_HELLMAN_GEX
177 &ssh_diffiehellman_gex,
179 &ssh_diffiehellman };
181 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
183 static void nullmac_key(unsigned char *key) { }
184 static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
185 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
186 const static struct ssh_mac ssh_mac_none = {
187 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
189 const static struct ssh_mac *macs[] = {
190 &ssh_sha1, &ssh_md5, &ssh_mac_none };
191 const static struct ssh_mac *buggymacs[] = {
192 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none };
194 static void ssh_comp_none_init(void) { }
195 static int ssh_comp_none_block(unsigned char *block, int len,
196 unsigned char **outblock, int *outlen) {
199 const static struct ssh_compress ssh_comp_none = {
201 ssh_comp_none_init, ssh_comp_none_block,
202 ssh_comp_none_init, ssh_comp_none_block
204 extern const struct ssh_compress ssh_zlib;
205 const static struct ssh_compress *compressions[] = {
206 &ssh_zlib, &ssh_comp_none };
208 enum { /* channel types */
215 * 2-3-4 tree storing channels.
218 unsigned remoteid, localid;
221 struct ssh2_data_channel {
222 unsigned char *outbuffer;
223 unsigned outbuflen, outbufsize;
224 unsigned remwindow, remmaxpkt;
227 struct ssh_agent_channel {
228 unsigned char *message;
229 unsigned char msglen[4];
230 int lensofar, totallen;
232 struct ssh_x11_channel {
247 static SHA_State exhash, exhashbase;
249 static Socket s = NULL;
251 static unsigned char session_key[32];
252 static int ssh1_compressing;
253 static int ssh_agentfwd_enabled;
254 static int ssh_X11_fwd_enabled;
255 static const struct ssh_cipher *cipher = NULL;
256 static const struct ssh2_cipher *cscipher = NULL;
257 static const struct ssh2_cipher *sccipher = NULL;
258 static const struct ssh_mac *csmac = NULL;
259 static const struct ssh_mac *scmac = NULL;
260 static const struct ssh_compress *cscomp = NULL;
261 static const struct ssh_compress *sccomp = NULL;
262 static const struct ssh_kex *kex = NULL;
263 static const struct ssh_signkey *hostkey = NULL;
264 static unsigned char ssh2_session_id[20];
265 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
267 static char *savedhost;
268 static int savedport;
269 static int ssh_send_ok;
270 static int ssh_echoing, ssh_editing;
272 static tree234 *ssh_channels; /* indexed by local id */
273 static struct ssh_channel *mainchan; /* primary session channel */
277 SSH_STATE_BEFORE_SIZE,
281 } ssh_state = SSH_STATE_PREPACKET;
283 static int size_needed = FALSE, eof_needed = FALSE;
285 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
286 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
287 static unsigned char *deferred_send_data = NULL;
288 static int deferred_len = 0, deferred_size = 0;
290 static int ssh_version;
291 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
292 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
293 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
294 static void ssh_size(void);
295 static void ssh_special (Telnet_Special);
296 static void ssh2_try_send(struct ssh_channel *c);
297 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
299 static int (*s_rdpkt)(unsigned char **data, int *datalen);
301 static struct rdpkt1_state_tag {
302 long len, pad, biglen, to_read;
303 unsigned long realcrc, gotcrc;
309 static struct rdpkt2_state_tag {
310 long len, pad, payload, packetlen, maclen;
313 unsigned long incoming_sequence;
316 static int ssh_channelcmp(void *av, void *bv) {
317 struct ssh_channel *a = (struct ssh_channel *)av;
318 struct ssh_channel *b = (struct ssh_channel *)bv;
319 if (a->localid < b->localid) return -1;
320 if (a->localid > b->localid) return +1;
323 static int ssh_channelfind(void *av, void *bv) {
324 unsigned *a = (unsigned *)av;
325 struct ssh_channel *b = (struct ssh_channel *)bv;
326 if (*a < b->localid) return -1;
327 if (*a > b->localid) return +1;
331 static void c_write (char *buf, int len) {
332 if ((flags & FLAG_STDERR)) {
334 for (i = 0; i < len; i++)
336 fputc(buf[i], stderr);
339 from_backend(1, buf, len);
342 static void c_write_str (char *buf) {
343 c_write(buf, strlen(buf));
347 * Collect incoming data in the incoming packet buffer.
348 * Decipher and verify the packet when it is completely read.
349 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
350 * Update the *data and *datalen variables.
351 * Return the additional nr of bytes needed, or 0 when
352 * a complete packet is available.
354 static int ssh1_rdpkt(unsigned char **data, int *datalen)
356 struct rdpkt1_state_tag *st = &rdpkt1_state;
365 for (st->i = st->len = 0; st->i < 4; st->i++) {
366 while ((*datalen) == 0)
368 st->len = (st->len << 8) + **data;
369 (*data)++, (*datalen)--;
373 if (st->len == 0x52656d6f) { /* "Remo"te server has closed ... */
374 st->len = 0x300; /* big enough to carry to end */
378 st->pad = 8 - (st->len % 8);
379 st->biglen = st->len + st->pad;
380 pktin.length = st->len - 5;
382 if (pktin.maxlen < st->biglen) {
383 pktin.maxlen = st->biglen;
384 pktin.data = (pktin.data == NULL ? smalloc(st->biglen+APIEXTRA) :
385 srealloc(pktin.data, st->biglen+APIEXTRA));
387 fatalbox("Out of memory");
390 st->to_read = st->biglen;
392 while (st->to_read > 0) {
393 st->chunk = st->to_read;
394 while ((*datalen) == 0)
395 crReturn(st->to_read);
396 if (st->chunk > (*datalen))
397 st->chunk = (*datalen);
398 memcpy(st->p, *data, st->chunk);
400 *datalen -= st->chunk;
402 st->to_read -= st->chunk;
406 cipher->decrypt(pktin.data, st->biglen);
408 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
409 for (st->i = 0; st->i < st->biglen; st->i++)
410 debug((" %02x", (unsigned char)pktin.data[st->i]));
414 st->realcrc = crc32(pktin.data, st->biglen-4);
415 st->gotcrc = GET_32BIT(pktin.data+st->biglen-4);
416 if (st->gotcrc != st->realcrc) {
417 bombout(("Incorrect CRC received on packet"));
421 pktin.body = pktin.data + st->pad + 1;
423 if (ssh1_compressing) {
424 unsigned char *decompblk;
428 debug(("Packet payload pre-decompression:\n"));
429 for (i = -1; i < pktin.length; i++)
430 debug((" %02x", (unsigned char)pktin.body[i]));
433 zlib_decompress_block(pktin.body-1, pktin.length+1,
434 &decompblk, &decomplen);
436 if (pktin.maxlen < st->pad + decomplen) {
437 pktin.maxlen = st->pad + decomplen;
438 pktin.data = srealloc(pktin.data, pktin.maxlen+APIEXTRA);
439 pktin.body = pktin.data + st->pad + 1;
441 fatalbox("Out of memory");
444 memcpy(pktin.body-1, decompblk, decomplen);
446 pktin.length = decomplen-1;
448 debug(("Packet payload post-decompression:\n"));
449 for (i = -1; i < pktin.length; i++)
450 debug((" %02x", (unsigned char)pktin.body[i]));
455 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
456 pktin.type == SSH1_SMSG_STDERR_DATA ||
457 pktin.type == SSH1_MSG_DEBUG ||
458 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
459 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
460 long strlen = GET_32BIT(pktin.body);
461 if (strlen + 4 != pktin.length) {
462 bombout(("Received data packet with bogus string length"));
467 pktin.type = pktin.body[-1];
469 if (pktin.type == SSH1_MSG_DEBUG) {
470 /* log debug message */
472 int strlen = GET_32BIT(pktin.body);
473 strcpy(buf, "Remote: ");
474 if (strlen > 70) strlen = 70;
475 memcpy(buf+8, pktin.body+4, strlen);
476 buf[8+strlen] = '\0';
479 } else if (pktin.type == SSH1_MSG_IGNORE) {
487 static int ssh2_rdpkt(unsigned char **data, int *datalen)
489 struct rdpkt2_state_tag *st = &rdpkt2_state;
497 st->cipherblk = sccipher->blksize;
500 if (st->cipherblk < 8)
503 if (pktin.maxlen < st->cipherblk) {
504 pktin.maxlen = st->cipherblk;
505 pktin.data = (pktin.data == NULL ? smalloc(st->cipherblk+APIEXTRA) :
506 srealloc(pktin.data, st->cipherblk+APIEXTRA));
508 fatalbox("Out of memory");
512 * Acquire and decrypt the first block of the packet. This will
513 * contain the length and padding details.
515 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
516 while ((*datalen) == 0)
517 crReturn(st->cipherblk-st->i);
518 pktin.data[st->i] = *(*data)++;
522 if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
527 sccipher->decrypt(pktin.data, st->cipherblk);
530 * Now get the length and padding figures.
532 st->len = GET_32BIT(pktin.data);
533 st->pad = pktin.data[4];
536 * This enables us to deduce the payload length.
538 st->payload = st->len - st->pad - 1;
540 pktin.length = st->payload + 5;
543 * So now we can work out the total packet length.
545 st->packetlen = st->len + 4;
546 st->maclen = scmac ? scmac->len : 0;
549 * Adjust memory allocation if packet is too big.
551 if (pktin.maxlen < st->packetlen+st->maclen) {
552 pktin.maxlen = st->packetlen+st->maclen;
553 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
554 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
556 fatalbox("Out of memory");
560 * Read and decrypt the remainder of the packet.
562 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen; st->i++) {
563 while ((*datalen) == 0)
564 crReturn(st->packetlen + st->maclen - st->i);
565 pktin.data[st->i] = *(*data)++;
568 /* Decrypt everything _except_ the MAC. */
570 sccipher->decrypt(pktin.data + st->cipherblk,
571 st->packetlen - st->cipherblk);
574 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
575 for (st->i = 0; st->i < st->packetlen; st->i++)
576 debug((" %02x", (unsigned char)pktin.data[st->i]));
583 if (scmac && !scmac->verify(pktin.data, st->len+4, st->incoming_sequence)) {
584 bombout(("Incorrect MAC received on packet"));
587 st->incoming_sequence++; /* whether or not we MACed */
590 * Decompress packet payload.
593 unsigned char *newpayload;
595 if (sccomp && sccomp->decompress(pktin.data+5, pktin.length-5,
596 &newpayload, &newlen)) {
597 if (pktin.maxlen < newlen+5) {
598 pktin.maxlen = newlen+5;
599 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
600 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
602 fatalbox("Out of memory");
604 pktin.length = 5 + newlen;
605 memcpy(pktin.data+5, newpayload, newlen);
607 debug(("Post-decompression payload:\r\n"));
608 for (st->i = 0; st->i < newlen; st->i++)
609 debug((" %02x", (unsigned char)pktin.data[5+st->i]));
618 pktin.type = pktin.data[5];
620 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
621 goto next_packet; /* FIXME: print DEBUG message */
626 static void ssh1_pktout_size(int len) {
629 len += 5; /* type and CRC */
633 pktout.length = len-5;
634 if (pktout.maxlen < biglen) {
635 pktout.maxlen = biglen;
637 /* Allocate enough buffer space for extra block
638 * for MS CryptEncrypt() */
639 pktout.data = (pktout.data == NULL ? smalloc(biglen+12) :
640 srealloc(pktout.data, biglen+12));
642 pktout.data = (pktout.data == NULL ? smalloc(biglen+4) :
643 srealloc(pktout.data, biglen+4));
646 fatalbox("Out of memory");
648 pktout.body = pktout.data+4+pad+1;
651 static void s_wrpkt_start(int type, int len) {
652 ssh1_pktout_size(len);
656 static int s_wrpkt_prepare(void) {
657 int pad, len, biglen, i;
660 pktout.body[-1] = pktout.type;
662 if (ssh1_compressing) {
663 unsigned char *compblk;
666 debug(("Packet payload pre-compression:\n"));
667 for (i = -1; i < pktout.length; i++)
668 debug((" %02x", (unsigned char)pktout.body[i]));
671 zlib_compress_block(pktout.body-1, pktout.length+1,
673 ssh1_pktout_size(complen-1);
674 memcpy(pktout.body-1, compblk, complen);
677 debug(("Packet payload post-compression:\n"));
678 for (i = -1; i < pktout.length; i++)
679 debug((" %02x", (unsigned char)pktout.body[i]));
684 len = pktout.length + 5; /* type and CRC */
688 for (i=0; i<pad; i++)
689 pktout.data[i+4] = random_byte();
690 crc = crc32(pktout.data+4, biglen-4);
691 PUT_32BIT(pktout.data+biglen, crc);
692 PUT_32BIT(pktout.data, len);
695 debug(("Sending packet len=%d\r\n", biglen+4));
696 for (i = 0; i < biglen+4; i++)
697 debug((" %02x", (unsigned char)pktout.data[i]));
701 cipher->encrypt(pktout.data+4, biglen);
706 static void s_wrpkt(void) {
708 len = s_wrpkt_prepare();
709 sk_write(s, pktout.data, len);
712 static void s_wrpkt_defer(void) {
714 len = s_wrpkt_prepare();
715 if (deferred_len + len > deferred_size) {
716 deferred_size = deferred_len + len + 128;
717 deferred_send_data = srealloc(deferred_send_data, deferred_size);
719 memcpy(deferred_send_data+deferred_len, pktout.data, len);
724 * Construct a packet with the specified contents.
726 static void construct_packet(int pkttype, va_list ap1, va_list ap2)
728 unsigned char *p, *argp, argchar;
729 unsigned long argint;
730 int pktlen, argtype, arglen;
734 while ((argtype = va_arg(ap1, int)) != PKT_END) {
737 (void) va_arg(ap1, int);
741 (void) va_arg(ap1, char);
745 (void) va_arg(ap1, unsigned char *);
746 arglen = va_arg(ap1, int);
750 argp = va_arg(ap1, unsigned char *);
751 arglen = strlen(argp);
752 pktlen += 4 + arglen;
755 bn = va_arg(ap1, Bignum);
756 pktlen += ssh1_bignum_length(bn);
763 s_wrpkt_start(pkttype, pktlen);
766 while ((argtype = va_arg(ap2, int)) != PKT_END) {
769 argint = va_arg(ap2, int);
770 PUT_32BIT(p, argint);
774 argchar = va_arg(ap2, unsigned char);
779 argp = va_arg(ap2, unsigned char *);
780 arglen = va_arg(ap2, int);
781 memcpy(p, argp, arglen);
785 argp = va_arg(ap2, unsigned char *);
786 arglen = strlen(argp);
787 PUT_32BIT(p, arglen);
788 memcpy(p + 4, argp, arglen);
792 bn = va_arg(ap2, Bignum);
793 p += ssh1_write_bignum(p, bn);
799 static void send_packet(int pkttype, ...) {
801 va_start(ap1, pkttype);
802 va_start(ap2, pkttype);
803 construct_packet(pkttype, ap1, ap2);
807 static void defer_packet(int pkttype, ...) {
809 va_start(ap1, pkttype);
810 va_start(ap2, pkttype);
811 construct_packet(pkttype, ap1, ap2);
815 static int ssh_versioncmp(char *a, char *b) {
817 unsigned long av, bv;
819 av = strtoul(a, &ae, 10);
820 bv = strtoul(b, &be, 10);
821 if (av != bv) return (av < bv ? -1 : +1);
822 if (*ae == '.') ae++;
823 if (*be == '.') be++;
824 av = strtoul(ae, &ae, 10);
825 bv = strtoul(be, &be, 10);
826 if (av != bv) return (av < bv ? -1 : +1);
832 * Utility routines for putting an SSH-protocol `string' and
833 * `uint32' into a SHA state.
836 static void sha_string(SHA_State *s, void *str, int len) {
837 unsigned char lenblk[4];
838 PUT_32BIT(lenblk, len);
839 SHA_Bytes(s, lenblk, 4);
840 SHA_Bytes(s, str, len);
843 static void sha_uint32(SHA_State *s, unsigned i) {
844 unsigned char intblk[4];
845 PUT_32BIT(intblk, i);
846 SHA_Bytes(s, intblk, 4);
850 * SSH2 packet construction functions.
852 static void ssh2_pkt_ensure(int length) {
853 if (pktout.maxlen < length) {
854 pktout.maxlen = length + 256;
855 pktout.data = (pktout.data == NULL ? smalloc(pktout.maxlen+APIEXTRA) :
856 srealloc(pktout.data, pktout.maxlen+APIEXTRA));
858 fatalbox("Out of memory");
861 static void ssh2_pkt_adddata(void *data, int len) {
862 pktout.length += len;
863 ssh2_pkt_ensure(pktout.length);
864 memcpy(pktout.data+pktout.length-len, data, len);
866 static void ssh2_pkt_addbyte(unsigned char byte) {
867 ssh2_pkt_adddata(&byte, 1);
869 static void ssh2_pkt_init(int pkt_type) {
871 ssh2_pkt_addbyte((unsigned char)pkt_type);
873 static void ssh2_pkt_addbool(unsigned char value) {
874 ssh2_pkt_adddata(&value, 1);
876 static void ssh2_pkt_adduint32(unsigned long value) {
879 ssh2_pkt_adddata(x, 4);
881 static void ssh2_pkt_addstring_start(void) {
882 ssh2_pkt_adduint32(0);
883 pktout.savedpos = pktout.length;
885 static void ssh2_pkt_addstring_str(char *data) {
886 ssh2_pkt_adddata(data, strlen(data));
887 PUT_32BIT(pktout.data + pktout.savedpos - 4,
888 pktout.length - pktout.savedpos);
890 static void ssh2_pkt_addstring_data(char *data, int len) {
891 ssh2_pkt_adddata(data, len);
892 PUT_32BIT(pktout.data + pktout.savedpos - 4,
893 pktout.length - pktout.savedpos);
895 static void ssh2_pkt_addstring(char *data) {
896 ssh2_pkt_addstring_start();
897 ssh2_pkt_addstring_str(data);
899 static char *ssh2_mpint_fmt(Bignum b, int *len) {
901 int i, n = (ssh1_bignum_bitcount(b)+7)/8;
904 fatalbox("out of memory");
906 for (i = 1; i <= n; i++)
907 p[i] = bignum_byte(b, n-i);
909 while (i <= n && p[i] == 0 && (p[i+1] & 0x80) == 0)
911 memmove(p, p+i, n+1-i);
915 static void ssh2_pkt_addmp(Bignum b) {
918 p = ssh2_mpint_fmt(b, &len);
919 ssh2_pkt_addstring_start();
920 ssh2_pkt_addstring_data(p, len);
925 * Construct an SSH2 final-form packet: compress it, encrypt it,
926 * put the MAC on it. Final packet, ready to be sent, is stored in
927 * pktout.data. Total length is returned.
929 static int ssh2_pkt_construct(void) {
930 int cipherblk, maclen, padding, i;
931 static unsigned long outgoing_sequence = 0;
934 * Compress packet payload.
937 debug(("Pre-compression payload:\r\n"));
938 for (i = 5; i < pktout.length; i++)
939 debug((" %02x", (unsigned char)pktout.data[i]));
943 unsigned char *newpayload;
945 if (cscomp && cscomp->compress(pktout.data+5, pktout.length-5,
946 &newpayload, &newlen)) {
948 ssh2_pkt_adddata(newpayload, newlen);
954 * Add padding. At least four bytes, and must also bring total
955 * length (minus MAC) up to a multiple of the block size.
957 cipherblk = cscipher ? cscipher->blksize : 8; /* block size */
958 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
960 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
961 maclen = csmac ? csmac->len : 0;
962 ssh2_pkt_ensure(pktout.length + padding + maclen);
963 pktout.data[4] = padding;
964 for (i = 0; i < padding; i++)
965 pktout.data[pktout.length + i] = random_byte();
966 PUT_32BIT(pktout.data, pktout.length + padding - 4);
968 csmac->generate(pktout.data, pktout.length + padding,
970 outgoing_sequence++; /* whether or not we MACed */
973 debug(("Sending packet len=%d\r\n", pktout.length+padding));
974 for (i = 0; i < pktout.length+padding; i++)
975 debug((" %02x", (unsigned char)pktout.data[i]));
980 cscipher->encrypt(pktout.data, pktout.length + padding);
982 /* Ready-to-send packet starts at pktout.data. We return length. */
983 return pktout.length + padding + maclen;
987 * Construct and send an SSH2 packet immediately.
989 static void ssh2_pkt_send(void) {
990 int len = ssh2_pkt_construct();
991 sk_write(s, pktout.data, len);
995 * Construct an SSH2 packet and add it to a deferred data block.
996 * Useful for sending multiple packets in a single sk_write() call,
997 * to prevent a traffic-analysing listener from being able to work
998 * out the length of any particular packet (such as the password
1001 * Note that because SSH2 sequence-numbers its packets, this can
1002 * NOT be used as an m4-style `defer' allowing packets to be
1003 * constructed in one order and sent in another.
1005 static void ssh2_pkt_defer(void) {
1006 int len = ssh2_pkt_construct();
1007 if (deferred_len + len > deferred_size) {
1008 deferred_size = deferred_len + len + 128;
1009 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1011 memcpy(deferred_send_data+deferred_len, pktout.data, len);
1012 deferred_len += len;
1016 * Send the whole deferred data block constructed by
1017 * ssh2_pkt_defer() or SSH1's defer_packet().
1019 static void ssh_pkt_defersend(void) {
1020 sk_write(s, deferred_send_data, deferred_len);
1021 deferred_len = deferred_size = 0;
1022 sfree(deferred_send_data);
1023 deferred_send_data = NULL;
1027 void bndebug(char *string, Bignum b) {
1030 p = ssh2_mpint_fmt(b, &len);
1031 debug(("%s", string));
1032 for (i = 0; i < len; i++)
1033 debug((" %02x", p[i]));
1039 static void sha_mpint(SHA_State *s, Bignum b) {
1042 p = ssh2_mpint_fmt(b, &len);
1043 sha_string(s, p, len);
1048 * SSH2 packet decode functions.
1050 static unsigned long ssh2_pkt_getuint32(void) {
1051 unsigned long value;
1052 if (pktin.length - pktin.savedpos < 4)
1053 return 0; /* arrgh, no way to decline (FIXME?) */
1054 value = GET_32BIT(pktin.data+pktin.savedpos);
1055 pktin.savedpos += 4;
1058 static int ssh2_pkt_getbool(void) {
1059 unsigned long value;
1060 if (pktin.length - pktin.savedpos < 1)
1061 return 0; /* arrgh, no way to decline (FIXME?) */
1062 value = pktin.data[pktin.savedpos] != 0;
1066 static void ssh2_pkt_getstring(char **p, int *length) {
1068 if (pktin.length - pktin.savedpos < 4)
1070 *length = GET_32BIT(pktin.data+pktin.savedpos);
1071 pktin.savedpos += 4;
1072 if (pktin.length - pktin.savedpos < *length)
1074 *p = pktin.data+pktin.savedpos;
1075 pktin.savedpos += *length;
1077 static Bignum ssh2_pkt_getmp(void) {
1082 ssh2_pkt_getstring(&p, &length);
1086 bombout(("internal error: Can't handle negative mpints"));
1089 b = bignum_from_bytes(p, length);
1093 static int do_ssh_init(unsigned char c) {
1095 static char version[10];
1096 static char vstring[80];
1097 static char vlog[sizeof(vstring)+20];
1102 /* Search for the string "SSH-" in the input. */
1105 static const int transS[] = { 1, 2, 2, 1 };
1106 static const int transH[] = { 0, 0, 3, 0 };
1107 static const int transminus[] = { 0, 0, 0, -1 };
1108 if (c == 'S') i = transS[i];
1109 else if (c == 'H') i = transH[i];
1110 else if (c == '-') i = transminus[i];
1114 crReturn(1); /* get another character */
1117 strcpy(vstring, "SSH-");
1121 crReturn(1); /* get another char */
1122 if (vsp < vstring+sizeof(vstring)-1)
1128 } else if (i < sizeof(version)-1)
1135 ssh_agentfwd_enabled = FALSE;
1136 rdpkt2_state.incoming_sequence = 0;
1139 sprintf(vlog, "Server version: %s", vstring);
1140 vlog[strcspn(vlog, "\r\n")] = '\0';
1144 * Server version "1.99" means we can choose whether we use v1
1145 * or v2 protocol. Choice is based on cfg.sshprot.
1147 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1149 * This is a v2 server. Begin v2 protocol.
1151 char *verstring = "SSH-2.0-PuTTY";
1152 SHA_Init(&exhashbase);
1154 * Hash our version string and their version string.
1156 sha_string(&exhashbase, verstring, strlen(verstring));
1157 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1158 sprintf(vstring, "%s\n", verstring);
1159 sprintf(vlog, "We claim version: %s", verstring);
1161 logevent("Using SSH protocol version 2");
1162 sk_write(s, vstring, strlen(vstring));
1163 ssh_protocol = ssh2_protocol;
1165 s_rdpkt = ssh2_rdpkt;
1168 * This is a v1 server. Begin v1 protocol.
1170 sprintf(vstring, "SSH-%s-PuTTY\n",
1171 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1172 sprintf(vlog, "We claim version: %s", vstring);
1173 vlog[strcspn(vlog, "\r\n")] = '\0';
1175 logevent("Using SSH protocol version 1");
1176 sk_write(s, vstring, strlen(vstring));
1177 ssh_protocol = ssh1_protocol;
1179 s_rdpkt = ssh1_rdpkt;
1181 ssh_state = SSH_STATE_BEFORE_SIZE;
1186 static void ssh_gotdata(unsigned char *data, int datalen)
1191 * To begin with, feed the characters one by one to the
1192 * protocol initialisation / selection function do_ssh_init().
1193 * When that returns 0, we're done with the initial greeting
1194 * exchange and can move on to packet discipline.
1199 crReturnV; /* more data please */
1200 ret = do_ssh_init(*data);
1207 * We emerge from that loop when the initial negotiation is
1208 * over and we have selected an s_rdpkt function. Now pass
1209 * everything to s_rdpkt, and then pass the resulting packets
1210 * to the proper protocol handler.
1215 while (datalen > 0) {
1216 if ( s_rdpkt(&data, &datalen) == 0 ) {
1217 ssh_protocol(NULL, 0, 1);
1218 if (ssh_state == SSH_STATE_CLOSED) {
1228 static int ssh_receive(Socket skt, int urgent, char *data, int len) {
1230 /* A socket error has occurred. */
1231 ssh_state = SSH_STATE_CLOSED;
1234 connection_fatal(data);
1237 /* Connection has closed. */
1238 ssh_state = SSH_STATE_CLOSED;
1243 ssh_gotdata (data, len);
1244 if (ssh_state == SSH_STATE_CLOSED) {
1255 * Connect to specified host and port.
1256 * Returns an error message, or NULL on success.
1257 * Also places the canonical host name into `realhost'.
1259 static char *connect_to_host(char *host, int port, char **realhost)
1268 savedhost = smalloc(1+strlen(host));
1270 fatalbox("Out of memory");
1271 strcpy(savedhost, host);
1274 port = 22; /* default ssh port */
1287 addr = sk_namelookup(host, realhost);
1288 if ( (err = sk_addr_error(addr)) )
1298 s = sk_new(addr, port, 0, 1, ssh_receive);
1299 if ( (err = sk_socket_error(s)) )
1303 sk_write(s, "connect ", 8);
1304 sk_write(s, FWhost, strlen(FWhost));
1307 sprintf(buf, " %d\n", FWport);
1308 sk_write(s, buf, strlen(buf));
1316 * Handle the key exchange and user authentication phases.
1318 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1321 unsigned char *rsabuf, *keystr1, *keystr2;
1322 unsigned char cookie[8];
1323 struct RSAKey servkey, hostkey;
1324 struct MD5Context md5c;
1325 static unsigned long supported_ciphers_mask, supported_auths_mask;
1326 static int tried_publickey;
1327 static unsigned char session_id[16];
1329 static char username[100];
1333 if (!ispkt) crWaitUntil(ispkt);
1335 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1336 bombout(("Public key packet not received"));
1340 logevent("Received public keys");
1342 memcpy(cookie, pktin.body, 8);
1344 i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1345 j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1348 * Log the host key fingerprint.
1352 logevent("Host key fingerprint is:");
1353 strcpy(logmsg, " ");
1354 hostkey.comment = NULL;
1355 rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
1360 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1361 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1364 MD5Update(&md5c, keystr2, hostkey.bytes);
1365 MD5Update(&md5c, keystr1, servkey.bytes);
1366 MD5Update(&md5c, pktin.body, 8);
1367 MD5Final(session_id, &md5c);
1369 for (i=0; i<32; i++)
1370 session_key[i] = random_byte();
1372 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1374 rsabuf = smalloc(len);
1376 fatalbox("Out of memory");
1379 * Verify the host key.
1383 * First format the key into a string.
1385 int len = rsastr_len(&hostkey);
1386 char fingerprint[100];
1387 char *keystr = smalloc(len);
1389 fatalbox("Out of memory");
1390 rsastr_fmt(keystr, &hostkey);
1391 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
1392 verify_ssh_host_key(savedhost, savedport, "rsa", keystr, fingerprint);
1396 for (i=0; i<32; i++) {
1397 rsabuf[i] = session_key[i];
1399 rsabuf[i] ^= session_id[i];
1402 if (hostkey.bytes > servkey.bytes) {
1403 rsaencrypt(rsabuf, 32, &servkey);
1404 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1406 rsaencrypt(rsabuf, 32, &hostkey);
1407 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1410 logevent("Encrypted session key");
1412 switch (cfg.cipher) {
1413 case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH; break;
1414 case CIPHER_DES: cipher_type = SSH_CIPHER_DES; break;
1415 case CIPHER_3DES: cipher_type = SSH_CIPHER_3DES; break;
1417 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1418 cipher_type = SSH_CIPHER_3DES;
1421 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1422 c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
1423 cipher_type = SSH_CIPHER_3DES;
1425 switch (cipher_type) {
1426 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1427 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1428 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1431 send_packet(SSH1_CMSG_SESSION_KEY,
1432 PKT_CHAR, cipher_type,
1433 PKT_DATA, cookie, 8,
1434 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1435 PKT_DATA, rsabuf, len,
1439 logevent("Trying to enable encryption...");
1443 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1444 cipher_type == SSH_CIPHER_DES ? &ssh_des :
1446 cipher->sesskey(session_key);
1450 if (pktin.type != SSH1_SMSG_SUCCESS) {
1451 bombout(("Encryption not successfully enabled"));
1455 logevent("Successfully started encryption");
1461 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1462 c_write_str("login as: ");
1465 crWaitUntil(!ispkt);
1466 while (inlen--) switch (c = *in++) {
1473 c_write_str("\b \b");
1479 c_write_str("\b \b");
1488 if (((c >= ' ' && c <= '~') ||
1489 ((unsigned char)c >= 160)) && pos < 40) {
1490 username[pos++] = c;
1496 c_write_str("\r\n");
1497 username[strcspn(username, "\n\r")] = '\0';
1499 strncpy(username, cfg.username, 99);
1500 username[99] = '\0';
1503 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1505 char userlog[22+sizeof(username)];
1506 sprintf(userlog, "Sent username \"%s\"", username);
1508 if (flags & FLAG_INTERACTIVE &&
1509 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
1510 strcat(userlog, "\r\n");
1511 c_write_str(userlog);
1518 tried_publickey = 0;
1520 while (pktin.type == SSH1_SMSG_FAILURE) {
1521 static char password[100];
1522 static char prompt[200];
1525 static int pwpkt_type;
1527 * Show password prompt, having first obtained it via a TIS
1528 * or CryptoCard exchange if we're doing TIS or CryptoCard
1531 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1532 if (agent_exists()) {
1534 * Attempt RSA authentication using Pageant.
1536 static unsigned char request[5], *response, *p;
1537 static int responselen;
1538 static int i, nkeys;
1539 static int authed = FALSE;
1542 logevent("Pageant is running. Requesting keys.");
1544 /* Request the keys held by the agent. */
1545 PUT_32BIT(request, 1);
1546 request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
1547 agent_query(request, 5, &r, &responselen);
1548 response = (unsigned char *)r;
1551 nkeys = GET_32BIT(p); p += 4;
1552 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
1554 for (i = 0; i < nkeys; i++) {
1555 static struct RSAKey key;
1556 static Bignum challenge;
1557 static char *commentp;
1558 static int commentlen;
1560 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1563 p += ssh1_read_bignum(p, &key.exponent);
1564 p += ssh1_read_bignum(p, &key.modulus);
1565 commentlen = GET_32BIT(p); p += 4;
1566 commentp = p; p += commentlen;
1567 send_packet(SSH1_CMSG_AUTH_RSA,
1568 PKT_BIGNUM, key.modulus, PKT_END);
1570 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1571 logevent("Key refused");
1574 logevent("Received RSA challenge");
1575 ssh1_read_bignum(pktin.body, &challenge);
1577 char *agentreq, *q, *ret;
1579 len = 1 + 4; /* message type, bit count */
1580 len += ssh1_bignum_length(key.exponent);
1581 len += ssh1_bignum_length(key.modulus);
1582 len += ssh1_bignum_length(challenge);
1583 len += 16; /* session id */
1584 len += 4; /* response format */
1585 agentreq = smalloc(4 + len);
1586 PUT_32BIT(agentreq, len);
1588 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
1589 PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1591 q += ssh1_write_bignum(q, key.exponent);
1592 q += ssh1_write_bignum(q, key.modulus);
1593 q += ssh1_write_bignum(q, challenge);
1594 memcpy(q, session_id, 16); q += 16;
1595 PUT_32BIT(q, 1); /* response format */
1596 agent_query(agentreq, len+4, &ret, &retlen);
1599 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
1600 logevent("Sending Pageant's response");
1601 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1602 PKT_DATA, ret+5, 16, PKT_END);
1605 if (pktin.type == SSH1_SMSG_SUCCESS) {
1606 logevent("Pageant's response accepted");
1607 if (flags & FLAG_VERBOSE) {
1608 c_write_str("Authenticated using RSA key \"");
1609 c_write(commentp, commentlen);
1610 c_write_str("\" from agent\r\n");
1614 logevent("Pageant's response not accepted");
1616 logevent("Pageant failed to answer challenge");
1620 logevent("No reply received from Pageant");
1623 freebn(key.exponent);
1624 freebn(key.modulus);
1633 if (*cfg.keyfile && !tried_publickey)
1634 pwpkt_type = SSH1_CMSG_AUTH_RSA;
1636 if (pktin.type == SSH1_SMSG_FAILURE &&
1638 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1639 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1640 logevent("Requested TIS authentication");
1641 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1643 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1644 logevent("TIS authentication declined");
1645 if (flags & FLAG_INTERACTIVE)
1646 c_write_str("TIS authentication refused.\r\n");
1648 int challengelen = ((pktin.body[0] << 24) |
1649 (pktin.body[1] << 16) |
1650 (pktin.body[2] << 8) |
1652 logevent("Received TIS challenge");
1653 if (challengelen > sizeof(prompt)-1)
1654 challengelen = sizeof(prompt)-1; /* prevent overrun */
1655 memcpy(prompt, pktin.body+4, challengelen);
1656 prompt[challengelen] = '\0';
1659 if (pktin.type == SSH1_SMSG_FAILURE &&
1661 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1662 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1663 logevent("Requested CryptoCard authentication");
1664 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1666 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1667 logevent("CryptoCard authentication declined");
1668 c_write_str("CryptoCard authentication refused.\r\n");
1670 int challengelen = ((pktin.body[0] << 24) |
1671 (pktin.body[1] << 16) |
1672 (pktin.body[2] << 8) |
1674 logevent("Received CryptoCard challenge");
1675 if (challengelen > sizeof(prompt)-1)
1676 challengelen = sizeof(prompt)-1; /* prevent overrun */
1677 memcpy(prompt, pktin.body+4, challengelen);
1678 strncpy(prompt + challengelen, "\r\nResponse : ",
1679 sizeof(prompt)-challengelen);
1680 prompt[sizeof(prompt)-1] = '\0';
1683 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1684 sprintf(prompt, "%.90s@%.90s's password: ",
1685 username, savedhost);
1687 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1688 char *comment = NULL;
1689 if (flags & FLAG_VERBOSE)
1690 c_write_str("Trying public key authentication.\r\n");
1691 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1692 if (flags & FLAG_VERBOSE)
1693 c_write_str("No passphrase required.\r\n");
1696 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
1700 if (ssh_get_password) {
1701 if (!ssh_get_password(prompt, password, sizeof(password))) {
1703 * get_password failed to get a password (for
1704 * example because one was supplied on the command
1705 * line which has already failed to work).
1708 logevent("No more passwords to try");
1709 ssh_state = SSH_STATE_CLOSED;
1713 c_write_str(prompt);
1717 crWaitUntil(!ispkt);
1718 while (inlen--) switch (c = *in++) {
1735 if (((c >= ' ' && c <= '~') ||
1736 ((unsigned char)c >= 160)) && pos < sizeof(password))
1737 password[pos++] = c;
1741 c_write_str("\r\n");
1745 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1747 * Try public key authentication with the specified
1750 static struct RSAKey pubkey;
1751 static Bignum challenge, response;
1753 static unsigned char buffer[32];
1755 tried_publickey = 1;
1756 i = loadrsakey(cfg.keyfile, &pubkey, password);
1758 c_write_str("Couldn't load public key from ");
1759 c_write_str(cfg.keyfile);
1760 c_write_str(".\r\n");
1761 continue; /* go and try password */
1764 c_write_str("Wrong passphrase.\r\n");
1765 tried_publickey = 0;
1766 continue; /* try again */
1770 * Send a public key attempt.
1772 send_packet(SSH1_CMSG_AUTH_RSA,
1773 PKT_BIGNUM, pubkey.modulus, PKT_END);
1776 if (pktin.type == SSH1_SMSG_FAILURE) {
1777 c_write_str("Server refused our public key.\r\n");
1778 continue; /* go and try password */
1780 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1781 bombout(("Bizarre response to offer of public key"));
1784 ssh1_read_bignum(pktin.body, &challenge);
1785 response = rsadecrypt(challenge, &pubkey);
1786 freebn(pubkey.private_exponent); /* burn the evidence */
1788 for (i = 0; i < 32; i++) {
1789 buffer[i] = bignum_byte(response, 31-i);
1793 MD5Update(&md5c, buffer, 32);
1794 MD5Update(&md5c, session_id, 16);
1795 MD5Final(buffer, &md5c);
1797 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1798 PKT_DATA, buffer, 16, PKT_END);
1801 if (pktin.type == SSH1_SMSG_FAILURE) {
1802 if (flags & FLAG_VERBOSE)
1803 c_write_str("Failed to authenticate with our public key.\r\n");
1804 continue; /* go and try password */
1805 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1806 bombout(("Bizarre response to RSA authentication response"));
1810 break; /* we're through! */
1812 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1814 * Defence against traffic analysis: we send a
1815 * whole bunch of packets containing strings of
1816 * different lengths. One of these strings is the
1817 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
1818 * The others are all random data in
1819 * SSH1_MSG_IGNORE packets. This way a passive
1820 * listener can't tell which is the password, and
1821 * hence can't deduce the password length.
1823 * Anybody with a password length greater than 16
1824 * bytes is going to have enough entropy in their
1825 * password that a listener won't find it _that_
1826 * much help to know how long it is. So what we'll
1829 * - if password length < 16, we send 15 packets
1830 * containing string lengths 1 through 15
1832 * - otherwise, we let N be the nearest multiple
1833 * of 8 below the password length, and send 8
1834 * packets containing string lengths N through
1835 * N+7. This won't obscure the order of
1836 * magnitude of the password length, but it will
1837 * introduce a bit of extra uncertainty.
1839 int bottom, top, pwlen, i;
1842 pwlen = strlen(password);
1847 bottom = pwlen &~ 7;
1851 assert(pwlen >= bottom && pwlen <= top);
1853 randomstr = smalloc(top+1);
1855 for (i = bottom; i <= top; i++) {
1857 defer_packet(pwpkt_type, PKT_STR, password, PKT_END);
1859 for (j = 0; j < i; j++) {
1861 randomstr[j] = random_byte();
1862 } while (randomstr[j] == '\0');
1864 randomstr[i] = '\0';
1865 defer_packet(SSH1_MSG_IGNORE,
1866 PKT_STR, randomstr, PKT_END);
1869 ssh_pkt_defersend();
1871 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1874 logevent("Sent password");
1875 memset(password, 0, strlen(password));
1877 if (pktin.type == SSH1_SMSG_FAILURE) {
1878 if (flags & FLAG_VERBOSE)
1879 c_write_str("Access denied\r\n");
1880 logevent("Authentication refused");
1881 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1882 logevent("Received disconnect request");
1883 ssh_state = SSH_STATE_CLOSED;
1885 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1886 bombout(("Strange packet received, type %d", pktin.type));
1891 logevent("Authentication successful");
1896 void sshfwd_close(struct ssh_channel *c) {
1898 if (ssh_version == 1) {
1899 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END);
1901 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
1902 ssh2_pkt_adduint32(c->remoteid);
1906 if (c->type == CHAN_X11) {
1908 logevent("X11 connection terminated");
1913 void sshfwd_write(struct ssh_channel *c, char *buf, int len) {
1914 if (ssh_version == 1) {
1915 send_packet(SSH1_MSG_CHANNEL_DATA,
1916 PKT_INT, c->remoteid,
1921 ssh2_add_channel_data(c, buf, len);
1926 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1931 while (!do_ssh1_login(in, inlen, ispkt)) {
1934 if (ssh_state == SSH_STATE_CLOSED)
1937 if (cfg.agentfwd && agent_exists()) {
1938 logevent("Requesting agent forwarding");
1939 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1940 do { crReturnV; } while (!ispkt);
1941 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1942 bombout(("Protocol confusion"));
1944 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1945 logevent("Agent forwarding refused");
1947 logevent("Agent forwarding enabled");
1948 ssh_agentfwd_enabled = TRUE;
1952 if (cfg.x11_forward) {
1953 char proto[20], data[64];
1954 logevent("Requesting X11 forwarding");
1955 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
1956 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
1957 PKT_STR, proto, PKT_STR, data,
1960 do { crReturnV; } while (!ispkt);
1961 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1962 bombout(("Protocol confusion"));
1964 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1965 logevent("X11 forwarding refused");
1967 logevent("X11 forwarding enabled");
1968 ssh_X11_fwd_enabled = TRUE;
1973 send_packet(SSH1_CMSG_REQUEST_PTY,
1974 PKT_STR, cfg.termtype,
1975 PKT_INT, rows, PKT_INT, cols,
1976 PKT_INT, 0, PKT_INT, 0,
1979 ssh_state = SSH_STATE_INTERMED;
1980 do { crReturnV; } while (!ispkt);
1981 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1982 bombout(("Protocol confusion"));
1984 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1985 c_write_str("Server refused to allocate pty\r\n");
1986 ssh_editing = ssh_echoing = 1;
1988 logevent("Allocated pty");
1990 ssh_editing = ssh_echoing = 1;
1993 if (cfg.compression) {
1994 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
1995 do { crReturnV; } while (!ispkt);
1996 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1997 bombout(("Protocol confusion"));
1999 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2000 c_write_str("Server refused to compress\r\n");
2002 logevent("Started compression");
2003 ssh1_compressing = TRUE;
2004 zlib_compress_init();
2005 zlib_decompress_init();
2008 if (*cfg.remote_cmd)
2009 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
2011 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
2012 logevent("Started session");
2014 ssh_state = SSH_STATE_SESSION;
2018 ssh_special(TS_EOF);
2020 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
2022 ssh_channels = newtree234(ssh_channelcmp);
2026 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
2027 pktin.type == SSH1_SMSG_STDERR_DATA) {
2028 long len = GET_32BIT(pktin.body);
2029 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
2031 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2032 ssh_state = SSH_STATE_CLOSED;
2033 logevent("Received disconnect request");
2035 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
2036 /* Remote side is trying to open a channel to talk to our
2037 * X-Server. Give them back a local channel number. */
2039 struct ssh_channel *c, *d;
2042 logevent("Received X11 connect request");
2043 /* Refuse if X11 forwarding is disabled. */
2044 if (!ssh_X11_fwd_enabled) {
2045 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2046 PKT_INT, GET_32BIT(pktin.body),
2048 logevent("Rejected X11 connect request");
2050 c = smalloc(sizeof(struct ssh_channel));
2052 if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
2053 logevent("opening X11 forward connection failed");
2055 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2056 PKT_INT, GET_32BIT(pktin.body),
2059 logevent("opening X11 forward connection succeeded");
2060 for (i=1, d = first234(ssh_channels, &e); d; d = next234(&e)) {
2062 break; /* found a free number */
2065 c->remoteid = GET_32BIT(pktin.body);
2068 c->type = CHAN_X11; /* identify channel type */
2069 add234(ssh_channels, c);
2070 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2071 PKT_INT, c->remoteid, PKT_INT, c->localid,
2073 logevent("Opened X11 forward channel");
2076 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
2077 /* Remote side is trying to open a channel to talk to our
2078 * agent. Give them back a local channel number. */
2080 struct ssh_channel *c;
2083 /* Refuse if agent forwarding is disabled. */
2084 if (!ssh_agentfwd_enabled) {
2085 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2086 PKT_INT, GET_32BIT(pktin.body),
2090 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
2092 break; /* found a free number */
2095 c = smalloc(sizeof(struct ssh_channel));
2096 c->remoteid = GET_32BIT(pktin.body);
2099 c->type = CHAN_AGENT; /* identify channel type */
2100 c->u.a.lensofar = 0;
2101 add234(ssh_channels, c);
2102 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2103 PKT_INT, c->remoteid, PKT_INT, c->localid,
2106 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2107 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
2108 /* Remote side closes a channel. */
2109 unsigned i = GET_32BIT(pktin.body);
2110 struct ssh_channel *c;
2111 c = find234(ssh_channels, &i, ssh_channelfind);
2114 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2115 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
2116 if ((c->closes == 0) && (c->type == CHAN_X11)) {
2117 logevent("X11 connection closed");
2118 assert(c->u.x11.s != NULL);
2119 x11_close(c->u.x11.s);
2122 c->closes |= closetype;
2123 if (c->closes == 3) {
2124 del234(ssh_channels, c);
2128 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2129 /* Data sent down one of our channels. */
2130 int i = GET_32BIT(pktin.body);
2131 int len = GET_32BIT(pktin.body+4);
2132 unsigned char *p = pktin.body+8;
2133 struct ssh_channel *c;
2134 c = find234(ssh_channels, &i, ssh_channelfind);
2138 x11_send(c->u.x11.s, p, len);
2141 /* Data for an agent message. Buffer it. */
2143 if (c->u.a.lensofar < 4) {
2144 int l = min(4 - c->u.a.lensofar, len);
2145 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
2146 p += l; len -= l; c->u.a.lensofar += l;
2148 if (c->u.a.lensofar == 4) {
2149 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
2150 c->u.a.message = smalloc(c->u.a.totallen);
2151 memcpy(c->u.a.message, c->u.a.msglen, 4);
2153 if (c->u.a.lensofar >= 4 && len > 0) {
2154 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
2155 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
2156 p += l; len -= l; c->u.a.lensofar += l;
2158 if (c->u.a.lensofar == c->u.a.totallen) {
2159 void *reply, *sentreply;
2161 agent_query(c->u.a.message, c->u.a.totallen,
2166 /* Fake SSH_AGENT_FAILURE. */
2167 sentreply = "\0\0\0\1\5";
2170 send_packet(SSH1_MSG_CHANNEL_DATA,
2171 PKT_INT, c->remoteid,
2173 PKT_DATA, sentreply, replylen,
2177 sfree(c->u.a.message);
2178 c->u.a.lensofar = 0;
2184 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
2185 /* may be from EXEC_SHELL on some servers */
2186 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2187 /* may be from EXEC_SHELL on some servers
2188 * if no pty is available or in other odd cases. Ignore */
2189 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2190 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2192 bombout(("Strange packet received: type %d", pktin.type));
2197 int len = min(inlen, 512);
2198 send_packet(SSH1_CMSG_STDIN_DATA,
2199 PKT_INT, len, PKT_DATA, in, len, PKT_END);
2210 * Utility routine for decoding comma-separated strings in KEXINIT.
2212 static int in_commasep_string(char *needle, char *haystack, int haylen) {
2213 int needlen = strlen(needle);
2216 * Is it at the start of the string?
2218 if (haylen >= needlen && /* haystack is long enough */
2219 !memcmp(needle, haystack, needlen) && /* initial match */
2220 (haylen == needlen || haystack[needlen] == ',')
2221 /* either , or EOS follows */
2225 * If not, search for the next comma and resume after that.
2226 * If no comma found, terminate.
2228 while (haylen > 0 && *haystack != ',')
2229 haylen--, haystack++;
2232 haylen--, haystack++; /* skip over comma itself */
2237 * SSH2 key creation method.
2239 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr, char *keyspace) {
2241 /* First 20 bytes. */
2244 SHA_Bytes(&s, H, 20);
2245 SHA_Bytes(&s, &chr, 1);
2246 SHA_Bytes(&s, sessid, 20);
2247 SHA_Final(&s, keyspace);
2248 /* Next 20 bytes. */
2251 SHA_Bytes(&s, H, 20);
2252 SHA_Bytes(&s, keyspace, 20);
2253 SHA_Final(&s, keyspace+20);
2257 * Handle the SSH2 transport layer.
2259 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
2261 static int i, j, len, nbits;
2263 static Bignum p, g, e, f, K;
2264 static int kex_init_value, kex_reply_value;
2265 static const struct ssh_mac **maclist;
2267 static const struct ssh2_cipher *cscipher_tobe = NULL;
2268 static const struct ssh2_cipher *sccipher_tobe = NULL;
2269 static const struct ssh_mac *csmac_tobe = NULL;
2270 static const struct ssh_mac *scmac_tobe = NULL;
2271 static const struct ssh_compress *cscomp_tobe = NULL;
2272 static const struct ssh_compress *sccomp_tobe = NULL;
2273 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
2274 static int hostkeylen, siglen;
2275 static void *hkey; /* actual host key */
2276 static unsigned char exchange_hash[20];
2277 static unsigned char keyspace[40];
2278 static const struct ssh2_ciphers *preferred_cipher;
2279 static const struct ssh_compress *preferred_comp;
2280 static int first_kex;
2287 * Set up the preferred cipher and compression.
2289 if (cfg.cipher == CIPHER_BLOWFISH) {
2290 preferred_cipher = &ssh2_blowfish;
2291 } else if (cfg.cipher == CIPHER_DES) {
2292 logevent("Single DES not supported in SSH2; using 3DES");
2293 preferred_cipher = &ssh2_3des;
2294 } else if (cfg.cipher == CIPHER_3DES) {
2295 preferred_cipher = &ssh2_3des;
2296 } else if (cfg.cipher == CIPHER_AES) {
2297 preferred_cipher = &ssh2_aes;
2299 /* Shouldn't happen, but we do want to initialise to _something_. */
2300 preferred_cipher = &ssh2_3des;
2302 if (cfg.compression)
2303 preferred_comp = &ssh_zlib;
2305 preferred_comp = &ssh_comp_none;
2308 * Be prepared to work around the buggy MAC problem.
2311 maclist = buggymacs, nmacs = lenof(buggymacs);
2313 maclist = macs, nmacs = lenof(macs);
2317 * Construct and send our key exchange packet.
2319 ssh2_pkt_init(SSH2_MSG_KEXINIT);
2320 for (i = 0; i < 16; i++)
2321 ssh2_pkt_addbyte((unsigned char)random_byte());
2322 /* List key exchange algorithms. */
2323 ssh2_pkt_addstring_start();
2324 for (i = 0; i < lenof(kex_algs); i++) {
2325 ssh2_pkt_addstring_str(kex_algs[i]->name);
2326 if (i < lenof(kex_algs)-1)
2327 ssh2_pkt_addstring_str(",");
2329 /* List server host key algorithms. */
2330 ssh2_pkt_addstring_start();
2331 for (i = 0; i < lenof(hostkey_algs); i++) {
2332 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
2333 if (i < lenof(hostkey_algs)-1)
2334 ssh2_pkt_addstring_str(",");
2336 /* List client->server encryption algorithms. */
2337 ssh2_pkt_addstring_start();
2338 for (i = 0; i < lenof(ciphers)+1; i++) {
2339 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2340 for (j = 0; j < c->nciphers; j++) {
2341 ssh2_pkt_addstring_str(c->list[j]->name);
2342 if (i < lenof(ciphers) || j < c->nciphers-1)
2343 ssh2_pkt_addstring_str(",");
2346 /* List server->client encryption algorithms. */
2347 ssh2_pkt_addstring_start();
2348 for (i = 0; i < lenof(ciphers)+1; i++) {
2349 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2350 for (j = 0; j < c->nciphers; j++) {
2351 ssh2_pkt_addstring_str(c->list[j]->name);
2352 if (i < lenof(ciphers) || j < c->nciphers-1)
2353 ssh2_pkt_addstring_str(",");
2356 /* List client->server MAC algorithms. */
2357 ssh2_pkt_addstring_start();
2358 for (i = 0; i < nmacs; i++) {
2359 ssh2_pkt_addstring_str(maclist[i]->name);
2361 ssh2_pkt_addstring_str(",");
2363 /* List server->client MAC algorithms. */
2364 ssh2_pkt_addstring_start();
2365 for (i = 0; i < nmacs; i++) {
2366 ssh2_pkt_addstring_str(maclist[i]->name);
2368 ssh2_pkt_addstring_str(",");
2370 /* List client->server compression algorithms. */
2371 ssh2_pkt_addstring_start();
2372 for (i = 0; i < lenof(compressions)+1; i++) {
2373 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2374 ssh2_pkt_addstring_str(c->name);
2375 if (i < lenof(compressions))
2376 ssh2_pkt_addstring_str(",");
2378 /* List server->client compression algorithms. */
2379 ssh2_pkt_addstring_start();
2380 for (i = 0; i < lenof(compressions)+1; i++) {
2381 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2382 ssh2_pkt_addstring_str(c->name);
2383 if (i < lenof(compressions))
2384 ssh2_pkt_addstring_str(",");
2386 /* List client->server languages. Empty list. */
2387 ssh2_pkt_addstring_start();
2388 /* List server->client languages. Empty list. */
2389 ssh2_pkt_addstring_start();
2390 /* First KEX packet does _not_ follow, because we're not that brave. */
2391 ssh2_pkt_addbool(FALSE);
2393 ssh2_pkt_adduint32(0);
2395 exhash = exhashbase;
2396 sha_string(&exhash, pktout.data+5, pktout.length-5);
2400 if (!ispkt) crWaitUntil(ispkt);
2401 sha_string(&exhash, pktin.data+5, pktin.length-5);
2404 * Now examine the other side's KEXINIT to see what we're up
2407 if (pktin.type != SSH2_MSG_KEXINIT) {
2408 bombout(("expected key exchange packet from server"));
2411 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
2412 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
2413 pktin.savedpos += 16; /* skip garbage cookie */
2414 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
2415 for (i = 0; i < lenof(kex_algs); i++) {
2416 if (in_commasep_string(kex_algs[i]->name, str, len)) {
2421 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
2422 for (i = 0; i < lenof(hostkey_algs); i++) {
2423 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
2424 hostkey = hostkey_algs[i];
2428 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
2429 for (i = 0; i < lenof(ciphers)+1; i++) {
2430 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2431 for (j = 0; j < c->nciphers; j++) {
2432 if (in_commasep_string(c->list[j]->name, str, len)) {
2433 cscipher_tobe = c->list[j];
2440 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
2441 for (i = 0; i < lenof(ciphers)+1; i++) {
2442 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2443 for (j = 0; j < c->nciphers; j++) {
2444 if (in_commasep_string(c->list[j]->name, str, len)) {
2445 sccipher_tobe = c->list[j];
2452 ssh2_pkt_getstring(&str, &len); /* client->server mac */
2453 for (i = 0; i < nmacs; i++) {
2454 if (in_commasep_string(maclist[i]->name, str, len)) {
2455 csmac_tobe = maclist[i];
2459 ssh2_pkt_getstring(&str, &len); /* server->client mac */
2460 for (i = 0; i < nmacs; i++) {
2461 if (in_commasep_string(maclist[i]->name, str, len)) {
2462 scmac_tobe = maclist[i];
2466 ssh2_pkt_getstring(&str, &len); /* client->server compression */
2467 for (i = 0; i < lenof(compressions)+1; i++) {
2468 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2469 if (in_commasep_string(c->name, str, len)) {
2474 ssh2_pkt_getstring(&str, &len); /* server->client compression */
2475 for (i = 0; i < lenof(compressions)+1; i++) {
2476 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2477 if (in_commasep_string(c->name, str, len)) {
2484 * If we're doing Diffie-Hellman group exchange, start by
2485 * requesting a group.
2487 if (kex == &ssh_diffiehellman_gex) {
2490 logevent("Doing Diffie-Hellman group exchange");
2492 * Work out number of bits. We start with the maximum key
2493 * length of either cipher...
2495 csbits = cscipher_tobe->keylen;
2496 scbits = sccipher_tobe->keylen;
2497 nbits = (csbits > scbits ? csbits : scbits);
2498 /* The keys only have 160-bit entropy, since they're based on
2499 * a SHA-1 hash. So cap the key size at 160 bits. */
2500 if (nbits > 160) nbits = 160;
2502 * ... and then work out how big a DH group we will need to
2503 * allow that much data.
2505 nbits = 512 << ((nbits-1) / 64);
2506 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
2507 ssh2_pkt_adduint32(nbits);
2511 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
2512 bombout(("expected key exchange group packet from server"));
2515 p = ssh2_pkt_getmp();
2516 g = ssh2_pkt_getmp();
2517 dh_setup_group(p, g);
2518 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
2519 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
2522 kex_init_value = SSH2_MSG_KEXDH_INIT;
2523 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
2526 logevent("Doing Diffie-Hellman key exchange");
2528 * Now generate and send e for Diffie-Hellman.
2531 ssh2_pkt_init(kex_init_value);
2536 if (pktin.type != kex_reply_value) {
2537 bombout(("expected key exchange reply packet from server"));
2540 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2541 f = ssh2_pkt_getmp();
2542 ssh2_pkt_getstring(&sigdata, &siglen);
2546 sha_string(&exhash, hostkeydata, hostkeylen);
2547 if (kex == &ssh_diffiehellman_gex) {
2548 sha_uint32(&exhash, nbits);
2549 sha_mpint(&exhash, p);
2550 sha_mpint(&exhash, g);
2552 sha_mpint(&exhash, e);
2553 sha_mpint(&exhash, f);
2554 sha_mpint(&exhash, K);
2555 SHA_Final(&exhash, exchange_hash);
2560 debug(("Exchange hash is:\r\n"));
2561 for (i = 0; i < 20; i++)
2562 debug((" %02x", exchange_hash[i]));
2566 hkey = hostkey->newkey(hostkeydata, hostkeylen);
2567 if (!hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
2568 bombout(("Server failed host key check"));
2573 * Expect SSH2_MSG_NEWKEYS from server.
2576 if (pktin.type != SSH2_MSG_NEWKEYS) {
2577 bombout(("expected new-keys packet from server"));
2582 * Authenticate remote host: verify host key. (We've already
2583 * checked the signature of the exchange hash.)
2585 keystr = hostkey->fmtkey(hkey);
2586 fingerprint = hostkey->fingerprint(hkey);
2587 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
2588 keystr, fingerprint);
2589 if (first_kex) { /* don't bother logging this in rekeys */
2590 logevent("Host key fingerprint is:");
2591 logevent(fingerprint);
2595 hostkey->freekey(hkey);
2598 * Send SSH2_MSG_NEWKEYS.
2600 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2604 * Create and initialise session keys.
2606 cscipher = cscipher_tobe;
2607 sccipher = sccipher_tobe;
2610 cscomp = cscomp_tobe;
2611 sccomp = sccomp_tobe;
2612 cscomp->compress_init();
2613 sccomp->decompress_init();
2615 * Set IVs after keys. Here we use the exchange hash from the
2616 * _first_ key exchange.
2619 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
2620 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
2621 cscipher->setcskey(keyspace);
2622 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
2623 sccipher->setsckey(keyspace);
2624 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
2625 cscipher->setcsiv(keyspace);
2626 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
2627 sccipher->setsciv(keyspace);
2628 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
2629 csmac->setcskey(keyspace);
2630 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
2631 scmac->setsckey(keyspace);
2634 * If this is the first key exchange phase, we must pass the
2635 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2636 * wants to see it but because it will need time to initialise
2637 * itself before it sees an actual packet. In subsequent key
2638 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2639 * it would only confuse the layer above.
2647 * Now we're encrypting. Begin returning 1 to the protocol main
2648 * function so that other things can run on top of the
2649 * transport. If we ever see a KEXINIT, we must go back to the
2652 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
2655 logevent("Server initiated key re-exchange");
2656 goto begin_key_exchange;
2662 * Add data to an SSH2 channel output buffer.
2664 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len) {
2665 if (c->v2.outbufsize <
2666 c->v2.outbuflen + len) {
2668 c->v2.outbuflen + len + 1024;
2669 c->v2.outbuffer = srealloc(c->v2.outbuffer,
2672 memcpy(c->v2.outbuffer + c->v2.outbuflen,
2674 c->v2.outbuflen += len;
2678 * Attempt to send data on an SSH2 channel.
2680 static void ssh2_try_send(struct ssh_channel *c) {
2681 while (c->v2.remwindow > 0 &&
2682 c->v2.outbuflen > 0) {
2683 unsigned len = c->v2.remwindow;
2684 if (len > c->v2.outbuflen)
2685 len = c->v2.outbuflen;
2686 if (len > c->v2.remmaxpkt)
2687 len = c->v2.remmaxpkt;
2688 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2689 ssh2_pkt_adduint32(c->remoteid);
2690 ssh2_pkt_addstring_start();
2691 ssh2_pkt_addstring_data(c->v2.outbuffer, len);
2693 c->v2.outbuflen -= len;
2694 memmove(c->v2.outbuffer, c->v2.outbuffer+len,
2696 c->v2.remwindow -= len;
2701 * Handle the SSH2 userauth and connection layers.
2703 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2705 static unsigned long remote_winsize;
2706 static unsigned long remote_maxpkt;
2708 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE, AUTH_PASSWORD
2712 AUTH_TYPE_PUBLICKEY,
2713 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
2714 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
2717 static int gotit, need_pw, can_pubkey, can_passwd;
2718 static int tried_pubkey_config, tried_agent;
2719 static int we_are_in;
2720 static char username[100];
2721 static char pwprompt[200];
2722 static char password[100];
2727 * Request userauth protocol, and await a response to it.
2729 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2730 ssh2_pkt_addstring("ssh-userauth");
2732 crWaitUntilV(ispkt);
2733 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2734 bombout(("Server refused user authentication protocol"));
2739 * We repeat this whole loop, including the username prompt,
2740 * until we manage a successful authentication. If the user
2741 * types the wrong _password_, they are sent back to the
2742 * beginning to try another username. (If they specify a
2743 * username in the config, they are never asked, even if they
2744 * do give a wrong password.)
2746 * I think this best serves the needs of
2748 * - the people who have no configuration, no keys, and just
2749 * want to try repeated (username,password) pairs until they
2750 * type both correctly
2752 * - people who have keys and configuration but occasionally
2753 * need to fall back to passwords
2755 * - people with a key held in Pageant, who might not have
2756 * logged in to a particular machine before; so they want to
2757 * type a username, and then _either_ their key will be
2758 * accepted, _or_ they will type a password. If they mistype
2759 * the username they will want to be able to get back and
2770 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2771 c_write_str("login as: ");
2774 crWaitUntilV(!ispkt);
2775 while (inlen--) switch (c = *in++) {
2782 c_write_str("\b \b");
2788 c_write_str("\b \b");
2797 if (((c >= ' ' && c <= '~') ||
2798 ((unsigned char)c >= 160)) && pos < 40) {
2799 username[pos++] = c;
2805 c_write_str("\r\n");
2806 username[strcspn(username, "\n\r")] = '\0';
2809 strncpy(username, cfg.username, 99);
2810 username[99] = '\0';
2811 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
2812 sprintf(stuff, "Using username \"%s\".\r\n", username);
2818 * Send an authentication request using method "none": (a)
2819 * just in case it succeeds, and (b) so that we know what
2820 * authentication methods we can usefully try next.
2822 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2823 ssh2_pkt_addstring(username);
2824 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2825 ssh2_pkt_addstring("none"); /* method */
2827 type = AUTH_TYPE_NONE;
2831 tried_pubkey_config = FALSE;
2832 tried_agent = FALSE;
2836 * Wait for the result of the last authentication request.
2839 crWaitUntilV(ispkt);
2840 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
2841 /* FIXME: should support this */
2842 crWaitUntilV(ispkt);
2844 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
2845 logevent("Access granted");
2850 if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
2851 bombout(("Strange packet received during authentication: type %d",
2858 * OK, we're now sitting on a USERAUTH_FAILURE message, so
2859 * we can look at the string in it and know what we can
2860 * helpfully try next.
2865 ssh2_pkt_getstring(&methods, &methlen);
2866 if (!ssh2_pkt_getbool()) {
2868 * We have received an unequivocal Access
2869 * Denied. This can translate to a variety of
2872 * - if we'd just tried "none" authentication,
2873 * it's not worth printing anything at all
2875 * - if we'd just tried a public key _offer_,
2876 * the message should be "Server refused our
2877 * key" (or no message at all if the key
2878 * came from Pageant)
2880 * - if we'd just tried anything else, the
2881 * message really should be "Access denied".
2883 * Additionally, if we'd just tried password
2884 * authentication, we should break out of this
2885 * whole loop so as to go back to the username
2888 if (type == AUTH_TYPE_NONE) {
2890 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
2891 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
2892 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
2893 c_write_str("Server refused our key\r\n");
2894 logevent("Server refused public key");
2896 c_write_str("Access denied\r\n");
2897 logevent("Access denied");
2898 if (type == AUTH_TYPE_PASSWORD) {
2904 c_write_str("Further authentication required\r\n");
2905 logevent("Further authentication required");
2908 can_pubkey = in_commasep_string("publickey", methods, methlen);
2909 can_passwd = in_commasep_string("password", methods, methlen);
2914 if (!method && can_pubkey && agent_exists && !tried_agent) {
2916 * Attempt public-key authentication using Pageant.
2918 static unsigned char request[5], *response, *p;
2919 static int responselen;
2920 static int i, nkeys;
2921 static int authed = FALSE;
2926 logevent("Pageant is running. Requesting keys.");
2928 /* Request the keys held by the agent. */
2929 PUT_32BIT(request, 1);
2930 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
2931 agent_query(request, 5, &r, &responselen);
2932 response = (unsigned char *)r;
2935 nkeys = GET_32BIT(p); p += 4;
2936 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
2938 for (i = 0; i < nkeys; i++) {
2939 static char *pkblob, *alg, *commentp;
2940 static int pklen, alglen, commentlen;
2941 static int siglen, retlen, len;
2942 static char *q, *agentreq, *ret;
2944 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
2946 pklen = GET_32BIT(p); p += 4;
2947 pkblob = p; p += pklen;
2948 alglen = GET_32BIT(pkblob);
2950 commentlen = GET_32BIT(p); p += 4;
2951 commentp = p; p += commentlen;
2952 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2953 ssh2_pkt_addstring(username);
2954 ssh2_pkt_addstring("ssh-connection");/* service requested */
2955 ssh2_pkt_addstring("publickey");/* method */
2956 ssh2_pkt_addbool(FALSE); /* no signature included */
2957 ssh2_pkt_addstring_start();
2958 ssh2_pkt_addstring_data(alg, alglen);
2959 ssh2_pkt_addstring_start();
2960 ssh2_pkt_addstring_data(pkblob, pklen);
2963 crWaitUntilV(ispkt);
2964 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
2965 logevent("Key refused");
2969 c_write_str("Authenticating with public key \"");
2970 c_write(commentp, commentlen);
2971 c_write_str("\" from agent\r\n");
2974 * Server is willing to accept the key.
2975 * Construct a SIGN_REQUEST.
2977 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2978 ssh2_pkt_addstring(username);
2979 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2980 ssh2_pkt_addstring("publickey"); /* method */
2981 ssh2_pkt_addbool(TRUE);
2982 ssh2_pkt_addstring_start();
2983 ssh2_pkt_addstring_data(alg, alglen);
2984 ssh2_pkt_addstring_start();
2985 ssh2_pkt_addstring_data(pkblob, pklen);
2987 siglen = pktout.length - 5 + 4 + 20;
2988 len = 1; /* message type */
2989 len += 4 + pklen; /* key blob */
2990 len += 4 + siglen; /* data to sign */
2991 len += 4; /* flags */
2992 agentreq = smalloc(4 + len);
2993 PUT_32BIT(agentreq, len);
2995 *q++ = SSH2_AGENTC_SIGN_REQUEST;
2996 PUT_32BIT(q, pklen); q += 4;
2997 memcpy(q, pkblob, pklen); q += pklen;
2998 PUT_32BIT(q, siglen); q += 4;
2999 /* Now the data to be signed... */
3000 PUT_32BIT(q, 20); q += 4;
3001 memcpy(q, ssh2_session_id, 20); q += 20;
3002 memcpy(q, pktout.data+5, pktout.length-5);
3003 q += pktout.length-5;
3004 /* And finally the (zero) flags word. */
3006 agent_query(agentreq, len+4, &ret, &retlen);
3009 if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
3010 logevent("Sending Pageant's response");
3011 ssh2_pkt_addstring_start();
3012 ssh2_pkt_addstring_data(ret+9, GET_32BIT(ret+5));
3017 logevent("Pageant failed to answer challenge");
3027 if (!method && can_pubkey && *cfg.keyfile && !tried_pubkey_config) {
3028 unsigned char *pub_blob;
3029 char *algorithm, *comment;
3032 tried_pubkey_config = TRUE;
3035 * Try the public key supplied in the configuration.
3037 * First, offer the public blob to see if the server is
3038 * willing to accept it.
3040 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
3043 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3044 ssh2_pkt_addstring(username);
3045 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3046 ssh2_pkt_addstring("publickey");/* method */
3047 ssh2_pkt_addbool(FALSE); /* no signature included */
3048 ssh2_pkt_addstring(algorithm);
3049 ssh2_pkt_addstring_start();
3050 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
3052 logevent("Offered public key"); /* FIXME */
3054 crWaitUntilV(ispkt);
3055 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3057 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
3058 continue; /* key refused; give up on it */
3061 logevent("Offer of public key accepted");
3063 * Actually attempt a serious authentication using
3066 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
3067 sprintf(pwprompt, "Passphrase for key \"%.100s\": ", comment);
3072 c_write_str("Authenticating with public key \"");
3073 c_write_str(comment);
3074 c_write_str("\"\r\n");
3075 method = AUTH_PUBLICKEY_FILE;
3079 if (!method && can_passwd) {
3080 method = AUTH_PASSWORD;
3081 sprintf(pwprompt, "%.90s@%.90s's password: ", username, savedhost);
3086 if (ssh_get_password) {
3087 if (!ssh_get_password(pwprompt, password, sizeof(password))) {
3089 * get_password failed to get a password (for
3090 * example because one was supplied on the command
3091 * line which has already failed to work).
3094 logevent("No more passwords to try");
3095 ssh_state = SSH_STATE_CLOSED;
3102 c_write_str(pwprompt);
3107 crWaitUntilV(!ispkt);
3108 while (inlen--) switch (c = *in++) {
3125 if (((c >= ' ' && c <= '~') ||
3126 ((unsigned char)c >= 160)) && pos < 40)
3127 password[pos++] = c;
3131 c_write_str("\r\n");
3135 if (method == AUTH_PUBLICKEY_FILE) {
3137 * We have our passphrase. Now try the actual authentication.
3139 struct ssh2_userkey *key;
3141 key = ssh2_load_userkey(cfg.keyfile, password);
3142 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
3143 if (key == SSH2_WRONG_PASSPHRASE) {
3144 c_write_str("Wrong passphrase\r\n");
3145 tried_pubkey_config = FALSE;
3147 c_write_str("Unable to load private key\r\n");
3148 tried_pubkey_config = TRUE;
3150 /* Send a spurious AUTH_NONE to return to the top. */
3151 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3152 ssh2_pkt_addstring(username);
3153 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3154 ssh2_pkt_addstring("none"); /* method */
3156 type = AUTH_TYPE_NONE;
3158 unsigned char *blob, *sigdata;
3159 int blob_len, sigdata_len;
3162 * We have loaded the private key and the server
3163 * has announced that it's willing to accept it.
3164 * Hallelujah. Generate a signature and send it.
3166 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3167 ssh2_pkt_addstring(username);
3168 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3169 ssh2_pkt_addstring("publickey"); /* method */
3170 ssh2_pkt_addbool(TRUE);
3171 ssh2_pkt_addstring(key->alg->name);
3172 blob = key->alg->public_blob(key->data, &blob_len);
3173 ssh2_pkt_addstring_start();
3174 ssh2_pkt_addstring_data(blob, blob_len);
3178 * The data to be signed is:
3182 * followed by everything so far placed in the
3185 sigdata_len = pktout.length - 5 + 4 + 20;
3186 sigdata = smalloc(sigdata_len);
3187 PUT_32BIT(sigdata, 20);
3188 memcpy(sigdata+4, ssh2_session_id, 20);
3189 memcpy(sigdata+24, pktout.data+5, pktout.length-5);
3190 blob = key->alg->sign(key->data, sigdata, sigdata_len, &blob_len);
3191 ssh2_pkt_addstring_start();
3192 ssh2_pkt_addstring_data(blob, blob_len);
3197 type = AUTH_TYPE_PUBLICKEY;
3199 } else if (method == AUTH_PASSWORD) {
3201 * We send the password packet lumped tightly together with
3202 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3203 * string long enough to make the total length of the two
3204 * packets constant. This should ensure that a passive
3205 * listener doing traffic analyis can't work out the length
3208 * For this to work, we need an assumption about the
3209 * maximum length of the password packet. I think 256 is
3210 * pretty conservative. Anyone using a password longer than
3211 * that probably doesn't have much to worry about from
3212 * people who find out how long their password is!
3214 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3215 ssh2_pkt_addstring(username);
3216 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3217 ssh2_pkt_addstring("password");
3218 ssh2_pkt_addbool(FALSE);
3219 ssh2_pkt_addstring(password);
3222 * We'll include a string that's an exact multiple of the
3223 * cipher block size. If the cipher is NULL for some
3224 * reason, we don't do this trick at all because we gain
3229 ssh2_pkt_init(SSH2_MSG_IGNORE);
3230 ssh2_pkt_addstring_start();
3231 for (i = deferred_len; i <= 256; i += cscipher->blksize) {
3232 for (j = 0; j < cscipher->blksize; j++) {
3233 char c = (char)random_byte();
3234 ssh2_pkt_addstring_data(&c, 1);
3239 ssh_pkt_defersend();
3240 logevent("Sent password");
3241 type = AUTH_TYPE_PASSWORD;
3243 c_write_str("No supported authentication methods left to try!\r\n");
3244 logevent("No supported authentications offered. Disconnecting");
3245 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3246 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3247 ssh2_pkt_addstring("No supported authentication methods available");
3248 ssh2_pkt_addstring("en"); /* language tag */
3250 ssh_state = SSH_STATE_CLOSED;
3254 } while (!we_are_in);
3257 * Now we're authenticated for the connection protocol. The
3258 * connection protocol will automatically have started at this
3259 * point; there's no need to send SERVICE_REQUEST.
3263 * So now create a channel with a session in it.
3265 mainchan = smalloc(sizeof(struct ssh_channel));
3266 mainchan->localid = 100; /* as good as any */
3267 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
3268 ssh2_pkt_addstring("session");
3269 ssh2_pkt_adduint32(mainchan->localid);
3270 ssh2_pkt_adduint32(0x8000UL); /* our window size */
3271 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
3273 crWaitUntilV(ispkt);
3274 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
3275 bombout(("Server refused to open a session"));
3277 /* FIXME: error data comes back in FAILURE packet */
3279 if (ssh2_pkt_getuint32() != mainchan->localid) {
3280 bombout(("Server's channel confirmation cited wrong channel"));
3283 mainchan->remoteid = ssh2_pkt_getuint32();
3284 mainchan->type = CHAN_MAINSESSION;
3285 mainchan->closes = 0;
3286 mainchan->v2.remwindow = ssh2_pkt_getuint32();
3287 mainchan->v2.remmaxpkt = ssh2_pkt_getuint32();
3288 mainchan->v2.outbuffer = NULL;
3289 mainchan->v2.outbuflen = mainchan->v2.outbufsize = 0;
3290 ssh_channels = newtree234(ssh_channelcmp);
3291 add234(ssh_channels, mainchan);
3292 logevent("Opened channel for session");
3295 * Potentially enable X11 forwarding.
3297 if (cfg.x11_forward) {
3298 char proto[20], data[64];
3299 logevent("Requesting X11 forwarding");
3300 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3301 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3302 ssh2_pkt_adduint32(mainchan->remoteid);
3303 ssh2_pkt_addstring("x11-req");
3304 ssh2_pkt_addbool(1); /* want reply */
3305 ssh2_pkt_addbool(0); /* many connections */
3306 ssh2_pkt_addstring(proto);
3307 ssh2_pkt_addstring(data);
3308 ssh2_pkt_adduint32(0); /* screen number */
3312 crWaitUntilV(ispkt);
3313 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3314 unsigned i = ssh2_pkt_getuint32();
3315 struct ssh_channel *c;
3316 c = find234(ssh_channels, &i, ssh_channelfind);
3318 continue; /* nonexistent channel */
3319 c->v2.remwindow += ssh2_pkt_getuint32();
3321 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3323 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3324 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3325 bombout(("Server got confused by X11 forwarding request"));
3328 logevent("X11 forwarding refused");
3330 logevent("X11 forwarding enabled");
3331 ssh_X11_fwd_enabled = TRUE;
3336 * Potentially enable agent forwarding.
3338 if (cfg.agentfwd && agent_exists()) {
3339 char proto[20], data[64];
3340 logevent("Requesting OpenSSH-style agent forwarding");
3341 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3342 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3343 ssh2_pkt_adduint32(mainchan->remoteid);
3344 ssh2_pkt_addstring("auth-agent-req@openssh.com");
3345 ssh2_pkt_addbool(1); /* want reply */
3349 crWaitUntilV(ispkt);
3350 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3351 unsigned i = ssh2_pkt_getuint32();
3352 struct ssh_channel *c;
3353 c = find234(ssh_channels, &i, ssh_channelfind);
3355 continue; /* nonexistent channel */
3356 c->v2.remwindow += ssh2_pkt_getuint32();
3358 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3360 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3361 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3362 bombout(("Server got confused by agent forwarding request"));
3365 logevent("Agent forwarding refused");
3367 logevent("Agent forwarding enabled");
3368 ssh_agentfwd_enabled = TRUE;
3373 * Now allocate a pty for the session.
3376 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3377 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
3378 ssh2_pkt_addstring("pty-req");
3379 ssh2_pkt_addbool(1); /* want reply */
3380 ssh2_pkt_addstring(cfg.termtype);
3381 ssh2_pkt_adduint32(cols);
3382 ssh2_pkt_adduint32(rows);
3383 ssh2_pkt_adduint32(0); /* pixel width */
3384 ssh2_pkt_adduint32(0); /* pixel height */
3385 ssh2_pkt_addstring_start();
3386 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3388 ssh_state = SSH_STATE_INTERMED;
3391 crWaitUntilV(ispkt);
3392 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3393 unsigned i = ssh2_pkt_getuint32();
3394 struct ssh_channel *c;
3395 c = find234(ssh_channels, &i, ssh_channelfind);
3397 continue; /* nonexistent channel */
3398 c->v2.remwindow += ssh2_pkt_getuint32();
3400 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3402 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3403 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3404 bombout(("Server got confused by pty request"));
3407 c_write_str("Server refused to allocate pty\r\n");
3408 ssh_editing = ssh_echoing = 1;
3410 logevent("Allocated pty");
3413 ssh_editing = ssh_echoing = 1;
3417 * Start a shell or a remote command.
3419 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3420 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
3421 if (cfg.ssh_subsys) {
3422 ssh2_pkt_addstring("subsystem");
3423 ssh2_pkt_addbool(1); /* want reply */
3424 ssh2_pkt_addstring(cfg.remote_cmd);
3425 } else if (*cfg.remote_cmd) {
3426 ssh2_pkt_addstring("exec");
3427 ssh2_pkt_addbool(1); /* want reply */
3428 ssh2_pkt_addstring(cfg.remote_cmd);
3430 ssh2_pkt_addstring("shell");
3431 ssh2_pkt_addbool(1); /* want reply */
3435 crWaitUntilV(ispkt);
3436 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3437 unsigned i = ssh2_pkt_getuint32();
3438 struct ssh_channel *c;
3439 c = find234(ssh_channels, &i, ssh_channelfind);
3441 continue; /* nonexistent channel */
3442 c->v2.remwindow += ssh2_pkt_getuint32();
3444 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3445 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3446 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3447 bombout(("Server got confused by shell/command request"));
3450 bombout(("Server refused to start a shell/command"));
3453 logevent("Started a shell/command");
3456 ssh_state = SSH_STATE_SESSION;
3460 ssh_special(TS_EOF);
3465 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
3468 static int try_send;
3472 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
3473 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
3476 unsigned i = ssh2_pkt_getuint32();
3477 struct ssh_channel *c;
3478 c = find234(ssh_channels, &i, ssh_channelfind);
3480 continue; /* nonexistent channel */
3481 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
3482 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
3483 continue; /* extended but not stderr */
3484 ssh2_pkt_getstring(&data, &length);
3487 case CHAN_MAINSESSION:
3488 from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
3492 x11_send(c->u.x11.s, data, length);
3495 while (length > 0) {
3496 if (c->u.a.lensofar < 4) {
3497 int l = min(4 - c->u.a.lensofar, length);
3498 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
3499 data += l; length -= l; c->u.a.lensofar += l;
3501 if (c->u.a.lensofar == 4) {
3502 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
3503 c->u.a.message = smalloc(c->u.a.totallen);
3504 memcpy(c->u.a.message, c->u.a.msglen, 4);
3506 if (c->u.a.lensofar >= 4 && length > 0) {
3507 int l = min(c->u.a.totallen - c->u.a.lensofar,
3509 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
3510 data += l; length -= l; c->u.a.lensofar += l;
3512 if (c->u.a.lensofar == c->u.a.totallen) {
3513 void *reply, *sentreply;
3515 agent_query(c->u.a.message, c->u.a.totallen,
3520 /* Fake SSH_AGENT_FAILURE. */
3521 sentreply = "\0\0\0\1\5";
3524 ssh2_add_channel_data(c, sentreply, replylen);
3528 sfree(c->u.a.message);
3529 c->u.a.lensofar = 0;
3535 * Enlarge the window again at the remote
3536 * side, just in case it ever runs down and
3537 * they fail to send us any more data.
3539 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3540 ssh2_pkt_adduint32(c->remoteid);
3541 ssh2_pkt_adduint32(length);
3544 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
3545 ssh_state = SSH_STATE_CLOSED;
3546 logevent("Received disconnect message");
3548 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
3549 continue; /* exit status et al; ignore (FIXME?) */
3550 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
3551 unsigned i = ssh2_pkt_getuint32();
3552 struct ssh_channel *c;
3554 c = find234(ssh_channels, &i, ssh_channelfind);
3556 continue; /* nonexistent channel */
3558 if (c->type == CHAN_X11) {
3560 * Remote EOF on an X11 channel means we should
3561 * wrap up and close the channel ourselves.
3563 x11_close(c->u.x11.s);
3565 } else if (c->type == CHAN_AGENT) {
3568 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
3569 unsigned i = ssh2_pkt_getuint32();
3570 struct ssh_channel *c;
3573 c = find234(ssh_channels, &i, ssh_channelfind);
3575 continue; /* nonexistent channel */
3576 if (c->closes == 0) {
3577 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3578 ssh2_pkt_adduint32(c->remoteid);
3581 /* Do pre-close processing on the channel. */
3583 case CHAN_MAINSESSION:
3584 break; /* nothing to see here, move along */
3590 del234(ssh_channels, c);
3591 sfree(c->v2.outbuffer);
3595 * See if that was the last channel left open.
3597 c = first234(ssh_channels, &e);
3599 logevent("All channels closed. Disconnecting");
3600 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3601 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3602 ssh2_pkt_addstring("All open channels closed");
3603 ssh2_pkt_addstring("en"); /* language tag */
3605 ssh_state = SSH_STATE_CLOSED;
3608 continue; /* remote sends close; ignore (FIXME) */
3609 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3610 unsigned i = ssh2_pkt_getuint32();
3611 struct ssh_channel *c;
3612 c = find234(ssh_channels, &i, ssh_channelfind);
3614 continue; /* nonexistent channel */
3615 mainchan->v2.remwindow += ssh2_pkt_getuint32();
3617 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
3621 struct ssh_channel *c;
3622 ssh2_pkt_getstring(&type, &typelen);
3623 c = smalloc(sizeof(struct ssh_channel));
3625 if (typelen == 3 && !memcmp(type, "x11", 3)) {
3626 if (!ssh_X11_fwd_enabled)
3627 error = "X11 forwarding is not enabled";
3628 else if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
3629 error = "Unable to open an X11 connection";
3633 } else if (typelen == 22 &&
3634 !memcmp(type, "auth-agent@openssh.com", 3)) {
3635 if (!ssh_agentfwd_enabled)
3636 error = "Agent forwarding is not enabled";
3638 c->type = CHAN_AGENT; /* identify channel type */
3639 c->u.a.lensofar = 0;
3642 error = "Unsupported channel type requested";
3645 c->remoteid = ssh2_pkt_getuint32();
3647 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
3648 ssh2_pkt_adduint32(c->remoteid);
3649 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
3650 ssh2_pkt_addstring(error);
3651 ssh2_pkt_addstring("en"); /* language tag */
3655 struct ssh_channel *d;
3659 for (i=1, d = first234(ssh_channels, &e); d;
3662 break; /* found a free number */
3667 c->v2.remwindow = ssh2_pkt_getuint32();
3668 c->v2.remmaxpkt = ssh2_pkt_getuint32();
3669 c->v2.outbuffer = NULL;
3670 c->v2.outbuflen = c->v2.outbufsize = 0;
3671 add234(ssh_channels, c);
3672 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
3673 ssh2_pkt_adduint32(c->remoteid);
3674 ssh2_pkt_adduint32(c->localid);
3675 ssh2_pkt_adduint32(0x8000UL); /* our window size */
3676 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
3680 bombout(("Strange packet received: type %d", pktin.type));
3685 * We have spare data. Add it to the channel buffer.
3687 ssh2_add_channel_data(mainchan, in, inlen);
3692 struct ssh_channel *c;
3694 * Try to send data on all channels if we can.
3696 for (c = first234(ssh_channels, &e); c; c = next234(&e))
3705 * Handle the top-level SSH2 protocol.
3707 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
3709 if (do_ssh2_transport(in, inlen, ispkt) == 0)
3711 do_ssh2_authconn(in, inlen, ispkt);
3715 * Called to set up the connection.
3717 * Returns an error message, or NULL on success.
3719 static char *ssh_init (char *host, int port, char **realhost) {
3723 if(crypto_startup() == 0)
3724 return "Microsoft high encryption pack not installed!";
3731 p = connect_to_host(host, port, realhost);
3739 * Called to send data down the Telnet connection.
3741 static void ssh_send (char *buf, int len) {
3742 if (s == NULL || ssh_protocol == NULL)
3745 ssh_protocol(buf, len, 0);
3749 * Called to set the size of the window from SSH's POV.
3751 static void ssh_size(void) {
3752 switch (ssh_state) {
3753 case SSH_STATE_BEFORE_SIZE:
3754 case SSH_STATE_PREPACKET:
3755 case SSH_STATE_CLOSED:
3756 break; /* do nothing */
3757 case SSH_STATE_INTERMED:
3758 size_needed = TRUE; /* buffer for later */
3760 case SSH_STATE_SESSION:
3762 if (ssh_version == 1) {
3763 send_packet(SSH1_CMSG_WINDOW_SIZE,
3764 PKT_INT, rows, PKT_INT, cols,
3765 PKT_INT, 0, PKT_INT, 0, PKT_END);
3767 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3768 ssh2_pkt_adduint32(mainchan->remoteid);
3769 ssh2_pkt_addstring("window-change");
3770 ssh2_pkt_addbool(0);
3771 ssh2_pkt_adduint32(cols);
3772 ssh2_pkt_adduint32(rows);
3773 ssh2_pkt_adduint32(0);
3774 ssh2_pkt_adduint32(0);
3783 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3784 * can send an EOF and collect resulting output (e.g. `plink
3787 static void ssh_special (Telnet_Special code) {
3788 if (code == TS_EOF) {
3789 if (ssh_state != SSH_STATE_SESSION) {
3791 * Buffer the EOF in case we are pre-SESSION, so we can
3792 * send it as soon as we reach SESSION.
3798 if (ssh_version == 1) {
3799 send_packet(SSH1_CMSG_EOF, PKT_END);
3801 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
3802 ssh2_pkt_adduint32(mainchan->remoteid);
3805 logevent("Sent EOF message");
3806 } else if (code == TS_PING) {
3807 if (ssh_state == SSH_STATE_CLOSED || ssh_state == SSH_STATE_PREPACKET)
3809 if (ssh_version == 1) {
3810 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
3812 ssh2_pkt_init(SSH2_MSG_IGNORE);
3813 ssh2_pkt_addstring_start();
3821 static Socket ssh_socket(void) { return s; }
3823 static int ssh_sendok(void) { return ssh_send_ok; }
3825 static int ssh_ldisc(int option) {
3826 if (option == LD_ECHO) return ssh_echoing;
3827 if (option == LD_EDIT) return ssh_editing;
3831 Backend ssh_backend = {