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 */
126 * Various remote-bug flags.
128 #define BUG_CHOKES_ON_SSH1_IGNORE 1
129 #define BUG_SSH2_HMAC 2
131 #define GET_32BIT(cp) \
132 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
133 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
134 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
135 ((unsigned long)(unsigned char)(cp)[3]))
137 #define PUT_32BIT(cp, value) { \
138 (cp)[0] = (unsigned char)((value) >> 24); \
139 (cp)[1] = (unsigned char)((value) >> 16); \
140 (cp)[2] = (unsigned char)((value) >> 8); \
141 (cp)[3] = (unsigned char)(value); }
143 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
145 /* Coroutine mechanics for the sillier bits of the code */
146 #define crBegin1 static int crLine = 0;
147 #define crBegin2 switch(crLine) { case 0:;
148 #define crBegin crBegin1; crBegin2;
149 #define crFinish(z) } crLine = 0; return (z)
150 #define crFinishV } crLine = 0; return
151 #define crReturn(z) \
153 crLine=__LINE__; return (z); case __LINE__:;\
157 crLine=__LINE__; return; case __LINE__:;\
159 #define crStop(z) do{ crLine = 0; return (z); }while(0)
160 #define crStopV do{ crLine = 0; return; }while(0)
161 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
162 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
164 extern char *x11_init (Socket *, char *, void *);
165 extern void x11_close (Socket);
166 extern void x11_send (Socket , char *, int);
167 extern void x11_invent_auth(char *, int, char *, int);
170 * Ciphers for SSH2. We miss out single-DES because it isn't
171 * supported; also 3DES and Blowfish are both done differently from
172 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
173 * endianness and different-sized keys.)
175 const static struct ssh2_ciphers *ciphers[] = {
181 const static struct ssh_kex *kex_algs[] = {
182 #ifdef DO_DIFFIE_HELLMAN_GEX
183 &ssh_diffiehellman_gex,
185 &ssh_diffiehellman };
187 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
189 static void nullmac_key(unsigned char *key) { }
190 static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
191 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
192 const static struct ssh_mac ssh_mac_none = {
193 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
195 const static struct ssh_mac *macs[] = {
196 &ssh_sha1, &ssh_md5, &ssh_mac_none };
197 const static struct ssh_mac *buggymacs[] = {
198 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none };
200 static void ssh_comp_none_init(void) { }
201 static int ssh_comp_none_block(unsigned char *block, int len,
202 unsigned char **outblock, int *outlen) {
205 const static struct ssh_compress ssh_comp_none = {
207 ssh_comp_none_init, ssh_comp_none_block,
208 ssh_comp_none_init, ssh_comp_none_block
210 extern const struct ssh_compress ssh_zlib;
211 const static struct ssh_compress *compressions[] = {
212 &ssh_zlib, &ssh_comp_none };
214 enum { /* channel types */
221 * 2-3-4 tree storing channels.
224 unsigned remoteid, localid;
227 struct ssh2_data_channel {
228 unsigned char *outbuffer;
229 unsigned outbuflen, outbufsize;
230 unsigned remwindow, remmaxpkt;
233 struct ssh_agent_channel {
234 unsigned char *message;
235 unsigned char msglen[4];
236 int lensofar, totallen;
238 struct ssh_x11_channel {
253 static SHA_State exhash, exhashbase;
255 static Socket s = NULL;
257 static unsigned char session_key[32];
258 static int ssh1_compressing;
259 static int ssh_agentfwd_enabled;
260 static int ssh_X11_fwd_enabled;
261 static int ssh_remote_bugs;
262 static const struct ssh_cipher *cipher = NULL;
263 static const struct ssh2_cipher *cscipher = NULL;
264 static const struct ssh2_cipher *sccipher = NULL;
265 static const struct ssh_mac *csmac = NULL;
266 static const struct ssh_mac *scmac = NULL;
267 static const struct ssh_compress *cscomp = NULL;
268 static const struct ssh_compress *sccomp = NULL;
269 static const struct ssh_kex *kex = NULL;
270 static const struct ssh_signkey *hostkey = NULL;
271 static unsigned char ssh2_session_id[20];
272 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
274 static char *savedhost;
275 static int savedport;
276 static int ssh_send_ok;
277 static int ssh_echoing, ssh_editing;
279 static tree234 *ssh_channels; /* indexed by local id */
280 static struct ssh_channel *mainchan; /* primary session channel */
284 SSH_STATE_BEFORE_SIZE,
288 } ssh_state = SSH_STATE_PREPACKET;
290 static int size_needed = FALSE, eof_needed = FALSE;
292 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
293 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
294 static unsigned char *deferred_send_data = NULL;
295 static int deferred_len = 0, deferred_size = 0;
297 static int ssh_version;
298 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
299 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
300 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
301 static void ssh_size(void);
302 static void ssh_special (Telnet_Special);
303 static void ssh2_try_send(struct ssh_channel *c);
304 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
306 static int (*s_rdpkt)(unsigned char **data, int *datalen);
308 static struct rdpkt1_state_tag {
309 long len, pad, biglen, to_read;
310 unsigned long realcrc, gotcrc;
316 static struct rdpkt2_state_tag {
317 long len, pad, payload, packetlen, maclen;
320 unsigned long incoming_sequence;
323 static int ssh_channelcmp(void *av, void *bv) {
324 struct ssh_channel *a = (struct ssh_channel *)av;
325 struct ssh_channel *b = (struct ssh_channel *)bv;
326 if (a->localid < b->localid) return -1;
327 if (a->localid > b->localid) return +1;
330 static int ssh_channelfind(void *av, void *bv) {
331 unsigned *a = (unsigned *)av;
332 struct ssh_channel *b = (struct ssh_channel *)bv;
333 if (*a < b->localid) return -1;
334 if (*a > b->localid) return +1;
338 static void c_write (char *buf, int len) {
339 if ((flags & FLAG_STDERR)) {
341 for (i = 0; i < len; i++)
343 fputc(buf[i], stderr);
346 from_backend(1, buf, len);
349 static void c_write_str (char *buf) {
350 c_write(buf, strlen(buf));
354 * Collect incoming data in the incoming packet buffer.
355 * Decipher and verify the packet when it is completely read.
356 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
357 * Update the *data and *datalen variables.
358 * Return the additional nr of bytes needed, or 0 when
359 * a complete packet is available.
361 static int ssh1_rdpkt(unsigned char **data, int *datalen)
363 struct rdpkt1_state_tag *st = &rdpkt1_state;
372 for (st->i = st->len = 0; st->i < 4; st->i++) {
373 while ((*datalen) == 0)
375 st->len = (st->len << 8) + **data;
376 (*data)++, (*datalen)--;
380 if (st->len == 0x52656d6f) { /* "Remo"te server has closed ... */
381 st->len = 0x300; /* big enough to carry to end */
385 st->pad = 8 - (st->len % 8);
386 st->biglen = st->len + st->pad;
387 pktin.length = st->len - 5;
389 if (pktin.maxlen < st->biglen) {
390 pktin.maxlen = st->biglen;
391 pktin.data = (pktin.data == NULL ? smalloc(st->biglen+APIEXTRA) :
392 srealloc(pktin.data, st->biglen+APIEXTRA));
394 fatalbox("Out of memory");
397 st->to_read = st->biglen;
399 while (st->to_read > 0) {
400 st->chunk = st->to_read;
401 while ((*datalen) == 0)
402 crReturn(st->to_read);
403 if (st->chunk > (*datalen))
404 st->chunk = (*datalen);
405 memcpy(st->p, *data, st->chunk);
407 *datalen -= st->chunk;
409 st->to_read -= st->chunk;
413 cipher->decrypt(pktin.data, st->biglen);
415 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
416 for (st->i = 0; st->i < st->biglen; st->i++)
417 debug((" %02x", (unsigned char)pktin.data[st->i]));
421 st->realcrc = crc32(pktin.data, st->biglen-4);
422 st->gotcrc = GET_32BIT(pktin.data+st->biglen-4);
423 if (st->gotcrc != st->realcrc) {
424 bombout(("Incorrect CRC received on packet"));
428 pktin.body = pktin.data + st->pad + 1;
430 if (ssh1_compressing) {
431 unsigned char *decompblk;
435 debug(("Packet payload pre-decompression:\n"));
436 for (i = -1; i < pktin.length; i++)
437 debug((" %02x", (unsigned char)pktin.body[i]));
440 zlib_decompress_block(pktin.body-1, pktin.length+1,
441 &decompblk, &decomplen);
443 if (pktin.maxlen < st->pad + decomplen) {
444 pktin.maxlen = st->pad + decomplen;
445 pktin.data = srealloc(pktin.data, pktin.maxlen+APIEXTRA);
446 pktin.body = pktin.data + st->pad + 1;
448 fatalbox("Out of memory");
451 memcpy(pktin.body-1, decompblk, decomplen);
453 pktin.length = decomplen-1;
455 debug(("Packet payload post-decompression:\n"));
456 for (i = -1; i < pktin.length; i++)
457 debug((" %02x", (unsigned char)pktin.body[i]));
462 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
463 pktin.type == SSH1_SMSG_STDERR_DATA ||
464 pktin.type == SSH1_MSG_DEBUG ||
465 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
466 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
467 long strlen = GET_32BIT(pktin.body);
468 if (strlen + 4 != pktin.length) {
469 bombout(("Received data packet with bogus string length"));
474 pktin.type = pktin.body[-1];
476 if (pktin.type == SSH1_MSG_DEBUG) {
477 /* log debug message */
479 int strlen = GET_32BIT(pktin.body);
480 strcpy(buf, "Remote: ");
481 if (strlen > 70) strlen = 70;
482 memcpy(buf+8, pktin.body+4, strlen);
483 buf[8+strlen] = '\0';
486 } else if (pktin.type == SSH1_MSG_IGNORE) {
494 static int ssh2_rdpkt(unsigned char **data, int *datalen)
496 struct rdpkt2_state_tag *st = &rdpkt2_state;
504 st->cipherblk = sccipher->blksize;
507 if (st->cipherblk < 8)
510 if (pktin.maxlen < st->cipherblk) {
511 pktin.maxlen = st->cipherblk;
512 pktin.data = (pktin.data == NULL ? smalloc(st->cipherblk+APIEXTRA) :
513 srealloc(pktin.data, st->cipherblk+APIEXTRA));
515 fatalbox("Out of memory");
519 * Acquire and decrypt the first block of the packet. This will
520 * contain the length and padding details.
522 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
523 while ((*datalen) == 0)
524 crReturn(st->cipherblk-st->i);
525 pktin.data[st->i] = *(*data)++;
529 if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
534 sccipher->decrypt(pktin.data, st->cipherblk);
537 * Now get the length and padding figures.
539 st->len = GET_32BIT(pktin.data);
540 st->pad = pktin.data[4];
543 * This enables us to deduce the payload length.
545 st->payload = st->len - st->pad - 1;
547 pktin.length = st->payload + 5;
550 * So now we can work out the total packet length.
552 st->packetlen = st->len + 4;
553 st->maclen = scmac ? scmac->len : 0;
556 * Adjust memory allocation if packet is too big.
558 if (pktin.maxlen < st->packetlen+st->maclen) {
559 pktin.maxlen = st->packetlen+st->maclen;
560 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
561 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
563 fatalbox("Out of memory");
567 * Read and decrypt the remainder of the packet.
569 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen; st->i++) {
570 while ((*datalen) == 0)
571 crReturn(st->packetlen + st->maclen - st->i);
572 pktin.data[st->i] = *(*data)++;
575 /* Decrypt everything _except_ the MAC. */
577 sccipher->decrypt(pktin.data + st->cipherblk,
578 st->packetlen - st->cipherblk);
581 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
582 for (st->i = 0; st->i < st->packetlen; st->i++)
583 debug((" %02x", (unsigned char)pktin.data[st->i]));
590 if (scmac && !scmac->verify(pktin.data, st->len+4, st->incoming_sequence)) {
591 bombout(("Incorrect MAC received on packet"));
594 st->incoming_sequence++; /* whether or not we MACed */
597 * Decompress packet payload.
600 unsigned char *newpayload;
602 if (sccomp && sccomp->decompress(pktin.data+5, pktin.length-5,
603 &newpayload, &newlen)) {
604 if (pktin.maxlen < newlen+5) {
605 pktin.maxlen = newlen+5;
606 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
607 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
609 fatalbox("Out of memory");
611 pktin.length = 5 + newlen;
612 memcpy(pktin.data+5, newpayload, newlen);
614 debug(("Post-decompression payload:\r\n"));
615 for (st->i = 0; st->i < newlen; st->i++)
616 debug((" %02x", (unsigned char)pktin.data[5+st->i]));
625 pktin.type = pktin.data[5];
627 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
628 goto next_packet; /* FIXME: print DEBUG message */
633 static void ssh1_pktout_size(int len) {
636 len += 5; /* type and CRC */
640 pktout.length = len-5;
641 if (pktout.maxlen < biglen) {
642 pktout.maxlen = biglen;
644 /* Allocate enough buffer space for extra block
645 * for MS CryptEncrypt() */
646 pktout.data = (pktout.data == NULL ? smalloc(biglen+12) :
647 srealloc(pktout.data, biglen+12));
649 pktout.data = (pktout.data == NULL ? smalloc(biglen+4) :
650 srealloc(pktout.data, biglen+4));
653 fatalbox("Out of memory");
655 pktout.body = pktout.data+4+pad+1;
658 static void s_wrpkt_start(int type, int len) {
659 ssh1_pktout_size(len);
663 static int s_wrpkt_prepare(void) {
664 int pad, len, biglen, i;
667 pktout.body[-1] = pktout.type;
670 debug(("Packet payload pre-compression:\n"));
671 for (i = -1; i < pktout.length; i++)
672 debug((" %02x", (unsigned char)pktout.body[i]));
676 if (ssh1_compressing) {
677 unsigned char *compblk;
679 zlib_compress_block(pktout.body-1, pktout.length+1,
681 ssh1_pktout_size(complen-1);
682 memcpy(pktout.body-1, compblk, complen);
685 debug(("Packet payload post-compression:\n"));
686 for (i = -1; i < pktout.length; i++)
687 debug((" %02x", (unsigned char)pktout.body[i]));
692 len = pktout.length + 5; /* type and CRC */
696 for (i=0; i<pad; i++)
697 pktout.data[i+4] = random_byte();
698 crc = crc32(pktout.data+4, biglen-4);
699 PUT_32BIT(pktout.data+biglen, crc);
700 PUT_32BIT(pktout.data, len);
703 debug(("Sending packet len=%d\r\n", biglen+4));
704 for (i = 0; i < biglen+4; i++)
705 debug((" %02x", (unsigned char)pktout.data[i]));
709 cipher->encrypt(pktout.data+4, biglen);
714 static void s_wrpkt(void) {
716 len = s_wrpkt_prepare();
717 sk_write(s, pktout.data, len);
720 static void s_wrpkt_defer(void) {
722 len = s_wrpkt_prepare();
723 if (deferred_len + len > deferred_size) {
724 deferred_size = deferred_len + len + 128;
725 deferred_send_data = srealloc(deferred_send_data, deferred_size);
727 memcpy(deferred_send_data+deferred_len, pktout.data, len);
732 * Construct a packet with the specified contents.
734 static void construct_packet(int pkttype, va_list ap1, va_list ap2)
736 unsigned char *p, *argp, argchar;
737 unsigned long argint;
738 int pktlen, argtype, arglen;
742 while ((argtype = va_arg(ap1, int)) != PKT_END) {
745 (void) va_arg(ap1, int);
749 (void) va_arg(ap1, char);
753 (void) va_arg(ap1, unsigned char *);
754 arglen = va_arg(ap1, int);
758 argp = va_arg(ap1, unsigned char *);
759 arglen = strlen(argp);
760 pktlen += 4 + arglen;
763 bn = va_arg(ap1, Bignum);
764 pktlen += ssh1_bignum_length(bn);
771 s_wrpkt_start(pkttype, pktlen);
774 while ((argtype = va_arg(ap2, int)) != PKT_END) {
777 argint = va_arg(ap2, int);
778 PUT_32BIT(p, argint);
782 argchar = va_arg(ap2, unsigned char);
787 argp = va_arg(ap2, unsigned char *);
788 arglen = va_arg(ap2, int);
789 memcpy(p, argp, arglen);
793 argp = va_arg(ap2, unsigned char *);
794 arglen = strlen(argp);
795 PUT_32BIT(p, arglen);
796 memcpy(p + 4, argp, arglen);
800 bn = va_arg(ap2, Bignum);
801 p += ssh1_write_bignum(p, bn);
807 static void send_packet(int pkttype, ...) {
809 va_start(ap1, pkttype);
810 va_start(ap2, pkttype);
811 construct_packet(pkttype, ap1, ap2);
815 static void defer_packet(int pkttype, ...) {
817 va_start(ap1, pkttype);
818 va_start(ap2, pkttype);
819 construct_packet(pkttype, ap1, ap2);
823 static int ssh_versioncmp(char *a, char *b) {
825 unsigned long av, bv;
827 av = strtoul(a, &ae, 10);
828 bv = strtoul(b, &be, 10);
829 if (av != bv) return (av < bv ? -1 : +1);
830 if (*ae == '.') ae++;
831 if (*be == '.') be++;
832 av = strtoul(ae, &ae, 10);
833 bv = strtoul(be, &be, 10);
834 if (av != bv) return (av < bv ? -1 : +1);
840 * Utility routines for putting an SSH-protocol `string' and
841 * `uint32' into a SHA state.
844 static void sha_string(SHA_State *s, void *str, int len) {
845 unsigned char lenblk[4];
846 PUT_32BIT(lenblk, len);
847 SHA_Bytes(s, lenblk, 4);
848 SHA_Bytes(s, str, len);
851 static void sha_uint32(SHA_State *s, unsigned i) {
852 unsigned char intblk[4];
853 PUT_32BIT(intblk, i);
854 SHA_Bytes(s, intblk, 4);
858 * SSH2 packet construction functions.
860 static void ssh2_pkt_ensure(int length) {
861 if (pktout.maxlen < length) {
862 pktout.maxlen = length + 256;
863 pktout.data = (pktout.data == NULL ? smalloc(pktout.maxlen+APIEXTRA) :
864 srealloc(pktout.data, pktout.maxlen+APIEXTRA));
866 fatalbox("Out of memory");
869 static void ssh2_pkt_adddata(void *data, int len) {
870 pktout.length += len;
871 ssh2_pkt_ensure(pktout.length);
872 memcpy(pktout.data+pktout.length-len, data, len);
874 static void ssh2_pkt_addbyte(unsigned char byte) {
875 ssh2_pkt_adddata(&byte, 1);
877 static void ssh2_pkt_init(int pkt_type) {
879 ssh2_pkt_addbyte((unsigned char)pkt_type);
881 static void ssh2_pkt_addbool(unsigned char value) {
882 ssh2_pkt_adddata(&value, 1);
884 static void ssh2_pkt_adduint32(unsigned long value) {
887 ssh2_pkt_adddata(x, 4);
889 static void ssh2_pkt_addstring_start(void) {
890 ssh2_pkt_adduint32(0);
891 pktout.savedpos = pktout.length;
893 static void ssh2_pkt_addstring_str(char *data) {
894 ssh2_pkt_adddata(data, strlen(data));
895 PUT_32BIT(pktout.data + pktout.savedpos - 4,
896 pktout.length - pktout.savedpos);
898 static void ssh2_pkt_addstring_data(char *data, int len) {
899 ssh2_pkt_adddata(data, len);
900 PUT_32BIT(pktout.data + pktout.savedpos - 4,
901 pktout.length - pktout.savedpos);
903 static void ssh2_pkt_addstring(char *data) {
904 ssh2_pkt_addstring_start();
905 ssh2_pkt_addstring_str(data);
907 static char *ssh2_mpint_fmt(Bignum b, int *len) {
909 int i, n = (ssh1_bignum_bitcount(b)+7)/8;
912 fatalbox("out of memory");
914 for (i = 1; i <= n; i++)
915 p[i] = bignum_byte(b, n-i);
917 while (i <= n && p[i] == 0 && (p[i+1] & 0x80) == 0)
919 memmove(p, p+i, n+1-i);
923 static void ssh2_pkt_addmp(Bignum b) {
926 p = ssh2_mpint_fmt(b, &len);
927 ssh2_pkt_addstring_start();
928 ssh2_pkt_addstring_data(p, len);
933 * Construct an SSH2 final-form packet: compress it, encrypt it,
934 * put the MAC on it. Final packet, ready to be sent, is stored in
935 * pktout.data. Total length is returned.
937 static int ssh2_pkt_construct(void) {
938 int cipherblk, maclen, padding, i;
939 static unsigned long outgoing_sequence = 0;
942 * Compress packet payload.
945 debug(("Pre-compression payload:\r\n"));
946 for (i = 5; i < pktout.length; i++)
947 debug((" %02x", (unsigned char)pktout.data[i]));
951 unsigned char *newpayload;
953 if (cscomp && cscomp->compress(pktout.data+5, pktout.length-5,
954 &newpayload, &newlen)) {
956 ssh2_pkt_adddata(newpayload, newlen);
962 * Add padding. At least four bytes, and must also bring total
963 * length (minus MAC) up to a multiple of the block size.
965 cipherblk = cscipher ? cscipher->blksize : 8; /* block size */
966 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
968 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
969 maclen = csmac ? csmac->len : 0;
970 ssh2_pkt_ensure(pktout.length + padding + maclen);
971 pktout.data[4] = padding;
972 for (i = 0; i < padding; i++)
973 pktout.data[pktout.length + i] = random_byte();
974 PUT_32BIT(pktout.data, pktout.length + padding - 4);
976 csmac->generate(pktout.data, pktout.length + padding,
978 outgoing_sequence++; /* whether or not we MACed */
981 debug(("Sending packet len=%d\r\n", pktout.length+padding));
982 for (i = 0; i < pktout.length+padding; i++)
983 debug((" %02x", (unsigned char)pktout.data[i]));
988 cscipher->encrypt(pktout.data, pktout.length + padding);
990 /* Ready-to-send packet starts at pktout.data. We return length. */
991 return pktout.length + padding + maclen;
995 * Construct and send an SSH2 packet immediately.
997 static void ssh2_pkt_send(void) {
998 int len = ssh2_pkt_construct();
999 sk_write(s, pktout.data, len);
1003 * Construct an SSH2 packet and add it to a deferred data block.
1004 * Useful for sending multiple packets in a single sk_write() call,
1005 * to prevent a traffic-analysing listener from being able to work
1006 * out the length of any particular packet (such as the password
1009 * Note that because SSH2 sequence-numbers its packets, this can
1010 * NOT be used as an m4-style `defer' allowing packets to be
1011 * constructed in one order and sent in another.
1013 static void ssh2_pkt_defer(void) {
1014 int len = ssh2_pkt_construct();
1015 if (deferred_len + len > deferred_size) {
1016 deferred_size = deferred_len + len + 128;
1017 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1019 memcpy(deferred_send_data+deferred_len, pktout.data, len);
1020 deferred_len += len;
1024 * Send the whole deferred data block constructed by
1025 * ssh2_pkt_defer() or SSH1's defer_packet().
1027 static void ssh_pkt_defersend(void) {
1028 sk_write(s, deferred_send_data, deferred_len);
1029 deferred_len = deferred_size = 0;
1030 sfree(deferred_send_data);
1031 deferred_send_data = NULL;
1035 void bndebug(char *string, Bignum b) {
1038 p = ssh2_mpint_fmt(b, &len);
1039 debug(("%s", string));
1040 for (i = 0; i < len; i++)
1041 debug((" %02x", p[i]));
1047 static void sha_mpint(SHA_State *s, Bignum b) {
1050 p = ssh2_mpint_fmt(b, &len);
1051 sha_string(s, p, len);
1056 * SSH2 packet decode functions.
1058 static unsigned long ssh2_pkt_getuint32(void) {
1059 unsigned long value;
1060 if (pktin.length - pktin.savedpos < 4)
1061 return 0; /* arrgh, no way to decline (FIXME?) */
1062 value = GET_32BIT(pktin.data+pktin.savedpos);
1063 pktin.savedpos += 4;
1066 static int ssh2_pkt_getbool(void) {
1067 unsigned long value;
1068 if (pktin.length - pktin.savedpos < 1)
1069 return 0; /* arrgh, no way to decline (FIXME?) */
1070 value = pktin.data[pktin.savedpos] != 0;
1074 static void ssh2_pkt_getstring(char **p, int *length) {
1076 if (pktin.length - pktin.savedpos < 4)
1078 *length = GET_32BIT(pktin.data+pktin.savedpos);
1079 pktin.savedpos += 4;
1080 if (pktin.length - pktin.savedpos < *length)
1082 *p = pktin.data+pktin.savedpos;
1083 pktin.savedpos += *length;
1085 static Bignum ssh2_pkt_getmp(void) {
1090 ssh2_pkt_getstring(&p, &length);
1094 bombout(("internal error: Can't handle negative mpints"));
1097 b = bignum_from_bytes(p, length);
1102 * Examine the remote side's version string and compare it against
1103 * a list of known buggy implementations.
1105 static void ssh_detect_bugs(char *vstring) {
1106 char *imp; /* pointer to implementation part */
1108 imp += strcspn(imp, "-");
1109 imp += strcspn(imp, "-");
1111 ssh_remote_bugs = 0;
1113 if (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1114 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1115 !strcmp(imp, "1.2.22")) {
1117 * These versions don't support SSH1_MSG_IGNORE, so we have
1118 * to use a different defence against password length
1121 ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1122 logevent("We believe remote version has SSH1 ignore bug");
1125 if (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1126 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1127 !strncmp(imp, "2.1 ", 4)) {
1129 * These versions have the HMAC bug.
1131 ssh_remote_bugs |= BUG_SSH2_HMAC;
1132 logevent("We believe remote version has SSH2 HMAC bug");
1136 static int do_ssh_init(unsigned char c) {
1138 static char version[10];
1139 static char vstring[80];
1140 static char vlog[sizeof(vstring)+20];
1145 /* Search for the string "SSH-" in the input. */
1148 static const int transS[] = { 1, 2, 2, 1 };
1149 static const int transH[] = { 0, 0, 3, 0 };
1150 static const int transminus[] = { 0, 0, 0, -1 };
1151 if (c == 'S') i = transS[i];
1152 else if (c == 'H') i = transH[i];
1153 else if (c == '-') i = transminus[i];
1157 crReturn(1); /* get another character */
1160 strcpy(vstring, "SSH-");
1164 crReturn(1); /* get another char */
1165 if (vsp < vstring+sizeof(vstring)-1)
1171 } else if (i < sizeof(version)-1)
1178 ssh_agentfwd_enabled = FALSE;
1179 rdpkt2_state.incoming_sequence = 0;
1182 sprintf(vlog, "Server version: %s", vstring);
1183 ssh_detect_bugs(vstring);
1184 vlog[strcspn(vlog, "\r\n")] = '\0';
1188 * Server version "1.99" means we can choose whether we use v1
1189 * or v2 protocol. Choice is based on cfg.sshprot.
1191 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1193 * This is a v2 server. Begin v2 protocol.
1195 char *verstring = "SSH-2.0-PuTTY";
1196 SHA_Init(&exhashbase);
1198 * Hash our version string and their version string.
1200 sha_string(&exhashbase, verstring, strlen(verstring));
1201 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1202 sprintf(vstring, "%s\n", verstring);
1203 sprintf(vlog, "We claim version: %s", verstring);
1205 logevent("Using SSH protocol version 2");
1206 sk_write(s, vstring, strlen(vstring));
1207 ssh_protocol = ssh2_protocol;
1209 s_rdpkt = ssh2_rdpkt;
1212 * This is a v1 server. Begin v1 protocol.
1214 sprintf(vstring, "SSH-%s-PuTTY\n",
1215 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1216 sprintf(vlog, "We claim version: %s", vstring);
1217 vlog[strcspn(vlog, "\r\n")] = '\0';
1219 logevent("Using SSH protocol version 1");
1220 sk_write(s, vstring, strlen(vstring));
1221 ssh_protocol = ssh1_protocol;
1223 s_rdpkt = ssh1_rdpkt;
1225 ssh_state = SSH_STATE_BEFORE_SIZE;
1230 static void ssh_gotdata(unsigned char *data, int datalen)
1235 * To begin with, feed the characters one by one to the
1236 * protocol initialisation / selection function do_ssh_init().
1237 * When that returns 0, we're done with the initial greeting
1238 * exchange and can move on to packet discipline.
1243 crReturnV; /* more data please */
1244 ret = do_ssh_init(*data);
1251 * We emerge from that loop when the initial negotiation is
1252 * over and we have selected an s_rdpkt function. Now pass
1253 * everything to s_rdpkt, and then pass the resulting packets
1254 * to the proper protocol handler.
1259 while (datalen > 0) {
1260 if ( s_rdpkt(&data, &datalen) == 0 ) {
1261 ssh_protocol(NULL, 0, 1);
1262 if (ssh_state == SSH_STATE_CLOSED) {
1272 static int ssh_receive(Socket skt, int urgent, char *data, int len) {
1274 /* A socket error has occurred. */
1275 ssh_state = SSH_STATE_CLOSED;
1278 connection_fatal(data);
1281 /* Connection has closed. */
1282 ssh_state = SSH_STATE_CLOSED;
1287 ssh_gotdata (data, len);
1288 if (ssh_state == SSH_STATE_CLOSED) {
1299 * Connect to specified host and port.
1300 * Returns an error message, or NULL on success.
1301 * Also places the canonical host name into `realhost'.
1303 static char *connect_to_host(char *host, int port, char **realhost)
1312 savedhost = smalloc(1+strlen(host));
1314 fatalbox("Out of memory");
1315 strcpy(savedhost, host);
1318 port = 22; /* default ssh port */
1331 addr = sk_namelookup(host, realhost);
1332 if ( (err = sk_addr_error(addr)) )
1342 s = sk_new(addr, port, 0, 1, ssh_receive);
1343 if ( (err = sk_socket_error(s)) )
1347 sk_write(s, "connect ", 8);
1348 sk_write(s, FWhost, strlen(FWhost));
1351 sprintf(buf, " %d\n", FWport);
1352 sk_write(s, buf, strlen(buf));
1360 * Handle the key exchange and user authentication phases.
1362 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1365 unsigned char *rsabuf, *keystr1, *keystr2;
1366 unsigned char cookie[8];
1367 struct RSAKey servkey, hostkey;
1368 struct MD5Context md5c;
1369 static unsigned long supported_ciphers_mask, supported_auths_mask;
1370 static int tried_publickey;
1371 static unsigned char session_id[16];
1373 static char username[100];
1377 if (!ispkt) crWaitUntil(ispkt);
1379 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1380 bombout(("Public key packet not received"));
1384 logevent("Received public keys");
1386 memcpy(cookie, pktin.body, 8);
1388 i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1389 j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1392 * Log the host key fingerprint.
1396 logevent("Host key fingerprint is:");
1397 strcpy(logmsg, " ");
1398 hostkey.comment = NULL;
1399 rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
1404 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1405 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1408 MD5Update(&md5c, keystr2, hostkey.bytes);
1409 MD5Update(&md5c, keystr1, servkey.bytes);
1410 MD5Update(&md5c, pktin.body, 8);
1411 MD5Final(session_id, &md5c);
1413 for (i=0; i<32; i++)
1414 session_key[i] = random_byte();
1416 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1418 rsabuf = smalloc(len);
1420 fatalbox("Out of memory");
1423 * Verify the host key.
1427 * First format the key into a string.
1429 int len = rsastr_len(&hostkey);
1430 char fingerprint[100];
1431 char *keystr = smalloc(len);
1433 fatalbox("Out of memory");
1434 rsastr_fmt(keystr, &hostkey);
1435 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
1436 verify_ssh_host_key(savedhost, savedport, "rsa", keystr, fingerprint);
1440 for (i=0; i<32; i++) {
1441 rsabuf[i] = session_key[i];
1443 rsabuf[i] ^= session_id[i];
1446 if (hostkey.bytes > servkey.bytes) {
1447 rsaencrypt(rsabuf, 32, &servkey);
1448 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1450 rsaencrypt(rsabuf, 32, &hostkey);
1451 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1454 logevent("Encrypted session key");
1456 switch (cfg.cipher) {
1457 case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH; break;
1458 case CIPHER_DES: cipher_type = SSH_CIPHER_DES; break;
1459 case CIPHER_3DES: cipher_type = SSH_CIPHER_3DES; break;
1461 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1462 cipher_type = SSH_CIPHER_3DES;
1465 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1466 c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
1467 cipher_type = SSH_CIPHER_3DES;
1469 switch (cipher_type) {
1470 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1471 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1472 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1475 send_packet(SSH1_CMSG_SESSION_KEY,
1476 PKT_CHAR, cipher_type,
1477 PKT_DATA, cookie, 8,
1478 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1479 PKT_DATA, rsabuf, len,
1483 logevent("Trying to enable encryption...");
1487 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1488 cipher_type == SSH_CIPHER_DES ? &ssh_des :
1490 cipher->sesskey(session_key);
1494 if (pktin.type != SSH1_SMSG_SUCCESS) {
1495 bombout(("Encryption not successfully enabled"));
1499 logevent("Successfully started encryption");
1505 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1506 c_write_str("login as: ");
1509 crWaitUntil(!ispkt);
1510 while (inlen--) switch (c = *in++) {
1517 c_write_str("\b \b");
1523 c_write_str("\b \b");
1532 if (((c >= ' ' && c <= '~') ||
1533 ((unsigned char)c >= 160)) && pos < 40) {
1534 username[pos++] = c;
1540 c_write_str("\r\n");
1541 username[strcspn(username, "\n\r")] = '\0';
1543 strncpy(username, cfg.username, 99);
1544 username[99] = '\0';
1547 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1549 char userlog[22+sizeof(username)];
1550 sprintf(userlog, "Sent username \"%s\"", username);
1552 if (flags & FLAG_INTERACTIVE &&
1553 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
1554 strcat(userlog, "\r\n");
1555 c_write_str(userlog);
1562 tried_publickey = 0;
1564 while (pktin.type == SSH1_SMSG_FAILURE) {
1565 static char password[100];
1566 static char prompt[200];
1569 static int pwpkt_type;
1571 * Show password prompt, having first obtained it via a TIS
1572 * or CryptoCard exchange if we're doing TIS or CryptoCard
1575 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1576 if (agent_exists()) {
1578 * Attempt RSA authentication using Pageant.
1580 static unsigned char request[5], *response, *p;
1581 static int responselen;
1582 static int i, nkeys;
1583 static int authed = FALSE;
1586 logevent("Pageant is running. Requesting keys.");
1588 /* Request the keys held by the agent. */
1589 PUT_32BIT(request, 1);
1590 request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
1591 agent_query(request, 5, &r, &responselen);
1592 response = (unsigned char *)r;
1595 nkeys = GET_32BIT(p); p += 4;
1596 { char buf[64]; sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
1598 for (i = 0; i < nkeys; i++) {
1599 static struct RSAKey key;
1600 static Bignum challenge;
1601 static char *commentp;
1602 static int commentlen;
1604 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1607 p += ssh1_read_bignum(p, &key.exponent);
1608 p += ssh1_read_bignum(p, &key.modulus);
1609 commentlen = GET_32BIT(p); p += 4;
1610 commentp = p; p += commentlen;
1611 send_packet(SSH1_CMSG_AUTH_RSA,
1612 PKT_BIGNUM, key.modulus, PKT_END);
1614 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1615 logevent("Key refused");
1618 logevent("Received RSA challenge");
1619 ssh1_read_bignum(pktin.body, &challenge);
1621 char *agentreq, *q, *ret;
1623 len = 1 + 4; /* message type, bit count */
1624 len += ssh1_bignum_length(key.exponent);
1625 len += ssh1_bignum_length(key.modulus);
1626 len += ssh1_bignum_length(challenge);
1627 len += 16; /* session id */
1628 len += 4; /* response format */
1629 agentreq = smalloc(4 + len);
1630 PUT_32BIT(agentreq, len);
1632 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
1633 PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1635 q += ssh1_write_bignum(q, key.exponent);
1636 q += ssh1_write_bignum(q, key.modulus);
1637 q += ssh1_write_bignum(q, challenge);
1638 memcpy(q, session_id, 16); q += 16;
1639 PUT_32BIT(q, 1); /* response format */
1640 agent_query(agentreq, len+4, &ret, &retlen);
1643 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
1644 logevent("Sending Pageant's response");
1645 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1646 PKT_DATA, ret+5, 16, PKT_END);
1649 if (pktin.type == SSH1_SMSG_SUCCESS) {
1650 logevent("Pageant's response accepted");
1651 if (flags & FLAG_VERBOSE) {
1652 c_write_str("Authenticated using RSA key \"");
1653 c_write(commentp, commentlen);
1654 c_write_str("\" from agent\r\n");
1658 logevent("Pageant's response not accepted");
1660 logevent("Pageant failed to answer challenge");
1664 logevent("No reply received from Pageant");
1667 freebn(key.exponent);
1668 freebn(key.modulus);
1677 if (*cfg.keyfile && !tried_publickey)
1678 pwpkt_type = SSH1_CMSG_AUTH_RSA;
1680 if (pktin.type == SSH1_SMSG_FAILURE &&
1682 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1683 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1684 logevent("Requested TIS authentication");
1685 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1687 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1688 logevent("TIS authentication declined");
1689 if (flags & FLAG_INTERACTIVE)
1690 c_write_str("TIS authentication refused.\r\n");
1692 int challengelen = ((pktin.body[0] << 24) |
1693 (pktin.body[1] << 16) |
1694 (pktin.body[2] << 8) |
1696 logevent("Received TIS challenge");
1697 if (challengelen > sizeof(prompt)-1)
1698 challengelen = sizeof(prompt)-1; /* prevent overrun */
1699 memcpy(prompt, pktin.body+4, challengelen);
1700 prompt[challengelen] = '\0';
1703 if (pktin.type == SSH1_SMSG_FAILURE &&
1705 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1706 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1707 logevent("Requested CryptoCard authentication");
1708 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1710 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1711 logevent("CryptoCard authentication declined");
1712 c_write_str("CryptoCard authentication refused.\r\n");
1714 int challengelen = ((pktin.body[0] << 24) |
1715 (pktin.body[1] << 16) |
1716 (pktin.body[2] << 8) |
1718 logevent("Received CryptoCard challenge");
1719 if (challengelen > sizeof(prompt)-1)
1720 challengelen = sizeof(prompt)-1; /* prevent overrun */
1721 memcpy(prompt, pktin.body+4, challengelen);
1722 strncpy(prompt + challengelen, "\r\nResponse : ",
1723 sizeof(prompt)-challengelen);
1724 prompt[sizeof(prompt)-1] = '\0';
1727 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1728 sprintf(prompt, "%.90s@%.90s's password: ",
1729 username, savedhost);
1731 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1732 char *comment = NULL;
1733 if (flags & FLAG_VERBOSE)
1734 c_write_str("Trying public key authentication.\r\n");
1735 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1736 if (flags & FLAG_VERBOSE)
1737 c_write_str("No passphrase required.\r\n");
1740 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
1744 if (ssh_get_password) {
1745 if (!ssh_get_password(prompt, password, sizeof(password))) {
1747 * get_password failed to get a password (for
1748 * example because one was supplied on the command
1749 * line which has already failed to work).
1752 logevent("No more passwords to try");
1753 ssh_state = SSH_STATE_CLOSED;
1757 c_write_str(prompt);
1761 crWaitUntil(!ispkt);
1762 while (inlen--) switch (c = *in++) {
1779 if (((c >= ' ' && c <= '~') ||
1780 ((unsigned char)c >= 160)) && pos < sizeof(password))
1781 password[pos++] = c;
1785 c_write_str("\r\n");
1789 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1791 * Try public key authentication with the specified
1794 static struct RSAKey pubkey;
1795 static Bignum challenge, response;
1797 static unsigned char buffer[32];
1799 tried_publickey = 1;
1800 i = loadrsakey(cfg.keyfile, &pubkey, password);
1802 c_write_str("Couldn't load public key from ");
1803 c_write_str(cfg.keyfile);
1804 c_write_str(".\r\n");
1805 continue; /* go and try password */
1808 c_write_str("Wrong passphrase.\r\n");
1809 tried_publickey = 0;
1810 continue; /* try again */
1814 * Send a public key attempt.
1816 send_packet(SSH1_CMSG_AUTH_RSA,
1817 PKT_BIGNUM, pubkey.modulus, PKT_END);
1820 if (pktin.type == SSH1_SMSG_FAILURE) {
1821 c_write_str("Server refused our public key.\r\n");
1822 continue; /* go and try password */
1824 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1825 bombout(("Bizarre response to offer of public key"));
1828 ssh1_read_bignum(pktin.body, &challenge);
1829 response = rsadecrypt(challenge, &pubkey);
1830 freebn(pubkey.private_exponent); /* burn the evidence */
1832 for (i = 0; i < 32; i++) {
1833 buffer[i] = bignum_byte(response, 31-i);
1837 MD5Update(&md5c, buffer, 32);
1838 MD5Update(&md5c, session_id, 16);
1839 MD5Final(buffer, &md5c);
1841 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1842 PKT_DATA, buffer, 16, PKT_END);
1845 if (pktin.type == SSH1_SMSG_FAILURE) {
1846 if (flags & FLAG_VERBOSE)
1847 c_write_str("Failed to authenticate with our public key.\r\n");
1848 continue; /* go and try password */
1849 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1850 bombout(("Bizarre response to RSA authentication response"));
1854 break; /* we're through! */
1856 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1858 * Defence against traffic analysis: we send a
1859 * whole bunch of packets containing strings of
1860 * different lengths. One of these strings is the
1861 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
1862 * The others are all random data in
1863 * SSH1_MSG_IGNORE packets. This way a passive
1864 * listener can't tell which is the password, and
1865 * hence can't deduce the password length.
1867 * Anybody with a password length greater than 16
1868 * bytes is going to have enough entropy in their
1869 * password that a listener won't find it _that_
1870 * much help to know how long it is. So what we'll
1873 * - if password length < 16, we send 15 packets
1874 * containing string lengths 1 through 15
1876 * - otherwise, we let N be the nearest multiple
1877 * of 8 below the password length, and send 8
1878 * packets containing string lengths N through
1879 * N+7. This won't obscure the order of
1880 * magnitude of the password length, but it will
1881 * introduce a bit of extra uncertainty.
1883 * A few servers (the old 1.2.18 through 1.2.22)
1884 * can't deal with SSH1_MSG_IGNORE. For these
1885 * servers, we need an alternative defence. We make
1886 * use of the fact that the password is interpreted
1887 * as a C string: so we can append a NUL, then some
1890 if (ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) {
1895 len = strlen(password);
1896 if (len < sizeof(string)) {
1898 strcpy(string, password);
1899 len++; /* cover the zero byte */
1900 while (len < sizeof(string)) {
1901 string[len++] = (char)random_byte();
1906 send_packet(pwpkt_type, PKT_INT, len,
1907 PKT_DATA, s, len, PKT_END);
1909 int bottom, top, pwlen, i;
1912 pwlen = strlen(password);
1917 bottom = pwlen &~ 7;
1921 assert(pwlen >= bottom && pwlen <= top);
1923 randomstr = smalloc(top+1);
1925 for (i = bottom; i <= top; i++) {
1927 defer_packet(pwpkt_type, PKT_STR, password, PKT_END);
1929 for (j = 0; j < i; j++) {
1931 randomstr[j] = random_byte();
1932 } while (randomstr[j] == '\0');
1934 randomstr[i] = '\0';
1935 defer_packet(SSH1_MSG_IGNORE,
1936 PKT_STR, randomstr, PKT_END);
1939 ssh_pkt_defersend();
1942 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1945 logevent("Sent password");
1946 memset(password, 0, strlen(password));
1948 if (pktin.type == SSH1_SMSG_FAILURE) {
1949 if (flags & FLAG_VERBOSE)
1950 c_write_str("Access denied\r\n");
1951 logevent("Authentication refused");
1952 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1953 logevent("Received disconnect request");
1954 ssh_state = SSH_STATE_CLOSED;
1956 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1957 bombout(("Strange packet received, type %d", pktin.type));
1962 logevent("Authentication successful");
1967 void sshfwd_close(struct ssh_channel *c) {
1969 if (ssh_version == 1) {
1970 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END);
1972 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
1973 ssh2_pkt_adduint32(c->remoteid);
1977 if (c->type == CHAN_X11) {
1979 logevent("X11 connection terminated");
1984 void sshfwd_write(struct ssh_channel *c, char *buf, int len) {
1985 if (ssh_version == 1) {
1986 send_packet(SSH1_MSG_CHANNEL_DATA,
1987 PKT_INT, c->remoteid,
1992 ssh2_add_channel_data(c, buf, len);
1997 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
2002 while (!do_ssh1_login(in, inlen, ispkt)) {
2005 if (ssh_state == SSH_STATE_CLOSED)
2008 if (cfg.agentfwd && agent_exists()) {
2009 logevent("Requesting agent forwarding");
2010 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2011 do { crReturnV; } while (!ispkt);
2012 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2013 bombout(("Protocol confusion"));
2015 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2016 logevent("Agent forwarding refused");
2018 logevent("Agent forwarding enabled");
2019 ssh_agentfwd_enabled = TRUE;
2023 if (cfg.x11_forward) {
2024 char proto[20], data[64];
2025 logevent("Requesting X11 forwarding");
2026 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2027 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2028 PKT_STR, proto, PKT_STR, data,
2031 do { crReturnV; } while (!ispkt);
2032 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2033 bombout(("Protocol confusion"));
2035 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2036 logevent("X11 forwarding refused");
2038 logevent("X11 forwarding enabled");
2039 ssh_X11_fwd_enabled = TRUE;
2044 send_packet(SSH1_CMSG_REQUEST_PTY,
2045 PKT_STR, cfg.termtype,
2046 PKT_INT, rows, PKT_INT, cols,
2047 PKT_INT, 0, PKT_INT, 0,
2050 ssh_state = SSH_STATE_INTERMED;
2051 do { crReturnV; } while (!ispkt);
2052 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2053 bombout(("Protocol confusion"));
2055 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2056 c_write_str("Server refused to allocate pty\r\n");
2057 ssh_editing = ssh_echoing = 1;
2059 logevent("Allocated pty");
2061 ssh_editing = ssh_echoing = 1;
2064 if (cfg.compression) {
2065 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
2066 do { crReturnV; } while (!ispkt);
2067 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2068 bombout(("Protocol confusion"));
2070 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2071 c_write_str("Server refused to compress\r\n");
2073 logevent("Started compression");
2074 ssh1_compressing = TRUE;
2075 zlib_compress_init();
2076 zlib_decompress_init();
2079 if (*cfg.remote_cmd)
2080 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
2082 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
2083 logevent("Started session");
2085 ssh_state = SSH_STATE_SESSION;
2089 ssh_special(TS_EOF);
2091 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
2093 ssh_channels = newtree234(ssh_channelcmp);
2097 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
2098 pktin.type == SSH1_SMSG_STDERR_DATA) {
2099 long len = GET_32BIT(pktin.body);
2100 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
2102 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2103 ssh_state = SSH_STATE_CLOSED;
2104 logevent("Received disconnect request");
2106 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
2107 /* Remote side is trying to open a channel to talk to our
2108 * X-Server. Give them back a local channel number. */
2110 struct ssh_channel *c, *d;
2113 logevent("Received X11 connect request");
2114 /* Refuse if X11 forwarding is disabled. */
2115 if (!ssh_X11_fwd_enabled) {
2116 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2117 PKT_INT, GET_32BIT(pktin.body),
2119 logevent("Rejected X11 connect request");
2121 c = smalloc(sizeof(struct ssh_channel));
2123 if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
2124 logevent("opening X11 forward connection failed");
2126 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2127 PKT_INT, GET_32BIT(pktin.body),
2130 logevent("opening X11 forward connection succeeded");
2131 for (i=1, d = first234(ssh_channels, &e); d; d = next234(&e)) {
2133 break; /* found a free number */
2136 c->remoteid = GET_32BIT(pktin.body);
2139 c->type = CHAN_X11; /* identify channel type */
2140 add234(ssh_channels, c);
2141 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2142 PKT_INT, c->remoteid, PKT_INT, c->localid,
2144 logevent("Opened X11 forward channel");
2147 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
2148 /* Remote side is trying to open a channel to talk to our
2149 * agent. Give them back a local channel number. */
2151 struct ssh_channel *c;
2154 /* Refuse if agent forwarding is disabled. */
2155 if (!ssh_agentfwd_enabled) {
2156 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2157 PKT_INT, GET_32BIT(pktin.body),
2161 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
2163 break; /* found a free number */
2166 c = smalloc(sizeof(struct ssh_channel));
2167 c->remoteid = GET_32BIT(pktin.body);
2170 c->type = CHAN_AGENT; /* identify channel type */
2171 c->u.a.lensofar = 0;
2172 add234(ssh_channels, c);
2173 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2174 PKT_INT, c->remoteid, PKT_INT, c->localid,
2177 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2178 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
2179 /* Remote side closes a channel. */
2180 unsigned i = GET_32BIT(pktin.body);
2181 struct ssh_channel *c;
2182 c = find234(ssh_channels, &i, ssh_channelfind);
2185 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2186 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
2187 if ((c->closes == 0) && (c->type == CHAN_X11)) {
2188 logevent("X11 connection closed");
2189 assert(c->u.x11.s != NULL);
2190 x11_close(c->u.x11.s);
2193 c->closes |= closetype;
2194 if (c->closes == 3) {
2195 del234(ssh_channels, c);
2199 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2200 /* Data sent down one of our channels. */
2201 int i = GET_32BIT(pktin.body);
2202 int len = GET_32BIT(pktin.body+4);
2203 unsigned char *p = pktin.body+8;
2204 struct ssh_channel *c;
2205 c = find234(ssh_channels, &i, ssh_channelfind);
2209 x11_send(c->u.x11.s, p, len);
2212 /* Data for an agent message. Buffer it. */
2214 if (c->u.a.lensofar < 4) {
2215 int l = min(4 - c->u.a.lensofar, len);
2216 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
2217 p += l; len -= l; c->u.a.lensofar += l;
2219 if (c->u.a.lensofar == 4) {
2220 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
2221 c->u.a.message = smalloc(c->u.a.totallen);
2222 memcpy(c->u.a.message, c->u.a.msglen, 4);
2224 if (c->u.a.lensofar >= 4 && len > 0) {
2225 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
2226 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
2227 p += l; len -= l; c->u.a.lensofar += l;
2229 if (c->u.a.lensofar == c->u.a.totallen) {
2230 void *reply, *sentreply;
2232 agent_query(c->u.a.message, c->u.a.totallen,
2237 /* Fake SSH_AGENT_FAILURE. */
2238 sentreply = "\0\0\0\1\5";
2241 send_packet(SSH1_MSG_CHANNEL_DATA,
2242 PKT_INT, c->remoteid,
2244 PKT_DATA, sentreply, replylen,
2248 sfree(c->u.a.message);
2249 c->u.a.lensofar = 0;
2255 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
2256 /* may be from EXEC_SHELL on some servers */
2257 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2258 /* may be from EXEC_SHELL on some servers
2259 * if no pty is available or in other odd cases. Ignore */
2260 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2261 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2263 bombout(("Strange packet received: type %d", pktin.type));
2268 int len = min(inlen, 512);
2269 send_packet(SSH1_CMSG_STDIN_DATA,
2270 PKT_INT, len, PKT_DATA, in, len, PKT_END);
2281 * Utility routine for decoding comma-separated strings in KEXINIT.
2283 static int in_commasep_string(char *needle, char *haystack, int haylen) {
2284 int needlen = strlen(needle);
2287 * Is it at the start of the string?
2289 if (haylen >= needlen && /* haystack is long enough */
2290 !memcmp(needle, haystack, needlen) && /* initial match */
2291 (haylen == needlen || haystack[needlen] == ',')
2292 /* either , or EOS follows */
2296 * If not, search for the next comma and resume after that.
2297 * If no comma found, terminate.
2299 while (haylen > 0 && *haystack != ',')
2300 haylen--, haystack++;
2303 haylen--, haystack++; /* skip over comma itself */
2308 * SSH2 key creation method.
2310 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr, char *keyspace) {
2312 /* First 20 bytes. */
2315 SHA_Bytes(&s, H, 20);
2316 SHA_Bytes(&s, &chr, 1);
2317 SHA_Bytes(&s, sessid, 20);
2318 SHA_Final(&s, keyspace);
2319 /* Next 20 bytes. */
2322 SHA_Bytes(&s, H, 20);
2323 SHA_Bytes(&s, keyspace, 20);
2324 SHA_Final(&s, keyspace+20);
2328 * Handle the SSH2 transport layer.
2330 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
2332 static int i, j, len, nbits;
2334 static Bignum p, g, e, f, K;
2335 static int kex_init_value, kex_reply_value;
2336 static const struct ssh_mac **maclist;
2338 static const struct ssh2_cipher *cscipher_tobe = NULL;
2339 static const struct ssh2_cipher *sccipher_tobe = NULL;
2340 static const struct ssh_mac *csmac_tobe = NULL;
2341 static const struct ssh_mac *scmac_tobe = NULL;
2342 static const struct ssh_compress *cscomp_tobe = NULL;
2343 static const struct ssh_compress *sccomp_tobe = NULL;
2344 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
2345 static int hostkeylen, siglen;
2346 static void *hkey; /* actual host key */
2347 static unsigned char exchange_hash[20];
2348 static unsigned char keyspace[40];
2349 static const struct ssh2_ciphers *preferred_cipher;
2350 static const struct ssh_compress *preferred_comp;
2351 static int first_kex;
2358 * Set up the preferred cipher and compression.
2360 if (cfg.cipher == CIPHER_BLOWFISH) {
2361 preferred_cipher = &ssh2_blowfish;
2362 } else if (cfg.cipher == CIPHER_DES) {
2363 logevent("Single DES not supported in SSH2; using 3DES");
2364 preferred_cipher = &ssh2_3des;
2365 } else if (cfg.cipher == CIPHER_3DES) {
2366 preferred_cipher = &ssh2_3des;
2367 } else if (cfg.cipher == CIPHER_AES) {
2368 preferred_cipher = &ssh2_aes;
2370 /* Shouldn't happen, but we do want to initialise to _something_. */
2371 preferred_cipher = &ssh2_3des;
2373 if (cfg.compression)
2374 preferred_comp = &ssh_zlib;
2376 preferred_comp = &ssh_comp_none;
2379 * Be prepared to work around the buggy MAC problem.
2381 if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
2382 maclist = buggymacs, nmacs = lenof(buggymacs);
2384 maclist = macs, nmacs = lenof(macs);
2388 * Construct and send our key exchange packet.
2390 ssh2_pkt_init(SSH2_MSG_KEXINIT);
2391 for (i = 0; i < 16; i++)
2392 ssh2_pkt_addbyte((unsigned char)random_byte());
2393 /* List key exchange algorithms. */
2394 ssh2_pkt_addstring_start();
2395 for (i = 0; i < lenof(kex_algs); i++) {
2396 ssh2_pkt_addstring_str(kex_algs[i]->name);
2397 if (i < lenof(kex_algs)-1)
2398 ssh2_pkt_addstring_str(",");
2400 /* List server host key algorithms. */
2401 ssh2_pkt_addstring_start();
2402 for (i = 0; i < lenof(hostkey_algs); i++) {
2403 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
2404 if (i < lenof(hostkey_algs)-1)
2405 ssh2_pkt_addstring_str(",");
2407 /* List client->server encryption algorithms. */
2408 ssh2_pkt_addstring_start();
2409 for (i = 0; i < lenof(ciphers)+1; i++) {
2410 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2411 for (j = 0; j < c->nciphers; j++) {
2412 ssh2_pkt_addstring_str(c->list[j]->name);
2413 if (i < lenof(ciphers) || j < c->nciphers-1)
2414 ssh2_pkt_addstring_str(",");
2417 /* List server->client encryption algorithms. */
2418 ssh2_pkt_addstring_start();
2419 for (i = 0; i < lenof(ciphers)+1; i++) {
2420 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2421 for (j = 0; j < c->nciphers; j++) {
2422 ssh2_pkt_addstring_str(c->list[j]->name);
2423 if (i < lenof(ciphers) || j < c->nciphers-1)
2424 ssh2_pkt_addstring_str(",");
2427 /* List client->server MAC algorithms. */
2428 ssh2_pkt_addstring_start();
2429 for (i = 0; i < nmacs; i++) {
2430 ssh2_pkt_addstring_str(maclist[i]->name);
2432 ssh2_pkt_addstring_str(",");
2434 /* List server->client MAC algorithms. */
2435 ssh2_pkt_addstring_start();
2436 for (i = 0; i < nmacs; i++) {
2437 ssh2_pkt_addstring_str(maclist[i]->name);
2439 ssh2_pkt_addstring_str(",");
2441 /* List client->server compression algorithms. */
2442 ssh2_pkt_addstring_start();
2443 for (i = 0; i < lenof(compressions)+1; i++) {
2444 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2445 ssh2_pkt_addstring_str(c->name);
2446 if (i < lenof(compressions))
2447 ssh2_pkt_addstring_str(",");
2449 /* List server->client compression algorithms. */
2450 ssh2_pkt_addstring_start();
2451 for (i = 0; i < lenof(compressions)+1; i++) {
2452 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2453 ssh2_pkt_addstring_str(c->name);
2454 if (i < lenof(compressions))
2455 ssh2_pkt_addstring_str(",");
2457 /* List client->server languages. Empty list. */
2458 ssh2_pkt_addstring_start();
2459 /* List server->client languages. Empty list. */
2460 ssh2_pkt_addstring_start();
2461 /* First KEX packet does _not_ follow, because we're not that brave. */
2462 ssh2_pkt_addbool(FALSE);
2464 ssh2_pkt_adduint32(0);
2466 exhash = exhashbase;
2467 sha_string(&exhash, pktout.data+5, pktout.length-5);
2471 if (!ispkt) crWaitUntil(ispkt);
2472 sha_string(&exhash, pktin.data+5, pktin.length-5);
2475 * Now examine the other side's KEXINIT to see what we're up
2478 if (pktin.type != SSH2_MSG_KEXINIT) {
2479 bombout(("expected key exchange packet from server"));
2482 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
2483 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
2484 pktin.savedpos += 16; /* skip garbage cookie */
2485 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
2486 for (i = 0; i < lenof(kex_algs); i++) {
2487 if (in_commasep_string(kex_algs[i]->name, str, len)) {
2492 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
2493 for (i = 0; i < lenof(hostkey_algs); i++) {
2494 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
2495 hostkey = hostkey_algs[i];
2499 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
2500 for (i = 0; i < lenof(ciphers)+1; i++) {
2501 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2502 for (j = 0; j < c->nciphers; j++) {
2503 if (in_commasep_string(c->list[j]->name, str, len)) {
2504 cscipher_tobe = c->list[j];
2511 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
2512 for (i = 0; i < lenof(ciphers)+1; i++) {
2513 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2514 for (j = 0; j < c->nciphers; j++) {
2515 if (in_commasep_string(c->list[j]->name, str, len)) {
2516 sccipher_tobe = c->list[j];
2523 ssh2_pkt_getstring(&str, &len); /* client->server mac */
2524 for (i = 0; i < nmacs; i++) {
2525 if (in_commasep_string(maclist[i]->name, str, len)) {
2526 csmac_tobe = maclist[i];
2530 ssh2_pkt_getstring(&str, &len); /* server->client mac */
2531 for (i = 0; i < nmacs; i++) {
2532 if (in_commasep_string(maclist[i]->name, str, len)) {
2533 scmac_tobe = maclist[i];
2537 ssh2_pkt_getstring(&str, &len); /* client->server compression */
2538 for (i = 0; i < lenof(compressions)+1; i++) {
2539 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2540 if (in_commasep_string(c->name, str, len)) {
2545 ssh2_pkt_getstring(&str, &len); /* server->client compression */
2546 for (i = 0; i < lenof(compressions)+1; i++) {
2547 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2548 if (in_commasep_string(c->name, str, len)) {
2555 * If we're doing Diffie-Hellman group exchange, start by
2556 * requesting a group.
2558 if (kex == &ssh_diffiehellman_gex) {
2561 logevent("Doing Diffie-Hellman group exchange");
2563 * Work out number of bits. We start with the maximum key
2564 * length of either cipher...
2566 csbits = cscipher_tobe->keylen;
2567 scbits = sccipher_tobe->keylen;
2568 nbits = (csbits > scbits ? csbits : scbits);
2569 /* The keys only have 160-bit entropy, since they're based on
2570 * a SHA-1 hash. So cap the key size at 160 bits. */
2571 if (nbits > 160) nbits = 160;
2573 * ... and then work out how big a DH group we will need to
2574 * allow that much data.
2576 nbits = 512 << ((nbits-1) / 64);
2577 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
2578 ssh2_pkt_adduint32(nbits);
2582 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
2583 bombout(("expected key exchange group packet from server"));
2586 p = ssh2_pkt_getmp();
2587 g = ssh2_pkt_getmp();
2588 dh_setup_group(p, g);
2589 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
2590 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
2593 kex_init_value = SSH2_MSG_KEXDH_INIT;
2594 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
2597 logevent("Doing Diffie-Hellman key exchange");
2599 * Now generate and send e for Diffie-Hellman.
2602 ssh2_pkt_init(kex_init_value);
2607 if (pktin.type != kex_reply_value) {
2608 bombout(("expected key exchange reply packet from server"));
2611 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2612 f = ssh2_pkt_getmp();
2613 ssh2_pkt_getstring(&sigdata, &siglen);
2617 sha_string(&exhash, hostkeydata, hostkeylen);
2618 if (kex == &ssh_diffiehellman_gex) {
2619 sha_uint32(&exhash, nbits);
2620 sha_mpint(&exhash, p);
2621 sha_mpint(&exhash, g);
2623 sha_mpint(&exhash, e);
2624 sha_mpint(&exhash, f);
2625 sha_mpint(&exhash, K);
2626 SHA_Final(&exhash, exchange_hash);
2631 debug(("Exchange hash is:\r\n"));
2632 for (i = 0; i < 20; i++)
2633 debug((" %02x", exchange_hash[i]));
2637 hkey = hostkey->newkey(hostkeydata, hostkeylen);
2638 if (!hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
2639 bombout(("Server failed host key check"));
2644 * Expect SSH2_MSG_NEWKEYS from server.
2647 if (pktin.type != SSH2_MSG_NEWKEYS) {
2648 bombout(("expected new-keys packet from server"));
2653 * Authenticate remote host: verify host key. (We've already
2654 * checked the signature of the exchange hash.)
2656 keystr = hostkey->fmtkey(hkey);
2657 fingerprint = hostkey->fingerprint(hkey);
2658 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
2659 keystr, fingerprint);
2660 if (first_kex) { /* don't bother logging this in rekeys */
2661 logevent("Host key fingerprint is:");
2662 logevent(fingerprint);
2666 hostkey->freekey(hkey);
2669 * Send SSH2_MSG_NEWKEYS.
2671 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2675 * Create and initialise session keys.
2677 cscipher = cscipher_tobe;
2678 sccipher = sccipher_tobe;
2681 cscomp = cscomp_tobe;
2682 sccomp = sccomp_tobe;
2683 cscomp->compress_init();
2684 sccomp->decompress_init();
2686 * Set IVs after keys. Here we use the exchange hash from the
2687 * _first_ key exchange.
2690 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
2691 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
2692 cscipher->setcskey(keyspace);
2693 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
2694 sccipher->setsckey(keyspace);
2695 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
2696 cscipher->setcsiv(keyspace);
2697 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
2698 sccipher->setsciv(keyspace);
2699 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
2700 csmac->setcskey(keyspace);
2701 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
2702 scmac->setsckey(keyspace);
2705 * If this is the first key exchange phase, we must pass the
2706 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2707 * wants to see it but because it will need time to initialise
2708 * itself before it sees an actual packet. In subsequent key
2709 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2710 * it would only confuse the layer above.
2718 * Now we're encrypting. Begin returning 1 to the protocol main
2719 * function so that other things can run on top of the
2720 * transport. If we ever see a KEXINIT, we must go back to the
2723 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
2726 logevent("Server initiated key re-exchange");
2727 goto begin_key_exchange;
2733 * Add data to an SSH2 channel output buffer.
2735 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len) {
2736 if (c->v2.outbufsize <
2737 c->v2.outbuflen + len) {
2739 c->v2.outbuflen + len + 1024;
2740 c->v2.outbuffer = srealloc(c->v2.outbuffer,
2743 memcpy(c->v2.outbuffer + c->v2.outbuflen,
2745 c->v2.outbuflen += len;
2749 * Attempt to send data on an SSH2 channel.
2751 static void ssh2_try_send(struct ssh_channel *c) {
2752 while (c->v2.remwindow > 0 &&
2753 c->v2.outbuflen > 0) {
2754 unsigned len = c->v2.remwindow;
2755 if (len > c->v2.outbuflen)
2756 len = c->v2.outbuflen;
2757 if (len > c->v2.remmaxpkt)
2758 len = c->v2.remmaxpkt;
2759 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2760 ssh2_pkt_adduint32(c->remoteid);
2761 ssh2_pkt_addstring_start();
2762 ssh2_pkt_addstring_data(c->v2.outbuffer, len);
2764 c->v2.outbuflen -= len;
2765 memmove(c->v2.outbuffer, c->v2.outbuffer+len,
2767 c->v2.remwindow -= len;
2772 * Handle the SSH2 userauth and connection layers.
2774 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2776 static unsigned long remote_winsize;
2777 static unsigned long remote_maxpkt;
2779 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE, AUTH_PASSWORD
2783 AUTH_TYPE_PUBLICKEY,
2784 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
2785 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
2788 static int gotit, need_pw, can_pubkey, can_passwd;
2789 static int tried_pubkey_config, tried_agent;
2790 static int we_are_in;
2791 static char username[100];
2792 static char pwprompt[200];
2793 static char password[100];
2798 * Request userauth protocol, and await a response to it.
2800 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2801 ssh2_pkt_addstring("ssh-userauth");
2803 crWaitUntilV(ispkt);
2804 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2805 bombout(("Server refused user authentication protocol"));
2810 * We repeat this whole loop, including the username prompt,
2811 * until we manage a successful authentication. If the user
2812 * types the wrong _password_, they are sent back to the
2813 * beginning to try another username. (If they specify a
2814 * username in the config, they are never asked, even if they
2815 * do give a wrong password.)
2817 * I think this best serves the needs of
2819 * - the people who have no configuration, no keys, and just
2820 * want to try repeated (username,password) pairs until they
2821 * type both correctly
2823 * - people who have keys and configuration but occasionally
2824 * need to fall back to passwords
2826 * - people with a key held in Pageant, who might not have
2827 * logged in to a particular machine before; so they want to
2828 * type a username, and then _either_ their key will be
2829 * accepted, _or_ they will type a password. If they mistype
2830 * the username they will want to be able to get back and
2841 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2842 c_write_str("login as: ");
2845 crWaitUntilV(!ispkt);
2846 while (inlen--) switch (c = *in++) {
2853 c_write_str("\b \b");
2859 c_write_str("\b \b");
2868 if (((c >= ' ' && c <= '~') ||
2869 ((unsigned char)c >= 160)) && pos < 40) {
2870 username[pos++] = c;
2876 c_write_str("\r\n");
2877 username[strcspn(username, "\n\r")] = '\0';
2880 strncpy(username, cfg.username, 99);
2881 username[99] = '\0';
2882 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
2883 sprintf(stuff, "Using username \"%s\".\r\n", username);
2889 * Send an authentication request using method "none": (a)
2890 * just in case it succeeds, and (b) so that we know what
2891 * authentication methods we can usefully try next.
2893 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2894 ssh2_pkt_addstring(username);
2895 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2896 ssh2_pkt_addstring("none"); /* method */
2898 type = AUTH_TYPE_NONE;
2902 tried_pubkey_config = FALSE;
2903 tried_agent = FALSE;
2907 * Wait for the result of the last authentication request.
2910 crWaitUntilV(ispkt);
2911 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
2912 /* FIXME: should support this */
2913 crWaitUntilV(ispkt);
2915 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
2916 logevent("Access granted");
2921 if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
2922 bombout(("Strange packet received during authentication: type %d",
2929 * OK, we're now sitting on a USERAUTH_FAILURE message, so
2930 * we can look at the string in it and know what we can
2931 * helpfully try next.
2936 ssh2_pkt_getstring(&methods, &methlen);
2937 if (!ssh2_pkt_getbool()) {
2939 * We have received an unequivocal Access
2940 * Denied. This can translate to a variety of
2943 * - if we'd just tried "none" authentication,
2944 * it's not worth printing anything at all
2946 * - if we'd just tried a public key _offer_,
2947 * the message should be "Server refused our
2948 * key" (or no message at all if the key
2949 * came from Pageant)
2951 * - if we'd just tried anything else, the
2952 * message really should be "Access denied".
2954 * Additionally, if we'd just tried password
2955 * authentication, we should break out of this
2956 * whole loop so as to go back to the username
2959 if (type == AUTH_TYPE_NONE) {
2961 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
2962 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
2963 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
2964 c_write_str("Server refused our key\r\n");
2965 logevent("Server refused public key");
2967 c_write_str("Access denied\r\n");
2968 logevent("Access denied");
2969 if (type == AUTH_TYPE_PASSWORD) {
2975 c_write_str("Further authentication required\r\n");
2976 logevent("Further authentication required");
2979 can_pubkey = in_commasep_string("publickey", methods, methlen);
2980 can_passwd = in_commasep_string("password", methods, methlen);
2985 if (!method && can_pubkey && agent_exists && !tried_agent) {
2987 * Attempt public-key authentication using Pageant.
2989 static unsigned char request[5], *response, *p;
2990 static int responselen;
2991 static int i, nkeys;
2992 static int authed = FALSE;
2997 logevent("Pageant is running. Requesting keys.");
2999 /* Request the keys held by the agent. */
3000 PUT_32BIT(request, 1);
3001 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
3002 agent_query(request, 5, &r, &responselen);
3003 response = (unsigned char *)r;
3006 nkeys = GET_32BIT(p); p += 4;
3007 { char buf[64]; sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
3009 for (i = 0; i < nkeys; i++) {
3010 static char *pkblob, *alg, *commentp;
3011 static int pklen, alglen, commentlen;
3012 static int siglen, retlen, len;
3013 static char *q, *agentreq, *ret;
3015 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
3017 pklen = GET_32BIT(p); p += 4;
3018 pkblob = p; p += pklen;
3019 alglen = GET_32BIT(pkblob);
3021 commentlen = GET_32BIT(p); p += 4;
3022 commentp = p; p += commentlen;
3023 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3024 ssh2_pkt_addstring(username);
3025 ssh2_pkt_addstring("ssh-connection");/* service requested */
3026 ssh2_pkt_addstring("publickey");/* method */
3027 ssh2_pkt_addbool(FALSE); /* no signature included */
3028 ssh2_pkt_addstring_start();
3029 ssh2_pkt_addstring_data(alg, alglen);
3030 ssh2_pkt_addstring_start();
3031 ssh2_pkt_addstring_data(pkblob, pklen);
3034 crWaitUntilV(ispkt);
3035 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3036 logevent("Key refused");
3040 c_write_str("Authenticating with public key \"");
3041 c_write(commentp, commentlen);
3042 c_write_str("\" from agent\r\n");
3045 * Server is willing to accept the key.
3046 * Construct a SIGN_REQUEST.
3048 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3049 ssh2_pkt_addstring(username);
3050 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3051 ssh2_pkt_addstring("publickey"); /* method */
3052 ssh2_pkt_addbool(TRUE);
3053 ssh2_pkt_addstring_start();
3054 ssh2_pkt_addstring_data(alg, alglen);
3055 ssh2_pkt_addstring_start();
3056 ssh2_pkt_addstring_data(pkblob, pklen);
3058 siglen = pktout.length - 5 + 4 + 20;
3059 len = 1; /* message type */
3060 len += 4 + pklen; /* key blob */
3061 len += 4 + siglen; /* data to sign */
3062 len += 4; /* flags */
3063 agentreq = smalloc(4 + len);
3064 PUT_32BIT(agentreq, len);
3066 *q++ = SSH2_AGENTC_SIGN_REQUEST;
3067 PUT_32BIT(q, pklen); q += 4;
3068 memcpy(q, pkblob, pklen); q += pklen;
3069 PUT_32BIT(q, siglen); q += 4;
3070 /* Now the data to be signed... */
3071 PUT_32BIT(q, 20); q += 4;
3072 memcpy(q, ssh2_session_id, 20); q += 20;
3073 memcpy(q, pktout.data+5, pktout.length-5);
3074 q += pktout.length-5;
3075 /* And finally the (zero) flags word. */
3077 agent_query(agentreq, len+4, &ret, &retlen);
3080 if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
3081 logevent("Sending Pageant's response");
3082 ssh2_pkt_addstring_start();
3083 ssh2_pkt_addstring_data(ret+9, GET_32BIT(ret+5));
3088 logevent("Pageant failed to answer challenge");
3098 if (!method && can_pubkey && *cfg.keyfile && !tried_pubkey_config) {
3099 unsigned char *pub_blob;
3100 char *algorithm, *comment;
3103 tried_pubkey_config = TRUE;
3106 * Try the public key supplied in the configuration.
3108 * First, offer the public blob to see if the server is
3109 * willing to accept it.
3111 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
3114 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3115 ssh2_pkt_addstring(username);
3116 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3117 ssh2_pkt_addstring("publickey");/* method */
3118 ssh2_pkt_addbool(FALSE); /* no signature included */
3119 ssh2_pkt_addstring(algorithm);
3120 ssh2_pkt_addstring_start();
3121 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
3123 logevent("Offered public key"); /* FIXME */
3125 crWaitUntilV(ispkt);
3126 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3128 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
3129 continue; /* key refused; give up on it */
3132 logevent("Offer of public key accepted");
3134 * Actually attempt a serious authentication using
3137 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
3138 sprintf(pwprompt, "Passphrase for key \"%.100s\": ", comment);
3143 c_write_str("Authenticating with public key \"");
3144 c_write_str(comment);
3145 c_write_str("\"\r\n");
3146 method = AUTH_PUBLICKEY_FILE;
3150 if (!method && can_passwd) {
3151 method = AUTH_PASSWORD;
3152 sprintf(pwprompt, "%.90s@%.90s's password: ", username, savedhost);
3157 if (ssh_get_password) {
3158 if (!ssh_get_password(pwprompt, password, sizeof(password))) {
3160 * get_password failed to get a password (for
3161 * example because one was supplied on the command
3162 * line which has already failed to work).
3165 logevent("No more passwords to try");
3166 ssh_state = SSH_STATE_CLOSED;
3173 c_write_str(pwprompt);
3178 crWaitUntilV(!ispkt);
3179 while (inlen--) switch (c = *in++) {
3196 if (((c >= ' ' && c <= '~') ||
3197 ((unsigned char)c >= 160)) && pos < 40)
3198 password[pos++] = c;
3202 c_write_str("\r\n");
3206 if (method == AUTH_PUBLICKEY_FILE) {
3208 * We have our passphrase. Now try the actual authentication.
3210 struct ssh2_userkey *key;
3212 key = ssh2_load_userkey(cfg.keyfile, password);
3213 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
3214 if (key == SSH2_WRONG_PASSPHRASE) {
3215 c_write_str("Wrong passphrase\r\n");
3216 tried_pubkey_config = FALSE;
3218 c_write_str("Unable to load private key\r\n");
3219 tried_pubkey_config = TRUE;
3221 /* Send a spurious AUTH_NONE to return to the top. */
3222 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3223 ssh2_pkt_addstring(username);
3224 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3225 ssh2_pkt_addstring("none"); /* method */
3227 type = AUTH_TYPE_NONE;
3229 unsigned char *blob, *sigdata;
3230 int blob_len, sigdata_len;
3233 * We have loaded the private key and the server
3234 * has announced that it's willing to accept it.
3235 * Hallelujah. Generate a signature and send it.
3237 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3238 ssh2_pkt_addstring(username);
3239 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3240 ssh2_pkt_addstring("publickey"); /* method */
3241 ssh2_pkt_addbool(TRUE);
3242 ssh2_pkt_addstring(key->alg->name);
3243 blob = key->alg->public_blob(key->data, &blob_len);
3244 ssh2_pkt_addstring_start();
3245 ssh2_pkt_addstring_data(blob, blob_len);
3249 * The data to be signed is:
3253 * followed by everything so far placed in the
3256 sigdata_len = pktout.length - 5 + 4 + 20;
3257 sigdata = smalloc(sigdata_len);
3258 PUT_32BIT(sigdata, 20);
3259 memcpy(sigdata+4, ssh2_session_id, 20);
3260 memcpy(sigdata+24, pktout.data+5, pktout.length-5);
3261 blob = key->alg->sign(key->data, sigdata, sigdata_len, &blob_len);
3262 ssh2_pkt_addstring_start();
3263 ssh2_pkt_addstring_data(blob, blob_len);
3268 type = AUTH_TYPE_PUBLICKEY;
3270 } else if (method == AUTH_PASSWORD) {
3272 * We send the password packet lumped tightly together with
3273 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3274 * string long enough to make the total length of the two
3275 * packets constant. This should ensure that a passive
3276 * listener doing traffic analyis can't work out the length
3279 * For this to work, we need an assumption about the
3280 * maximum length of the password packet. I think 256 is
3281 * pretty conservative. Anyone using a password longer than
3282 * that probably doesn't have much to worry about from
3283 * people who find out how long their password is!
3285 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3286 ssh2_pkt_addstring(username);
3287 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3288 ssh2_pkt_addstring("password");
3289 ssh2_pkt_addbool(FALSE);
3290 ssh2_pkt_addstring(password);
3293 * We'll include a string that's an exact multiple of the
3294 * cipher block size. If the cipher is NULL for some
3295 * reason, we don't do this trick at all because we gain
3301 stringlen = (256 - deferred_len);
3302 stringlen += cscipher->blksize - 1;
3303 stringlen -= (stringlen % cscipher->blksize);
3306 * Temporarily disable actual compression,
3307 * so we can guarantee to get this string
3308 * exactly the length we want it. The
3309 * compression-disabling routine should
3310 * return an integer indicating how many
3311 * bytes we should adjust our string length
3314 stringlen -= cscomp->disable_compression();
3316 ssh2_pkt_init(SSH2_MSG_IGNORE);
3317 ssh2_pkt_addstring_start();
3318 for (i = 0; i < stringlen; i++) {
3319 char c = (char)random_byte();
3320 ssh2_pkt_addstring_data(&c, 1);
3324 ssh_pkt_defersend();
3325 logevent("Sent password");
3326 type = AUTH_TYPE_PASSWORD;
3328 c_write_str("No supported authentication methods left to try!\r\n");
3329 logevent("No supported authentications offered. Disconnecting");
3330 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3331 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3332 ssh2_pkt_addstring("No supported authentication methods available");
3333 ssh2_pkt_addstring("en"); /* language tag */
3335 ssh_state = SSH_STATE_CLOSED;
3339 } while (!we_are_in);
3342 * Now we're authenticated for the connection protocol. The
3343 * connection protocol will automatically have started at this
3344 * point; there's no need to send SERVICE_REQUEST.
3348 * So now create a channel with a session in it.
3350 mainchan = smalloc(sizeof(struct ssh_channel));
3351 mainchan->localid = 100; /* as good as any */
3352 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
3353 ssh2_pkt_addstring("session");
3354 ssh2_pkt_adduint32(mainchan->localid);
3355 ssh2_pkt_adduint32(0x8000UL); /* our window size */
3356 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
3358 crWaitUntilV(ispkt);
3359 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
3360 bombout(("Server refused to open a session"));
3362 /* FIXME: error data comes back in FAILURE packet */
3364 if (ssh2_pkt_getuint32() != mainchan->localid) {
3365 bombout(("Server's channel confirmation cited wrong channel"));
3368 mainchan->remoteid = ssh2_pkt_getuint32();
3369 mainchan->type = CHAN_MAINSESSION;
3370 mainchan->closes = 0;
3371 mainchan->v2.remwindow = ssh2_pkt_getuint32();
3372 mainchan->v2.remmaxpkt = ssh2_pkt_getuint32();
3373 mainchan->v2.outbuffer = NULL;
3374 mainchan->v2.outbuflen = mainchan->v2.outbufsize = 0;
3375 ssh_channels = newtree234(ssh_channelcmp);
3376 add234(ssh_channels, mainchan);
3377 logevent("Opened channel for session");
3380 * Potentially enable X11 forwarding.
3382 if (cfg.x11_forward) {
3383 char proto[20], data[64];
3384 logevent("Requesting X11 forwarding");
3385 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3386 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3387 ssh2_pkt_adduint32(mainchan->remoteid);
3388 ssh2_pkt_addstring("x11-req");
3389 ssh2_pkt_addbool(1); /* want reply */
3390 ssh2_pkt_addbool(0); /* many connections */
3391 ssh2_pkt_addstring(proto);
3392 ssh2_pkt_addstring(data);
3393 ssh2_pkt_adduint32(0); /* screen number */
3397 crWaitUntilV(ispkt);
3398 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3399 unsigned i = ssh2_pkt_getuint32();
3400 struct ssh_channel *c;
3401 c = find234(ssh_channels, &i, ssh_channelfind);
3403 continue; /* nonexistent channel */
3404 c->v2.remwindow += ssh2_pkt_getuint32();
3406 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3408 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3409 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3410 bombout(("Server got confused by X11 forwarding request"));
3413 logevent("X11 forwarding refused");
3415 logevent("X11 forwarding enabled");
3416 ssh_X11_fwd_enabled = TRUE;
3421 * Potentially enable agent forwarding.
3423 if (cfg.agentfwd && agent_exists()) {
3424 char proto[20], data[64];
3425 logevent("Requesting OpenSSH-style agent forwarding");
3426 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3427 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3428 ssh2_pkt_adduint32(mainchan->remoteid);
3429 ssh2_pkt_addstring("auth-agent-req@openssh.com");
3430 ssh2_pkt_addbool(1); /* want reply */
3434 crWaitUntilV(ispkt);
3435 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3436 unsigned i = ssh2_pkt_getuint32();
3437 struct ssh_channel *c;
3438 c = find234(ssh_channels, &i, ssh_channelfind);
3440 continue; /* nonexistent channel */
3441 c->v2.remwindow += ssh2_pkt_getuint32();
3443 } 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 agent forwarding request"));
3450 logevent("Agent forwarding refused");
3452 logevent("Agent forwarding enabled");
3453 ssh_agentfwd_enabled = TRUE;
3458 * Now allocate a pty for the session.
3461 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3462 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
3463 ssh2_pkt_addstring("pty-req");
3464 ssh2_pkt_addbool(1); /* want reply */
3465 ssh2_pkt_addstring(cfg.termtype);
3466 ssh2_pkt_adduint32(cols);
3467 ssh2_pkt_adduint32(rows);
3468 ssh2_pkt_adduint32(0); /* pixel width */
3469 ssh2_pkt_adduint32(0); /* pixel height */
3470 ssh2_pkt_addstring_start();
3471 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3473 ssh_state = SSH_STATE_INTERMED;
3476 crWaitUntilV(ispkt);
3477 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3478 unsigned i = ssh2_pkt_getuint32();
3479 struct ssh_channel *c;
3480 c = find234(ssh_channels, &i, ssh_channelfind);
3482 continue; /* nonexistent channel */
3483 c->v2.remwindow += ssh2_pkt_getuint32();
3485 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3487 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3488 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3489 bombout(("Server got confused by pty request"));
3492 c_write_str("Server refused to allocate pty\r\n");
3493 ssh_editing = ssh_echoing = 1;
3495 logevent("Allocated pty");
3498 ssh_editing = ssh_echoing = 1;
3502 * Start a shell or a remote command.
3504 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3505 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
3506 if (cfg.ssh_subsys) {
3507 ssh2_pkt_addstring("subsystem");
3508 ssh2_pkt_addbool(1); /* want reply */
3509 ssh2_pkt_addstring(cfg.remote_cmd);
3510 } else if (*cfg.remote_cmd) {
3511 ssh2_pkt_addstring("exec");
3512 ssh2_pkt_addbool(1); /* want reply */
3513 ssh2_pkt_addstring(cfg.remote_cmd);
3515 ssh2_pkt_addstring("shell");
3516 ssh2_pkt_addbool(1); /* want reply */
3520 crWaitUntilV(ispkt);
3521 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3522 unsigned i = ssh2_pkt_getuint32();
3523 struct ssh_channel *c;
3524 c = find234(ssh_channels, &i, ssh_channelfind);
3526 continue; /* nonexistent channel */
3527 c->v2.remwindow += ssh2_pkt_getuint32();
3529 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3530 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3531 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3532 bombout(("Server got confused by shell/command request"));
3535 bombout(("Server refused to start a shell/command"));
3538 logevent("Started a shell/command");
3541 ssh_state = SSH_STATE_SESSION;
3545 ssh_special(TS_EOF);
3550 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
3553 static int try_send;
3557 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
3558 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
3561 unsigned i = ssh2_pkt_getuint32();
3562 struct ssh_channel *c;
3563 c = find234(ssh_channels, &i, ssh_channelfind);
3565 continue; /* nonexistent channel */
3566 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
3567 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
3568 continue; /* extended but not stderr */
3569 ssh2_pkt_getstring(&data, &length);
3572 case CHAN_MAINSESSION:
3573 from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
3577 x11_send(c->u.x11.s, data, length);
3580 while (length > 0) {
3581 if (c->u.a.lensofar < 4) {
3582 int l = min(4 - c->u.a.lensofar, length);
3583 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
3584 data += l; length -= l; c->u.a.lensofar += l;
3586 if (c->u.a.lensofar == 4) {
3587 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
3588 c->u.a.message = smalloc(c->u.a.totallen);
3589 memcpy(c->u.a.message, c->u.a.msglen, 4);
3591 if (c->u.a.lensofar >= 4 && length > 0) {
3592 int l = min(c->u.a.totallen - c->u.a.lensofar,
3594 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
3595 data += l; length -= l; c->u.a.lensofar += l;
3597 if (c->u.a.lensofar == c->u.a.totallen) {
3598 void *reply, *sentreply;
3600 agent_query(c->u.a.message, c->u.a.totallen,
3605 /* Fake SSH_AGENT_FAILURE. */
3606 sentreply = "\0\0\0\1\5";
3609 ssh2_add_channel_data(c, sentreply, replylen);
3613 sfree(c->u.a.message);
3614 c->u.a.lensofar = 0;
3620 * Enlarge the window again at the remote
3621 * side, just in case it ever runs down and
3622 * they fail to send us any more data.
3624 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3625 ssh2_pkt_adduint32(c->remoteid);
3626 ssh2_pkt_adduint32(length);
3629 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
3630 ssh_state = SSH_STATE_CLOSED;
3631 logevent("Received disconnect message");
3633 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
3634 continue; /* exit status et al; ignore (FIXME?) */
3635 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
3636 unsigned i = ssh2_pkt_getuint32();
3637 struct ssh_channel *c;
3639 c = find234(ssh_channels, &i, ssh_channelfind);
3641 continue; /* nonexistent channel */
3643 if (c->type == CHAN_X11) {
3645 * Remote EOF on an X11 channel means we should
3646 * wrap up and close the channel ourselves.
3648 x11_close(c->u.x11.s);
3650 } else if (c->type == CHAN_AGENT) {
3653 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
3654 unsigned i = ssh2_pkt_getuint32();
3655 struct ssh_channel *c;
3658 c = find234(ssh_channels, &i, ssh_channelfind);
3660 continue; /* nonexistent channel */
3661 if (c->closes == 0) {
3662 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3663 ssh2_pkt_adduint32(c->remoteid);
3666 /* Do pre-close processing on the channel. */
3668 case CHAN_MAINSESSION:
3669 break; /* nothing to see here, move along */
3675 del234(ssh_channels, c);
3676 sfree(c->v2.outbuffer);
3680 * See if that was the last channel left open.
3682 c = first234(ssh_channels, &e);
3684 logevent("All channels closed. Disconnecting");
3685 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3686 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3687 ssh2_pkt_addstring("All open channels closed");
3688 ssh2_pkt_addstring("en"); /* language tag */
3690 ssh_state = SSH_STATE_CLOSED;
3693 continue; /* remote sends close; ignore (FIXME) */
3694 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3695 unsigned i = ssh2_pkt_getuint32();
3696 struct ssh_channel *c;
3697 c = find234(ssh_channels, &i, ssh_channelfind);
3699 continue; /* nonexistent channel */
3700 mainchan->v2.remwindow += ssh2_pkt_getuint32();
3702 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
3706 struct ssh_channel *c;
3707 ssh2_pkt_getstring(&type, &typelen);
3708 c = smalloc(sizeof(struct ssh_channel));
3710 if (typelen == 3 && !memcmp(type, "x11", 3)) {
3711 if (!ssh_X11_fwd_enabled)
3712 error = "X11 forwarding is not enabled";
3713 else if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
3714 error = "Unable to open an X11 connection";
3718 } else if (typelen == 22 &&
3719 !memcmp(type, "auth-agent@openssh.com", 3)) {
3720 if (!ssh_agentfwd_enabled)
3721 error = "Agent forwarding is not enabled";
3723 c->type = CHAN_AGENT; /* identify channel type */
3724 c->u.a.lensofar = 0;
3727 error = "Unsupported channel type requested";
3730 c->remoteid = ssh2_pkt_getuint32();
3732 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
3733 ssh2_pkt_adduint32(c->remoteid);
3734 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
3735 ssh2_pkt_addstring(error);
3736 ssh2_pkt_addstring("en"); /* language tag */
3740 struct ssh_channel *d;
3744 for (i=1, d = first234(ssh_channels, &e); d;
3747 break; /* found a free number */
3752 c->v2.remwindow = ssh2_pkt_getuint32();
3753 c->v2.remmaxpkt = ssh2_pkt_getuint32();
3754 c->v2.outbuffer = NULL;
3755 c->v2.outbuflen = c->v2.outbufsize = 0;
3756 add234(ssh_channels, c);
3757 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
3758 ssh2_pkt_adduint32(c->remoteid);
3759 ssh2_pkt_adduint32(c->localid);
3760 ssh2_pkt_adduint32(0x8000UL); /* our window size */
3761 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
3765 bombout(("Strange packet received: type %d", pktin.type));
3770 * We have spare data. Add it to the channel buffer.
3772 ssh2_add_channel_data(mainchan, in, inlen);
3777 struct ssh_channel *c;
3779 * Try to send data on all channels if we can.
3781 for (c = first234(ssh_channels, &e); c; c = next234(&e))
3790 * Handle the top-level SSH2 protocol.
3792 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
3794 if (do_ssh2_transport(in, inlen, ispkt) == 0)
3796 do_ssh2_authconn(in, inlen, ispkt);
3800 * Called to set up the connection.
3802 * Returns an error message, or NULL on success.
3804 static char *ssh_init (char *host, int port, char **realhost) {
3808 if(crypto_startup() == 0)
3809 return "Microsoft high encryption pack not installed!";
3816 p = connect_to_host(host, port, realhost);
3824 * Called to send data down the Telnet connection.
3826 static void ssh_send (char *buf, int len) {
3827 if (s == NULL || ssh_protocol == NULL)
3830 ssh_protocol(buf, len, 0);
3834 * Called to set the size of the window from SSH's POV.
3836 static void ssh_size(void) {
3837 switch (ssh_state) {
3838 case SSH_STATE_BEFORE_SIZE:
3839 case SSH_STATE_PREPACKET:
3840 case SSH_STATE_CLOSED:
3841 break; /* do nothing */
3842 case SSH_STATE_INTERMED:
3843 size_needed = TRUE; /* buffer for later */
3845 case SSH_STATE_SESSION:
3847 if (ssh_version == 1) {
3848 send_packet(SSH1_CMSG_WINDOW_SIZE,
3849 PKT_INT, rows, PKT_INT, cols,
3850 PKT_INT, 0, PKT_INT, 0, PKT_END);
3852 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3853 ssh2_pkt_adduint32(mainchan->remoteid);
3854 ssh2_pkt_addstring("window-change");
3855 ssh2_pkt_addbool(0);
3856 ssh2_pkt_adduint32(cols);
3857 ssh2_pkt_adduint32(rows);
3858 ssh2_pkt_adduint32(0);
3859 ssh2_pkt_adduint32(0);
3868 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3869 * can send an EOF and collect resulting output (e.g. `plink
3872 static void ssh_special (Telnet_Special code) {
3873 if (code == TS_EOF) {
3874 if (ssh_state != SSH_STATE_SESSION) {
3876 * Buffer the EOF in case we are pre-SESSION, so we can
3877 * send it as soon as we reach SESSION.
3883 if (ssh_version == 1) {
3884 send_packet(SSH1_CMSG_EOF, PKT_END);
3886 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
3887 ssh2_pkt_adduint32(mainchan->remoteid);
3890 logevent("Sent EOF message");
3891 } else if (code == TS_PING) {
3892 if (ssh_state == SSH_STATE_CLOSED || ssh_state == SSH_STATE_PREPACKET)
3894 if (ssh_version == 1) {
3895 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
3897 ssh2_pkt_init(SSH2_MSG_IGNORE);
3898 ssh2_pkt_addstring_start();
3906 static Socket ssh_socket(void) { return s; }
3908 static int ssh_sendok(void) { return ssh_send_ok; }
3910 static int ssh_ldisc(int option) {
3911 if (option == LD_ECHO) return ssh_echoing;
3912 if (option == LD_EDIT) return ssh_editing;
3916 Backend ssh_backend = {