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 : (void)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 SSH_AGENTC_REQUEST_RSA_IDENTITIES 1 /* 0x1 */
72 #define SSH_AGENT_RSA_IDENTITIES_ANSWER 2 /* 0x2 */
73 #define SSH_AGENTC_RSA_CHALLENGE 3 /* 0x3 */
74 #define SSH_AGENT_RSA_RESPONSE 4 /* 0x4 */
75 #define SSH_AGENT_FAILURE 5 /* 0x5 */
76 #define SSH_AGENT_SUCCESS 6 /* 0x6 */
77 #define SSH_AGENTC_ADD_RSA_IDENTITY 7 /* 0x7 */
78 #define SSH_AGENTC_REMOVE_RSA_IDENTITY 8 /* 0x8 */
80 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
81 #define SSH2_MSG_IGNORE 2 /* 0x2 */
82 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
83 #define SSH2_MSG_DEBUG 4 /* 0x4 */
84 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
85 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
86 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
87 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
88 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
89 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
90 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
91 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
92 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
93 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
94 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
95 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
96 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
97 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
98 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
99 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
100 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
101 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
102 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
103 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
104 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
105 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
106 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
107 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
108 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
109 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
111 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
112 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
113 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
114 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
115 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
116 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
117 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
118 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
119 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
120 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
121 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
123 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
124 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
125 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
126 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
128 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
130 #define GET_32BIT(cp) \
131 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
132 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
133 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
134 ((unsigned long)(unsigned char)(cp)[3]))
136 #define PUT_32BIT(cp, value) { \
137 (cp)[0] = (unsigned char)((value) >> 24); \
138 (cp)[1] = (unsigned char)((value) >> 16); \
139 (cp)[2] = (unsigned char)((value) >> 8); \
140 (cp)[3] = (unsigned char)(value); }
142 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
144 /* Coroutine mechanics for the sillier bits of the code */
145 #define crBegin1 static int crLine = 0;
146 #define crBegin2 switch(crLine) { case 0:;
147 #define crBegin crBegin1; crBegin2;
148 #define crFinish(z) } crLine = 0; return (z)
149 #define crFinishV } crLine = 0; return
150 #define crReturn(z) \
152 crLine=__LINE__; return (z); case __LINE__:;\
156 crLine=__LINE__; return; case __LINE__:;\
158 #define crStop(z) do{ crLine = 0; return (z); }while(0)
159 #define crStopV do{ crLine = 0; return; }while(0)
160 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
161 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
163 extern const struct ssh_cipher ssh_3des;
164 extern const struct ssh_cipher ssh_3des_ssh2;
165 extern const struct ssh_cipher ssh_des;
166 extern const struct ssh_cipher ssh_blowfish_ssh1;
167 extern const struct ssh_cipher ssh_blowfish_ssh2;
169 extern char *x11_init (Socket *, char *, void *);
170 extern void x11_close (Socket);
171 extern void x11_send (Socket , char *, int);
172 extern void x11_invent_auth(char *, int, char *, int);
175 * Ciphers for SSH2. We miss out single-DES because it isn't
176 * supported; also 3DES and Blowfish are both done differently from
177 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
178 * endianness and different-sized keys.)
180 const static struct ssh_cipher *ciphers[] = { &ssh_blowfish_ssh2, &ssh_3des_ssh2 };
182 extern const struct ssh_kex ssh_diffiehellman;
183 const static struct ssh_kex *kex_algs[] = { &ssh_diffiehellman };
185 extern const struct ssh_signkey ssh_dss;
186 const static struct ssh_signkey *hostkey_algs[] = { &ssh_dss };
188 extern const struct ssh_mac ssh_md5, ssh_sha1, ssh_sha1_buggy;
190 static void nullmac_key(unsigned char *key) { }
191 static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
192 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
193 const static struct ssh_mac ssh_mac_none = {
194 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
196 const static struct ssh_mac *macs[] = {
197 &ssh_sha1, &ssh_md5, &ssh_mac_none };
198 const static struct ssh_mac *buggymacs[] = {
199 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none };
201 static void ssh_comp_none_init(void) { }
202 static int ssh_comp_none_block(unsigned char *block, int len,
203 unsigned char **outblock, int *outlen) {
206 const static struct ssh_compress ssh_comp_none = {
208 ssh_comp_none_init, ssh_comp_none_block,
209 ssh_comp_none_init, ssh_comp_none_block
211 extern const struct ssh_compress ssh_zlib;
212 const static struct ssh_compress *compressions[] = {
213 &ssh_zlib, &ssh_comp_none };
215 enum { /* channel types */
222 * 2-3-4 tree storing channels.
225 unsigned remoteid, localid;
228 struct ssh2_data_channel {
229 unsigned char *outbuffer;
230 unsigned outbuflen, outbufsize;
231 unsigned remwindow, remmaxpkt;
234 struct ssh_agent_channel {
235 unsigned char *message;
236 unsigned char msglen[4];
237 int lensofar, totallen;
239 struct ssh_x11_channel {
254 static SHA_State exhash, exhashbase;
256 static Socket s = NULL;
258 static unsigned char session_key[32];
259 static int ssh1_compressing;
260 static int ssh_agentfwd_enabled;
261 static int ssh_X11_fwd_enabled;
262 static const struct ssh_cipher *cipher = NULL;
263 static const struct ssh_cipher *cscipher = NULL;
264 static const struct ssh_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 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
273 static char *savedhost;
274 static int savedport;
275 static int ssh_send_ok;
276 static int ssh_echoing, ssh_editing;
278 static tree234 *ssh_channels; /* indexed by local id */
279 static struct ssh_channel *mainchan; /* primary session channel */
283 SSH_STATE_BEFORE_SIZE,
287 } ssh_state = SSH_STATE_PREPACKET;
289 static int size_needed = FALSE, eof_needed = FALSE;
291 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
292 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
293 static unsigned char *deferred_send_data = NULL;
294 static int deferred_len = 0, deferred_size = 0;
296 static int ssh_version;
297 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
298 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
299 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
300 static void ssh_size(void);
301 static void ssh_special (Telnet_Special);
302 static void ssh2_try_send(struct ssh_channel *c);
303 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
305 static int (*s_rdpkt)(unsigned char **data, int *datalen);
307 static struct rdpkt1_state_tag {
308 long len, pad, biglen, to_read;
309 unsigned long realcrc, gotcrc;
315 static struct rdpkt2_state_tag {
316 long len, pad, payload, packetlen, maclen;
319 unsigned long incoming_sequence;
322 static int ssh_channelcmp(void *av, void *bv) {
323 struct ssh_channel *a = (struct ssh_channel *)av;
324 struct ssh_channel *b = (struct ssh_channel *)bv;
325 if (a->localid < b->localid) return -1;
326 if (a->localid > b->localid) return +1;
329 static int ssh_channelfind(void *av, void *bv) {
330 unsigned *a = (unsigned *)av;
331 struct ssh_channel *b = (struct ssh_channel *)bv;
332 if (*a < b->localid) return -1;
333 if (*a > b->localid) return +1;
337 static void c_write (char *buf, int len) {
338 if ((flags & FLAG_STDERR)) {
340 for (i = 0; i < len; i++)
342 fputc(buf[i], stderr);
345 from_backend(1, buf, len);
349 * Collect incoming data in the incoming packet buffer.
350 * Decipher and verify the packet when it is completely read.
351 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
352 * Update the *data and *datalen variables.
353 * Return the additional nr of bytes needed, or 0 when
354 * a complete packet is available.
356 static int ssh1_rdpkt(unsigned char **data, int *datalen)
358 struct rdpkt1_state_tag *st = &rdpkt1_state;
367 for (st->i = st->len = 0; st->i < 4; st->i++) {
368 while ((*datalen) == 0)
370 st->len = (st->len << 8) + **data;
371 (*data)++, (*datalen)--;
375 if (st->len == 0x52656d6f) { /* "Remo"te server has closed ... */
376 st->len = 0x300; /* big enough to carry to end */
380 st->pad = 8 - (st->len % 8);
381 st->biglen = st->len + st->pad;
382 pktin.length = st->len - 5;
384 if (pktin.maxlen < st->biglen) {
385 pktin.maxlen = st->biglen;
386 pktin.data = (pktin.data == NULL ? smalloc(st->biglen+APIEXTRA) :
387 srealloc(pktin.data, st->biglen+APIEXTRA));
389 fatalbox("Out of memory");
392 st->to_read = st->biglen;
394 while (st->to_read > 0) {
395 st->chunk = st->to_read;
396 while ((*datalen) == 0)
397 crReturn(st->to_read);
398 if (st->chunk > (*datalen))
399 st->chunk = (*datalen);
400 memcpy(st->p, *data, st->chunk);
402 *datalen -= st->chunk;
404 st->to_read -= st->chunk;
408 cipher->decrypt(pktin.data, st->biglen);
410 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
411 for (st->i = 0; st->i < st->biglen; st->i++)
412 debug((" %02x", (unsigned char)pktin.data[st->i]));
416 st->realcrc = crc32(pktin.data, st->biglen-4);
417 st->gotcrc = GET_32BIT(pktin.data+st->biglen-4);
418 if (st->gotcrc != st->realcrc) {
419 bombout(("Incorrect CRC received on packet"));
423 pktin.body = pktin.data + st->pad + 1;
425 if (ssh1_compressing) {
426 unsigned char *decompblk;
430 debug(("Packet payload pre-decompression:\n"));
431 for (i = -1; i < pktin.length; i++)
432 debug((" %02x", (unsigned char)pktin.body[i]));
435 zlib_decompress_block(pktin.body-1, pktin.length+1,
436 &decompblk, &decomplen);
438 if (pktin.maxlen < st->pad + decomplen) {
439 pktin.maxlen = st->pad + decomplen;
440 pktin.data = srealloc(pktin.data, pktin.maxlen+APIEXTRA);
441 pktin.body = pktin.data + st->pad + 1;
443 fatalbox("Out of memory");
446 memcpy(pktin.body-1, decompblk, decomplen);
448 pktin.length = decomplen-1;
450 debug(("Packet payload post-decompression:\n"));
451 for (i = -1; i < pktin.length; i++)
452 debug((" %02x", (unsigned char)pktin.body[i]));
457 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
458 pktin.type == SSH1_SMSG_STDERR_DATA ||
459 pktin.type == SSH1_MSG_DEBUG ||
460 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
461 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
462 long strlen = GET_32BIT(pktin.body);
463 if (strlen + 4 != pktin.length) {
464 bombout(("Received data packet with bogus string length"));
469 pktin.type = pktin.body[-1];
471 if (pktin.type == SSH1_MSG_DEBUG) {
472 /* log debug message */
474 int strlen = GET_32BIT(pktin.body);
475 strcpy(buf, "Remote: ");
476 if (strlen > 70) strlen = 70;
477 memcpy(buf+8, pktin.body+4, strlen);
478 buf[8+strlen] = '\0';
481 } else if (pktin.type == SSH1_MSG_IGNORE) {
489 static int ssh2_rdpkt(unsigned char **data, int *datalen)
491 struct rdpkt2_state_tag *st = &rdpkt2_state;
499 st->cipherblk = sccipher->blksize;
502 if (st->cipherblk < 8)
505 if (pktin.maxlen < st->cipherblk) {
506 pktin.maxlen = st->cipherblk;
507 pktin.data = (pktin.data == NULL ? smalloc(st->cipherblk+APIEXTRA) :
508 srealloc(pktin.data, st->cipherblk+APIEXTRA));
510 fatalbox("Out of memory");
514 * Acquire and decrypt the first block of the packet. This will
515 * contain the length and padding details.
517 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
518 while ((*datalen) == 0)
519 crReturn(st->cipherblk-st->i);
520 pktin.data[st->i] = *(*data)++;
524 if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
529 sccipher->decrypt(pktin.data, st->cipherblk);
532 * Now get the length and padding figures.
534 st->len = GET_32BIT(pktin.data);
535 st->pad = pktin.data[4];
538 * This enables us to deduce the payload length.
540 st->payload = st->len - st->pad - 1;
542 pktin.length = st->payload + 5;
545 * So now we can work out the total packet length.
547 st->packetlen = st->len + 4;
548 st->maclen = scmac ? scmac->len : 0;
551 * Adjust memory allocation if packet is too big.
553 if (pktin.maxlen < st->packetlen+st->maclen) {
554 pktin.maxlen = st->packetlen+st->maclen;
555 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
556 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
558 fatalbox("Out of memory");
562 * Read and decrypt the remainder of the packet.
564 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen; st->i++) {
565 while ((*datalen) == 0)
566 crReturn(st->packetlen + st->maclen - st->i);
567 pktin.data[st->i] = *(*data)++;
570 /* Decrypt everything _except_ the MAC. */
572 sccipher->decrypt(pktin.data + st->cipherblk,
573 st->packetlen - st->cipherblk);
576 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
577 for (st->i = 0; st->i < st->packetlen; st->i++)
578 debug((" %02x", (unsigned char)pktin.data[st->i]));
585 if (scmac && !scmac->verify(pktin.data, st->len+4, st->incoming_sequence)) {
586 bombout(("Incorrect MAC received on packet"));
589 st->incoming_sequence++; /* whether or not we MACed */
592 * Decompress packet payload.
595 unsigned char *newpayload;
597 if (sccomp && sccomp->decompress(pktin.data+5, pktin.length-5,
598 &newpayload, &newlen)) {
599 if (pktin.maxlen < newlen+5) {
600 pktin.maxlen = newlen+5;
601 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
602 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
604 fatalbox("Out of memory");
606 pktin.length = 5 + newlen;
607 memcpy(pktin.data+5, newpayload, newlen);
609 debug(("Post-decompression payload:\r\n"));
610 for (st->i = 0; st->i < newlen; st->i++)
611 debug((" %02x", (unsigned char)pktin.data[5+st->i]));
620 pktin.type = pktin.data[5];
622 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
623 goto next_packet; /* FIXME: print DEBUG message */
628 static void ssh1_pktout_size(int len) {
631 len += 5; /* type and CRC */
635 pktout.length = len-5;
636 if (pktout.maxlen < biglen) {
637 pktout.maxlen = biglen;
639 /* Allocate enough buffer space for extra block
640 * for MS CryptEncrypt() */
641 pktout.data = (pktout.data == NULL ? smalloc(biglen+12) :
642 srealloc(pktout.data, biglen+12));
644 pktout.data = (pktout.data == NULL ? smalloc(biglen+4) :
645 srealloc(pktout.data, biglen+4));
648 fatalbox("Out of memory");
650 pktout.body = pktout.data+4+pad+1;
653 static void s_wrpkt_start(int type, int len) {
654 ssh1_pktout_size(len);
658 static void s_wrpkt(void) {
659 int pad, len, biglen, i;
662 pktout.body[-1] = pktout.type;
664 if (ssh1_compressing) {
665 unsigned char *compblk;
668 debug(("Packet payload pre-compression:\n"));
669 for (i = -1; i < pktout.length; i++)
670 debug((" %02x", (unsigned char)pktout.body[i]));
673 zlib_compress_block(pktout.body-1, pktout.length+1,
675 ssh1_pktout_size(complen-1);
676 memcpy(pktout.body-1, compblk, complen);
679 debug(("Packet payload post-compression:\n"));
680 for (i = -1; i < pktout.length; i++)
681 debug((" %02x", (unsigned char)pktout.body[i]));
686 len = pktout.length + 5; /* type and CRC */
690 for (i=0; i<pad; i++)
691 pktout.data[i+4] = random_byte();
692 crc = crc32(pktout.data+4, biglen-4);
693 PUT_32BIT(pktout.data+biglen, crc);
694 PUT_32BIT(pktout.data, len);
697 debug(("Sending packet len=%d\r\n", biglen+4));
698 for (i = 0; i < biglen+4; i++)
699 debug((" %02x", (unsigned char)pktout.data[i]));
703 cipher->encrypt(pktout.data+4, biglen);
705 sk_write(s, pktout.data, biglen+4);
709 * Construct a packet with the specified contents and
710 * send it to the server.
712 static void send_packet(int pkttype, ...)
715 unsigned char *p, *argp, argchar;
716 unsigned long argint;
717 int pktlen, argtype, arglen;
721 va_start(args, pkttype);
722 while ((argtype = va_arg(args, int)) != PKT_END) {
725 (void) va_arg(args, int);
729 (void) va_arg(args, char);
733 (void) va_arg(args, unsigned char *);
734 arglen = va_arg(args, int);
738 argp = va_arg(args, unsigned char *);
739 arglen = strlen(argp);
740 pktlen += 4 + arglen;
743 bn = va_arg(args, Bignum);
744 pktlen += ssh1_bignum_length(bn);
752 s_wrpkt_start(pkttype, pktlen);
755 va_start(args, pkttype);
756 while ((argtype = va_arg(args, int)) != PKT_END) {
759 argint = va_arg(args, int);
760 PUT_32BIT(p, argint);
764 argchar = va_arg(args, unsigned char);
769 argp = va_arg(args, unsigned char *);
770 arglen = va_arg(args, int);
771 memcpy(p, argp, arglen);
775 argp = va_arg(args, unsigned char *);
776 arglen = strlen(argp);
777 PUT_32BIT(p, arglen);
778 memcpy(p + 4, argp, arglen);
782 bn = va_arg(args, Bignum);
783 p += ssh1_write_bignum(p, bn);
792 static int ssh_versioncmp(char *a, char *b) {
794 unsigned long av, bv;
796 av = strtoul(a, &ae, 10);
797 bv = strtoul(b, &be, 10);
798 if (av != bv) return (av < bv ? -1 : +1);
799 if (*ae == '.') ae++;
800 if (*be == '.') be++;
801 av = strtoul(ae, &ae, 10);
802 bv = strtoul(be, &be, 10);
803 if (av != bv) return (av < bv ? -1 : +1);
809 * Utility routine for putting an SSH-protocol `string' into a SHA
813 static void sha_string(SHA_State *s, void *str, int len) {
814 unsigned char lenblk[4];
815 PUT_32BIT(lenblk, len);
816 SHA_Bytes(s, lenblk, 4);
817 SHA_Bytes(s, str, len);
821 * SSH2 packet construction functions.
823 static void ssh2_pkt_ensure(int length) {
824 if (pktout.maxlen < length) {
825 pktout.maxlen = length + 256;
826 pktout.data = (pktout.data == NULL ? smalloc(pktout.maxlen+APIEXTRA) :
827 srealloc(pktout.data, pktout.maxlen+APIEXTRA));
829 fatalbox("Out of memory");
832 static void ssh2_pkt_adddata(void *data, int len) {
833 pktout.length += len;
834 ssh2_pkt_ensure(pktout.length);
835 memcpy(pktout.data+pktout.length-len, data, len);
837 static void ssh2_pkt_addbyte(unsigned char byte) {
838 ssh2_pkt_adddata(&byte, 1);
840 static void ssh2_pkt_init(int pkt_type) {
842 ssh2_pkt_addbyte((unsigned char)pkt_type);
844 static void ssh2_pkt_addbool(unsigned char value) {
845 ssh2_pkt_adddata(&value, 1);
847 static void ssh2_pkt_adduint32(unsigned long value) {
850 ssh2_pkt_adddata(x, 4);
852 static void ssh2_pkt_addstring_start(void) {
853 ssh2_pkt_adduint32(0);
854 pktout.savedpos = pktout.length;
856 static void ssh2_pkt_addstring_str(char *data) {
857 ssh2_pkt_adddata(data, strlen(data));
858 PUT_32BIT(pktout.data + pktout.savedpos - 4,
859 pktout.length - pktout.savedpos);
861 static void ssh2_pkt_addstring_data(char *data, int len) {
862 ssh2_pkt_adddata(data, len);
863 PUT_32BIT(pktout.data + pktout.savedpos - 4,
864 pktout.length - pktout.savedpos);
866 static void ssh2_pkt_addstring(char *data) {
867 ssh2_pkt_addstring_start();
868 ssh2_pkt_addstring_str(data);
870 static char *ssh2_mpint_fmt(Bignum b, int *len) {
873 p = smalloc(n * 2 + 1);
875 fatalbox("out of memory");
877 for (i = 0; i < n; i++) {
878 p[i*2+1] = (b[n-i] >> 8) & 0xFF;
879 p[i*2+2] = (b[n-i] ) & 0xFF;
882 while (p[i] == 0 && (p[i+1] & 0x80) == 0)
884 memmove(p, p+i, n*2+1-i);
888 static void ssh2_pkt_addmp(Bignum b) {
891 p = ssh2_mpint_fmt(b, &len);
892 ssh2_pkt_addstring_start();
893 ssh2_pkt_addstring_data(p, len);
898 * Construct an SSH2 final-form packet: compress it, encrypt it,
899 * put the MAC on it. Final packet, ready to be sent, is stored in
900 * pktout.data. Total length is returned.
902 static int ssh2_pkt_construct(void) {
903 int cipherblk, maclen, padding, i;
904 static unsigned long outgoing_sequence = 0;
907 * Compress packet payload.
910 debug(("Pre-compression payload:\r\n"));
911 for (i = 5; i < pktout.length; i++)
912 debug((" %02x", (unsigned char)pktout.data[i]));
916 unsigned char *newpayload;
918 if (cscomp && cscomp->compress(pktout.data+5, pktout.length-5,
919 &newpayload, &newlen)) {
921 ssh2_pkt_adddata(newpayload, newlen);
927 * Add padding. At least four bytes, and must also bring total
928 * length (minus MAC) up to a multiple of the block size.
930 cipherblk = cipher ? cipher->blksize : 8; /* block size */
931 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
933 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
934 maclen = csmac ? csmac->len : 0;
935 ssh2_pkt_ensure(pktout.length + padding + maclen);
936 pktout.data[4] = padding;
937 for (i = 0; i < padding; i++)
938 pktout.data[pktout.length + i] = random_byte();
939 PUT_32BIT(pktout.data, pktout.length + padding - 4);
941 csmac->generate(pktout.data, pktout.length + padding,
943 outgoing_sequence++; /* whether or not we MACed */
946 debug(("Sending packet len=%d\r\n", pktout.length+padding));
947 for (i = 0; i < pktout.length+padding; i++)
948 debug((" %02x", (unsigned char)pktout.data[i]));
953 cscipher->encrypt(pktout.data, pktout.length + padding);
955 /* Ready-to-send packet starts at pktout.data. We return length. */
956 return pktout.length + padding + maclen;
960 * Construct and send an SSH2 packet immediately.
962 static void ssh2_pkt_send(void) {
963 int len = ssh2_pkt_construct();
964 sk_write(s, pktout.data, len);
968 * Construct an SSH2 packet and add it to a deferred data block.
969 * Useful for sending multiple packets in a single sk_write() call,
970 * to prevent a traffic-analysing listener from being able to work
971 * out the length of any particular packet (such as the password
974 * Note that because SSH2 sequence-numbers its packets, this can
975 * NOT be used as an m4-style `defer' allowing packets to be
976 * constructed in one order and sent in another.
978 static void ssh2_pkt_defer(void) {
979 int len = ssh2_pkt_construct();
980 if (deferred_len + len > deferred_size) {
981 deferred_size = deferred_len + len + 128;
982 deferred_send_data = srealloc(deferred_send_data, deferred_size);
984 memcpy(deferred_send_data+deferred_len, pktout.data, len);
989 * Send the whole deferred data block constructed by
992 static void ssh2_pkt_defersend(void) {
993 sk_write(s, deferred_send_data, deferred_len);
994 deferred_len = deferred_size = 0;
995 sfree(deferred_send_data);
996 deferred_send_data = NULL;
1000 void bndebug(char *string, Bignum b) {
1003 p = ssh2_mpint_fmt(b, &len);
1004 debug(("%s", string));
1005 for (i = 0; i < len; i++)
1006 debug((" %02x", p[i]));
1012 static void sha_mpint(SHA_State *s, Bignum b) {
1015 p = ssh2_mpint_fmt(b, &len);
1016 sha_string(s, p, len);
1021 * SSH2 packet decode functions.
1023 static unsigned long ssh2_pkt_getuint32(void) {
1024 unsigned long value;
1025 if (pktin.length - pktin.savedpos < 4)
1026 return 0; /* arrgh, no way to decline (FIXME?) */
1027 value = GET_32BIT(pktin.data+pktin.savedpos);
1028 pktin.savedpos += 4;
1031 static void ssh2_pkt_getstring(char **p, int *length) {
1033 if (pktin.length - pktin.savedpos < 4)
1035 *length = GET_32BIT(pktin.data+pktin.savedpos);
1036 pktin.savedpos += 4;
1037 if (pktin.length - pktin.savedpos < *length)
1039 *p = pktin.data+pktin.savedpos;
1040 pktin.savedpos += *length;
1042 static Bignum ssh2_pkt_getmp(void) {
1047 ssh2_pkt_getstring(&p, &length);
1051 bombout(("internal error: Can't handle negative mpints"));
1054 b = newbn((length+1)/2);
1055 for (i = 0; i < length; i++) {
1058 b[j/2+1] |= ((unsigned char)p[i]) << 8;
1060 b[j/2+1] |= ((unsigned char)p[i]);
1062 while (b[0] > 1 && b[b[0]] == 0) b[0]--;
1066 static int do_ssh_init(unsigned char c) {
1068 static char version[10];
1069 static char vstring[80];
1070 static char vlog[sizeof(vstring)+20];
1075 /* Search for the string "SSH-" in the input. */
1078 static const int transS[] = { 1, 2, 2, 1 };
1079 static const int transH[] = { 0, 0, 3, 0 };
1080 static const int transminus[] = { 0, 0, 0, -1 };
1081 if (c == 'S') i = transS[i];
1082 else if (c == 'H') i = transH[i];
1083 else if (c == '-') i = transminus[i];
1087 crReturn(1); /* get another character */
1090 strcpy(vstring, "SSH-");
1094 crReturn(1); /* get another char */
1095 if (vsp < vstring+sizeof(vstring)-1)
1101 } else if (i < sizeof(version)-1)
1108 ssh_agentfwd_enabled = FALSE;
1109 rdpkt2_state.incoming_sequence = 0;
1112 sprintf(vlog, "Server version: %s", vstring);
1113 vlog[strcspn(vlog, "\r\n")] = '\0';
1117 * Server version "1.99" means we can choose whether we use v1
1118 * or v2 protocol. Choice is based on cfg.sshprot.
1120 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1122 * This is a v2 server. Begin v2 protocol.
1124 char *verstring = "SSH-2.0-PuTTY";
1125 SHA_Init(&exhashbase);
1127 * Hash our version string and their version string.
1129 sha_string(&exhashbase, verstring, strlen(verstring));
1130 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1131 sprintf(vstring, "%s\n", verstring);
1132 sprintf(vlog, "We claim version: %s", verstring);
1134 logevent("Using SSH protocol version 2");
1135 sk_write(s, vstring, strlen(vstring));
1136 ssh_protocol = ssh2_protocol;
1138 s_rdpkt = ssh2_rdpkt;
1141 * This is a v1 server. Begin v1 protocol.
1143 sprintf(vstring, "SSH-%s-PuTTY\n",
1144 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1145 sprintf(vlog, "We claim version: %s", vstring);
1146 vlog[strcspn(vlog, "\r\n")] = '\0';
1148 logevent("Using SSH protocol version 1");
1149 sk_write(s, vstring, strlen(vstring));
1150 ssh_protocol = ssh1_protocol;
1152 s_rdpkt = ssh1_rdpkt;
1154 ssh_state = SSH_STATE_BEFORE_SIZE;
1159 static void ssh_gotdata(unsigned char *data, int datalen)
1164 * To begin with, feed the characters one by one to the
1165 * protocol initialisation / selection function do_ssh_init().
1166 * When that returns 0, we're done with the initial greeting
1167 * exchange and can move on to packet discipline.
1172 crReturnV; /* more data please */
1173 ret = do_ssh_init(*data);
1180 * We emerge from that loop when the initial negotiation is
1181 * over and we have selected an s_rdpkt function. Now pass
1182 * everything to s_rdpkt, and then pass the resulting packets
1183 * to the proper protocol handler.
1188 while (datalen > 0) {
1189 if ( s_rdpkt(&data, &datalen) == 0 ) {
1190 ssh_protocol(NULL, 0, 1);
1191 if (ssh_state == SSH_STATE_CLOSED) {
1201 static int ssh_receive(Socket skt, int urgent, char *data, int len) {
1203 /* A socket error has occurred. */
1204 ssh_state = SSH_STATE_CLOSED;
1207 connection_fatal(data);
1210 /* Connection has closed. */
1211 ssh_state = SSH_STATE_CLOSED;
1216 ssh_gotdata (data, len);
1217 if (ssh_state == SSH_STATE_CLOSED) {
1228 * Connect to specified host and port.
1229 * Returns an error message, or NULL on success.
1230 * Also places the canonical host name into `realhost'.
1232 static char *connect_to_host(char *host, int port, char **realhost)
1241 savedhost = smalloc(1+strlen(host));
1243 fatalbox("Out of memory");
1244 strcpy(savedhost, host);
1247 port = 22; /* default ssh port */
1260 addr = sk_namelookup(host, realhost);
1261 if ( (err = sk_addr_error(addr)) )
1271 s = sk_new(addr, port, 0, 1, ssh_receive);
1272 if ( (err = sk_socket_error(s)) )
1276 sk_write(s, "connect ", 8);
1277 sk_write(s, FWhost, strlen(FWhost));
1280 sprintf(buf, " %d\n", FWport);
1281 sk_write(s, buf, strlen(buf));
1289 * Handle the key exchange and user authentication phases.
1291 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1294 unsigned char *rsabuf, *keystr1, *keystr2;
1295 unsigned char cookie[8];
1296 struct RSAKey servkey, hostkey;
1297 struct MD5Context md5c;
1298 static unsigned long supported_ciphers_mask, supported_auths_mask;
1299 static int tried_publickey;
1300 static unsigned char session_id[16];
1302 static char username[100];
1306 if (!ispkt) crWaitUntil(ispkt);
1308 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1309 bombout(("Public key packet not received"));
1313 logevent("Received public keys");
1315 memcpy(cookie, pktin.body, 8);
1317 i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1318 j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1321 * Log the host key fingerprint.
1325 logevent("Host key fingerprint is:");
1326 strcpy(logmsg, " ");
1327 hostkey.comment = NULL;
1328 rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
1333 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1334 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1337 MD5Update(&md5c, keystr2, hostkey.bytes);
1338 MD5Update(&md5c, keystr1, servkey.bytes);
1339 MD5Update(&md5c, pktin.body, 8);
1340 MD5Final(session_id, &md5c);
1342 for (i=0; i<32; i++)
1343 session_key[i] = random_byte();
1345 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1347 rsabuf = smalloc(len);
1349 fatalbox("Out of memory");
1352 * Verify the host key.
1356 * First format the key into a string.
1358 int len = rsastr_len(&hostkey);
1359 char fingerprint[100];
1360 char *keystr = smalloc(len);
1362 fatalbox("Out of memory");
1363 rsastr_fmt(keystr, &hostkey);
1364 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
1365 verify_ssh_host_key(savedhost, savedport, "rsa", keystr, fingerprint);
1369 for (i=0; i<32; i++) {
1370 rsabuf[i] = session_key[i];
1372 rsabuf[i] ^= session_id[i];
1375 if (hostkey.bytes > servkey.bytes) {
1376 rsaencrypt(rsabuf, 32, &servkey);
1377 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1379 rsaencrypt(rsabuf, 32, &hostkey);
1380 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1383 logevent("Encrypted session key");
1385 cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
1386 cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES :
1388 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1389 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1390 cipher_type = SSH_CIPHER_3DES;
1392 switch (cipher_type) {
1393 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1394 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1395 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1398 send_packet(SSH1_CMSG_SESSION_KEY,
1399 PKT_CHAR, cipher_type,
1400 PKT_DATA, cookie, 8,
1401 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1402 PKT_DATA, rsabuf, len,
1406 logevent("Trying to enable encryption...");
1410 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1411 cipher_type == SSH_CIPHER_DES ? &ssh_des :
1413 cipher->sesskey(session_key);
1417 if (pktin.type != SSH1_SMSG_SUCCESS) {
1418 bombout(("Encryption not successfully enabled"));
1422 logevent("Successfully started encryption");
1428 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1429 c_write("login as: ", 10);
1432 crWaitUntil(!ispkt);
1433 while (inlen--) switch (c = *in++) {
1440 c_write("\b \b", 3);
1446 c_write("\b \b", 3);
1455 if (((c >= ' ' && c <= '~') ||
1456 ((unsigned char)c >= 160)) && pos < 40) {
1457 username[pos++] = c;
1464 username[strcspn(username, "\n\r")] = '\0';
1466 strncpy(username, cfg.username, 99);
1467 username[99] = '\0';
1470 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1472 char userlog[22+sizeof(username)];
1473 sprintf(userlog, "Sent username \"%s\"", username);
1475 if (flags & FLAG_INTERACTIVE &&
1476 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
1477 strcat(userlog, "\r\n");
1478 c_write(userlog, strlen(userlog));
1485 tried_publickey = 0;
1487 while (pktin.type == SSH1_SMSG_FAILURE) {
1488 static char password[100];
1489 static char prompt[200];
1492 static int pwpkt_type;
1494 * Show password prompt, having first obtained it via a TIS
1495 * or CryptoCard exchange if we're doing TIS or CryptoCard
1498 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1499 if (agent_exists()) {
1501 * Attempt RSA authentication using Pageant.
1503 static unsigned char request[5], *response, *p;
1504 static int responselen;
1505 static int i, nkeys;
1506 static int authed = FALSE;
1509 logevent("Pageant is running. Requesting keys.");
1511 /* Request the keys held by the agent. */
1512 PUT_32BIT(request, 1);
1513 request[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
1514 agent_query(request, 5, &r, &responselen);
1515 response = (unsigned char *)r;
1518 nkeys = GET_32BIT(p); p += 4;
1519 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
1521 for (i = 0; i < nkeys; i++) {
1522 static struct RSAKey key;
1523 static Bignum challenge;
1524 static char *commentp;
1525 static int commentlen;
1527 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1530 p += ssh1_read_bignum(p, &key.exponent);
1531 p += ssh1_read_bignum(p, &key.modulus);
1532 commentlen = GET_32BIT(p); p += 4;
1533 commentp = p; p += commentlen;
1534 send_packet(SSH1_CMSG_AUTH_RSA,
1535 PKT_BIGNUM, key.modulus, PKT_END);
1537 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1538 logevent("Key refused");
1541 logevent("Received RSA challenge");
1542 ssh1_read_bignum(pktin.body, &challenge);
1544 char *agentreq, *q, *ret;
1546 len = 1 + 4; /* message type, bit count */
1547 len += ssh1_bignum_length(key.exponent);
1548 len += ssh1_bignum_length(key.modulus);
1549 len += ssh1_bignum_length(challenge);
1550 len += 16; /* session id */
1551 len += 4; /* response format */
1552 agentreq = smalloc(4 + len);
1553 PUT_32BIT(agentreq, len);
1555 *q++ = SSH_AGENTC_RSA_CHALLENGE;
1556 PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1558 q += ssh1_write_bignum(q, key.exponent);
1559 q += ssh1_write_bignum(q, key.modulus);
1560 q += ssh1_write_bignum(q, challenge);
1561 memcpy(q, session_id, 16); q += 16;
1562 PUT_32BIT(q, 1); /* response format */
1563 agent_query(agentreq, len+4, &ret, &retlen);
1566 if (ret[4] == SSH_AGENT_RSA_RESPONSE) {
1567 logevent("Sending Pageant's response");
1568 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1569 PKT_DATA, ret+5, 16, PKT_END);
1572 if (pktin.type == SSH1_SMSG_SUCCESS) {
1573 logevent("Pageant's response accepted");
1574 if (flags & FLAG_VERBOSE) {
1575 c_write("Authenticated using RSA key \"",
1577 c_write(commentp, commentlen);
1578 c_write("\" from agent\r\n", 14);
1582 logevent("Pageant's response not accepted");
1584 logevent("Pageant failed to answer challenge");
1588 logevent("No reply received from Pageant");
1591 freebn(key.exponent);
1592 freebn(key.modulus);
1601 if (*cfg.keyfile && !tried_publickey)
1602 pwpkt_type = SSH1_CMSG_AUTH_RSA;
1604 if (pktin.type == SSH1_SMSG_FAILURE &&
1606 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1607 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1608 logevent("Requested TIS authentication");
1609 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1611 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1612 logevent("TIS authentication declined");
1613 if (flags & FLAG_INTERACTIVE)
1614 c_write("TIS authentication refused.\r\n", 29);
1616 int challengelen = ((pktin.body[0] << 24) |
1617 (pktin.body[1] << 16) |
1618 (pktin.body[2] << 8) |
1620 logevent("Received TIS challenge");
1621 if (challengelen > sizeof(prompt)-1)
1622 challengelen = sizeof(prompt)-1; /* prevent overrun */
1623 memcpy(prompt, pktin.body+4, challengelen);
1624 prompt[challengelen] = '\0';
1627 if (pktin.type == SSH1_SMSG_FAILURE &&
1629 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1630 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1631 logevent("Requested CryptoCard authentication");
1632 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1634 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1635 logevent("CryptoCard authentication declined");
1636 c_write("CryptoCard authentication refused.\r\n", 29);
1638 int challengelen = ((pktin.body[0] << 24) |
1639 (pktin.body[1] << 16) |
1640 (pktin.body[2] << 8) |
1642 logevent("Received CryptoCard challenge");
1643 if (challengelen > sizeof(prompt)-1)
1644 challengelen = sizeof(prompt)-1; /* prevent overrun */
1645 memcpy(prompt, pktin.body+4, challengelen);
1646 strncpy(prompt + challengelen, "\r\nResponse : ",
1647 sizeof(prompt)-challengelen);
1648 prompt[sizeof(prompt)-1] = '\0';
1651 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1652 sprintf(prompt, "%.90s@%.90s's password: ",
1653 username, savedhost);
1655 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1656 char *comment = NULL;
1657 if (flags & FLAG_VERBOSE)
1658 c_write("Trying public key authentication.\r\n", 35);
1659 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1660 if (flags & FLAG_VERBOSE)
1661 c_write("No passphrase required.\r\n", 25);
1664 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
1668 if (ssh_get_password) {
1669 if (!ssh_get_password(prompt, password, sizeof(password))) {
1671 * get_password failed to get a password (for
1672 * example because one was supplied on the command
1673 * line which has already failed to work).
1676 logevent("No more passwords to try");
1677 ssh_state = SSH_STATE_CLOSED;
1681 c_write(prompt, strlen(prompt));
1685 crWaitUntil(!ispkt);
1686 while (inlen--) switch (c = *in++) {
1703 if (((c >= ' ' && c <= '~') ||
1704 ((unsigned char)c >= 160)) && pos < sizeof(password))
1705 password[pos++] = c;
1713 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1715 * Try public key authentication with the specified
1718 static struct RSAKey pubkey;
1719 static Bignum challenge, response;
1721 static unsigned char buffer[32];
1723 tried_publickey = 1;
1724 i = loadrsakey(cfg.keyfile, &pubkey, NULL, password);
1726 c_write("Couldn't load public key from ", 30);
1727 c_write(cfg.keyfile, strlen(cfg.keyfile));
1728 c_write(".\r\n", 3);
1729 continue; /* go and try password */
1732 c_write("Wrong passphrase.\r\n", 19);
1733 tried_publickey = 0;
1734 continue; /* try again */
1738 * Send a public key attempt.
1740 send_packet(SSH1_CMSG_AUTH_RSA,
1741 PKT_BIGNUM, pubkey.modulus, PKT_END);
1744 if (pktin.type == SSH1_SMSG_FAILURE) {
1745 c_write("Server refused our public key.\r\n", 32);
1746 continue; /* go and try password */
1748 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1749 bombout(("Bizarre response to offer of public key"));
1752 ssh1_read_bignum(pktin.body, &challenge);
1753 response = rsadecrypt(challenge, &pubkey);
1754 freebn(pubkey.private_exponent); /* burn the evidence */
1756 for (i = 0; i < 32; i += 2) {
1757 buffer[i] = response[16-i/2] >> 8;
1758 buffer[i+1] = response[16-i/2] & 0xFF;
1762 MD5Update(&md5c, buffer, 32);
1763 MD5Update(&md5c, session_id, 16);
1764 MD5Final(buffer, &md5c);
1766 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1767 PKT_DATA, buffer, 16, PKT_END);
1770 if (pktin.type == SSH1_SMSG_FAILURE) {
1771 if (flags & FLAG_VERBOSE)
1772 c_write("Failed to authenticate with our public key.\r\n",
1774 continue; /* go and try password */
1775 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1776 bombout(("Bizarre response to RSA authentication response"));
1780 break; /* we're through! */
1782 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1784 logevent("Sent password");
1785 memset(password, 0, strlen(password));
1787 if (pktin.type == SSH1_SMSG_FAILURE) {
1788 if (flags & FLAG_VERBOSE)
1789 c_write("Access denied\r\n", 15);
1790 logevent("Authentication refused");
1791 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1792 logevent("Received disconnect request");
1793 ssh_state = SSH_STATE_CLOSED;
1795 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1796 bombout(("Strange packet received, type %d", pktin.type));
1801 logevent("Authentication successful");
1806 void sshfwd_close(struct ssh_channel *c) {
1808 if (ssh_version == 1) {
1809 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END);
1811 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
1812 ssh2_pkt_adduint32(c->remoteid);
1816 if (c->type == CHAN_X11) {
1818 logevent("X11 connection terminated");
1823 void sshfwd_write(struct ssh_channel *c, char *buf, int len) {
1824 if (ssh_version == 1) {
1825 send_packet(SSH1_MSG_CHANNEL_DATA,
1826 PKT_INT, c->remoteid,
1831 ssh2_add_channel_data(c, buf, len);
1836 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1841 while (!do_ssh1_login(in, inlen, ispkt)) {
1844 if (ssh_state == SSH_STATE_CLOSED)
1847 if (cfg.agentfwd && agent_exists()) {
1848 logevent("Requesting agent forwarding");
1849 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1850 do { crReturnV; } while (!ispkt);
1851 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1852 bombout(("Protocol confusion"));
1854 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1855 logevent("Agent forwarding refused");
1857 logevent("Agent forwarding enabled");
1858 ssh_agentfwd_enabled = TRUE;
1862 if (cfg.x11_forward) {
1863 char proto[20], data[64];
1864 logevent("Requesting X11 forwarding");
1865 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
1866 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
1867 PKT_STR, proto, PKT_STR, data,
1870 do { crReturnV; } while (!ispkt);
1871 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1872 bombout(("Protocol confusion"));
1874 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1875 logevent("X11 forwarding refused");
1877 logevent("X11 forwarding enabled");
1878 ssh_X11_fwd_enabled = TRUE;
1883 send_packet(SSH1_CMSG_REQUEST_PTY,
1884 PKT_STR, cfg.termtype,
1885 PKT_INT, rows, PKT_INT, cols,
1886 PKT_INT, 0, PKT_INT, 0,
1889 ssh_state = SSH_STATE_INTERMED;
1890 do { crReturnV; } while (!ispkt);
1891 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1892 bombout(("Protocol confusion"));
1894 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1895 c_write("Server refused to allocate pty\r\n", 32);
1896 ssh_editing = ssh_echoing = 1;
1898 logevent("Allocated pty");
1900 ssh_editing = ssh_echoing = 1;
1903 if (cfg.compression) {
1904 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
1905 do { crReturnV; } while (!ispkt);
1906 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1907 bombout(("Protocol confusion"));
1909 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1910 c_write("Server refused to compress\r\n", 32);
1912 logevent("Started compression");
1913 ssh1_compressing = TRUE;
1914 zlib_compress_init();
1915 zlib_decompress_init();
1918 if (*cfg.remote_cmd)
1919 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1921 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1922 logevent("Started session");
1924 ssh_state = SSH_STATE_SESSION;
1928 ssh_special(TS_EOF);
1930 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
1932 ssh_channels = newtree234(ssh_channelcmp);
1936 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1937 pktin.type == SSH1_SMSG_STDERR_DATA) {
1938 long len = GET_32BIT(pktin.body);
1939 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
1941 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1942 ssh_state = SSH_STATE_CLOSED;
1943 logevent("Received disconnect request");
1945 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
1946 /* Remote side is trying to open a channel to talk to our
1947 * X-Server. Give them back a local channel number. */
1949 struct ssh_channel *c, *d;
1952 logevent("Received X11 connect request");
1953 /* Refuse if X11 forwarding is disabled. */
1954 if (!ssh_X11_fwd_enabled) {
1955 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1956 PKT_INT, GET_32BIT(pktin.body),
1958 logevent("Rejected X11 connect request");
1960 c = smalloc(sizeof(struct ssh_channel));
1962 if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
1963 logevent("opening X11 forward connection failed");
1965 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1966 PKT_INT, GET_32BIT(pktin.body),
1969 logevent("opening X11 forward connection succeeded");
1970 for (i=1, d = first234(ssh_channels, &e); d; d = next234(&e)) {
1972 break; /* found a free number */
1975 c->remoteid = GET_32BIT(pktin.body);
1978 c->type = CHAN_X11; /* identify channel type */
1979 add234(ssh_channels, c);
1980 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1981 PKT_INT, c->remoteid, PKT_INT, c->localid,
1983 logevent("Opened X11 forward channel");
1986 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
1987 /* Remote side is trying to open a channel to talk to our
1988 * agent. Give them back a local channel number. */
1990 struct ssh_channel *c;
1993 /* Refuse if agent forwarding is disabled. */
1994 if (!ssh_agentfwd_enabled) {
1995 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1996 PKT_INT, GET_32BIT(pktin.body),
2000 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
2002 break; /* found a free number */
2005 c = smalloc(sizeof(struct ssh_channel));
2006 c->remoteid = GET_32BIT(pktin.body);
2009 c->type = CHAN_AGENT; /* identify channel type */
2010 c->u.a.lensofar = 0;
2011 add234(ssh_channels, c);
2012 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2013 PKT_INT, c->remoteid, PKT_INT, c->localid,
2016 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2017 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
2018 /* Remote side closes a channel. */
2019 unsigned i = GET_32BIT(pktin.body);
2020 struct ssh_channel *c;
2021 c = find234(ssh_channels, &i, ssh_channelfind);
2024 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2025 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
2026 if ((c->closes == 0) && (c->type == CHAN_X11)) {
2027 logevent("X11 connection closed");
2028 assert(c->u.x11.s != NULL);
2029 x11_close(c->u.x11.s);
2032 c->closes |= closetype;
2033 if (c->closes == 3) {
2034 del234(ssh_channels, c);
2038 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2039 /* Data sent down one of our channels. */
2040 int i = GET_32BIT(pktin.body);
2041 int len = GET_32BIT(pktin.body+4);
2042 unsigned char *p = pktin.body+8;
2043 struct ssh_channel *c;
2044 c = find234(ssh_channels, &i, ssh_channelfind);
2048 x11_send(c->u.x11.s, p, len);
2051 /* Data for an agent message. Buffer it. */
2053 if (c->u.a.lensofar < 4) {
2054 int l = min(4 - c->u.a.lensofar, len);
2055 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
2056 p += l; len -= l; c->u.a.lensofar += l;
2058 if (c->u.a.lensofar == 4) {
2059 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
2060 c->u.a.message = smalloc(c->u.a.totallen);
2061 memcpy(c->u.a.message, c->u.a.msglen, 4);
2063 if (c->u.a.lensofar >= 4 && len > 0) {
2064 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
2065 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
2066 p += l; len -= l; c->u.a.lensofar += l;
2068 if (c->u.a.lensofar == c->u.a.totallen) {
2069 void *reply, *sentreply;
2071 agent_query(c->u.a.message, c->u.a.totallen,
2076 /* Fake SSH_AGENT_FAILURE. */
2077 sentreply = "\0\0\0\1\5";
2080 send_packet(SSH1_MSG_CHANNEL_DATA,
2081 PKT_INT, c->remoteid,
2083 PKT_DATA, sentreply, replylen,
2087 sfree(c->u.a.message);
2088 c->u.a.lensofar = 0;
2094 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
2095 /* may be from EXEC_SHELL on some servers */
2096 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2097 /* may be from EXEC_SHELL on some servers
2098 * if no pty is available or in other odd cases. Ignore */
2099 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2100 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2102 bombout(("Strange packet received: type %d", pktin.type));
2107 int len = min(inlen, 512);
2108 send_packet(SSH1_CMSG_STDIN_DATA,
2109 PKT_INT, len, PKT_DATA, in, len, PKT_END);
2120 * Utility routine for decoding comma-separated strings in KEXINIT.
2122 static int in_commasep_string(char *needle, char *haystack, int haylen) {
2123 int needlen = strlen(needle);
2126 * Is it at the start of the string?
2128 if (haylen >= needlen && /* haystack is long enough */
2129 !memcmp(needle, haystack, needlen) && /* initial match */
2130 (haylen == needlen || haystack[needlen] == ',')
2131 /* either , or EOS follows */
2135 * If not, search for the next comma and resume after that.
2136 * If no comma found, terminate.
2138 while (haylen > 0 && *haystack != ',')
2139 haylen--, haystack++;
2142 haylen--, haystack++; /* skip over comma itself */
2147 * SSH2 key creation method.
2149 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr, char *keyspace) {
2151 /* First 20 bytes. */
2154 SHA_Bytes(&s, H, 20);
2155 SHA_Bytes(&s, &chr, 1);
2156 SHA_Bytes(&s, sessid, 20);
2157 SHA_Final(&s, keyspace);
2158 /* Next 20 bytes. */
2161 SHA_Bytes(&s, H, 20);
2162 SHA_Bytes(&s, keyspace, 20);
2163 SHA_Final(&s, keyspace+20);
2167 * Handle the SSH2 transport layer.
2169 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
2173 static Bignum e, f, K;
2174 static const struct ssh_mac **maclist;
2176 static const struct ssh_cipher *cscipher_tobe = NULL;
2177 static const struct ssh_cipher *sccipher_tobe = NULL;
2178 static const struct ssh_mac *csmac_tobe = NULL;
2179 static const struct ssh_mac *scmac_tobe = NULL;
2180 static const struct ssh_compress *cscomp_tobe = NULL;
2181 static const struct ssh_compress *sccomp_tobe = NULL;
2182 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
2183 static int hostkeylen, siglen;
2184 static void *hkey; /* actual host key */
2185 static unsigned char exchange_hash[20];
2186 static unsigned char first_exchange_hash[20];
2187 static unsigned char keyspace[40];
2188 static const struct ssh_cipher *preferred_cipher;
2189 static const struct ssh_compress *preferred_comp;
2190 static int first_kex;
2197 * Set up the preferred cipher and compression.
2199 if (cfg.cipher == CIPHER_BLOWFISH) {
2200 preferred_cipher = &ssh_blowfish_ssh2;
2201 } else if (cfg.cipher == CIPHER_DES) {
2202 logevent("Single DES not supported in SSH2; using 3DES");
2203 preferred_cipher = &ssh_3des_ssh2;
2204 } else if (cfg.cipher == CIPHER_3DES) {
2205 preferred_cipher = &ssh_3des_ssh2;
2207 /* Shouldn't happen, but we do want to initialise to _something_. */
2208 preferred_cipher = &ssh_3des_ssh2;
2210 if (cfg.compression)
2211 preferred_comp = &ssh_zlib;
2213 preferred_comp = &ssh_comp_none;
2216 * Be prepared to work around the buggy MAC problem.
2219 maclist = buggymacs, nmacs = lenof(buggymacs);
2221 maclist = macs, nmacs = lenof(macs);
2225 * Construct and send our key exchange packet.
2227 ssh2_pkt_init(SSH2_MSG_KEXINIT);
2228 for (i = 0; i < 16; i++)
2229 ssh2_pkt_addbyte((unsigned char)random_byte());
2230 /* List key exchange algorithms. */
2231 ssh2_pkt_addstring_start();
2232 for (i = 0; i < lenof(kex_algs); i++) {
2233 ssh2_pkt_addstring_str(kex_algs[i]->name);
2234 if (i < lenof(kex_algs)-1)
2235 ssh2_pkt_addstring_str(",");
2237 /* List server host key algorithms. */
2238 ssh2_pkt_addstring_start();
2239 for (i = 0; i < lenof(hostkey_algs); i++) {
2240 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
2241 if (i < lenof(hostkey_algs)-1)
2242 ssh2_pkt_addstring_str(",");
2244 /* List client->server encryption algorithms. */
2245 ssh2_pkt_addstring_start();
2246 for (i = 0; i < lenof(ciphers)+1; i++) {
2247 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2248 ssh2_pkt_addstring_str(c->name);
2249 if (i < lenof(ciphers))
2250 ssh2_pkt_addstring_str(",");
2252 /* List server->client encryption algorithms. */
2253 ssh2_pkt_addstring_start();
2254 for (i = 0; i < lenof(ciphers)+1; i++) {
2255 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2256 ssh2_pkt_addstring_str(c->name);
2257 if (i < lenof(ciphers))
2258 ssh2_pkt_addstring_str(",");
2260 /* List client->server MAC algorithms. */
2261 ssh2_pkt_addstring_start();
2262 for (i = 0; i < nmacs; i++) {
2263 ssh2_pkt_addstring_str(maclist[i]->name);
2265 ssh2_pkt_addstring_str(",");
2267 /* List server->client MAC algorithms. */
2268 ssh2_pkt_addstring_start();
2269 for (i = 0; i < nmacs; i++) {
2270 ssh2_pkt_addstring_str(maclist[i]->name);
2272 ssh2_pkt_addstring_str(",");
2274 /* List client->server compression algorithms. */
2275 ssh2_pkt_addstring_start();
2276 for (i = 0; i < lenof(compressions)+1; i++) {
2277 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2278 ssh2_pkt_addstring_str(c->name);
2279 if (i < lenof(compressions))
2280 ssh2_pkt_addstring_str(",");
2282 /* List server->client compression algorithms. */
2283 ssh2_pkt_addstring_start();
2284 for (i = 0; i < lenof(compressions)+1; i++) {
2285 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2286 ssh2_pkt_addstring_str(c->name);
2287 if (i < lenof(compressions))
2288 ssh2_pkt_addstring_str(",");
2290 /* List client->server languages. Empty list. */
2291 ssh2_pkt_addstring_start();
2292 /* List server->client languages. Empty list. */
2293 ssh2_pkt_addstring_start();
2294 /* First KEX packet does _not_ follow, because we're not that brave. */
2295 ssh2_pkt_addbool(FALSE);
2297 ssh2_pkt_adduint32(0);
2299 exhash = exhashbase;
2300 sha_string(&exhash, pktout.data+5, pktout.length-5);
2304 if (!ispkt) crWaitUntil(ispkt);
2305 sha_string(&exhash, pktin.data+5, pktin.length-5);
2308 * Now examine the other side's KEXINIT to see what we're up
2311 if (pktin.type != SSH2_MSG_KEXINIT) {
2312 bombout(("expected key exchange packet from server"));
2315 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
2316 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
2317 pktin.savedpos += 16; /* skip garbage cookie */
2318 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
2319 for (i = 0; i < lenof(kex_algs); i++) {
2320 if (in_commasep_string(kex_algs[i]->name, str, len)) {
2325 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
2326 for (i = 0; i < lenof(hostkey_algs); i++) {
2327 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
2328 hostkey = hostkey_algs[i];
2332 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
2333 for (i = 0; i < lenof(ciphers)+1; i++) {
2334 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2335 if (in_commasep_string(c->name, str, len)) {
2340 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
2341 for (i = 0; i < lenof(ciphers)+1; i++) {
2342 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2343 if (in_commasep_string(c->name, str, len)) {
2348 ssh2_pkt_getstring(&str, &len); /* client->server mac */
2349 for (i = 0; i < nmacs; i++) {
2350 if (in_commasep_string(maclist[i]->name, str, len)) {
2351 csmac_tobe = maclist[i];
2355 ssh2_pkt_getstring(&str, &len); /* server->client mac */
2356 for (i = 0; i < nmacs; i++) {
2357 if (in_commasep_string(maclist[i]->name, str, len)) {
2358 scmac_tobe = maclist[i];
2362 ssh2_pkt_getstring(&str, &len); /* client->server compression */
2363 for (i = 0; i < lenof(compressions)+1; i++) {
2364 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2365 if (in_commasep_string(c->name, str, len)) {
2370 ssh2_pkt_getstring(&str, &len); /* server->client compression */
2371 for (i = 0; i < lenof(compressions)+1; i++) {
2372 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2373 if (in_commasep_string(c->name, str, len)) {
2380 * Currently we only support Diffie-Hellman and DSS, so let's
2381 * bomb out if those aren't selected.
2383 if (kex != &ssh_diffiehellman || hostkey != &ssh_dss) {
2384 bombout(("internal fault: chaos in SSH 2 transport layer"));
2389 * Now we begin the fun. Generate and send e for Diffie-Hellman.
2392 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
2397 if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
2398 bombout(("expected key exchange packet from server"));
2401 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2402 f = ssh2_pkt_getmp();
2403 ssh2_pkt_getstring(&sigdata, &siglen);
2407 sha_string(&exhash, hostkeydata, hostkeylen);
2408 sha_mpint(&exhash, e);
2409 sha_mpint(&exhash, f);
2410 sha_mpint(&exhash, K);
2411 SHA_Final(&exhash, exchange_hash);
2414 debug(("Exchange hash is:\r\n"));
2415 for (i = 0; i < 20; i++)
2416 debug((" %02x", exchange_hash[i]));
2420 hkey = hostkey->newkey(hostkeydata, hostkeylen);
2421 if (!hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
2422 bombout(("Server failed host key check"));
2427 * Expect SSH2_MSG_NEWKEYS from server.
2430 if (pktin.type != SSH2_MSG_NEWKEYS) {
2431 bombout(("expected new-keys packet from server"));
2436 * Authenticate remote host: verify host key. (We've already
2437 * checked the signature of the exchange hash.)
2439 keystr = hostkey->fmtkey(hkey);
2440 fingerprint = hostkey->fingerprint(hkey);
2441 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
2442 keystr, fingerprint);
2443 if (first_kex) { /* don't bother logging this in rekeys */
2444 logevent("Host key fingerprint is:");
2445 logevent(fingerprint);
2449 hostkey->freekey(hkey);
2452 * Send SSH2_MSG_NEWKEYS.
2454 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2458 * Create and initialise session keys.
2460 cscipher = cscipher_tobe;
2461 sccipher = sccipher_tobe;
2464 cscomp = cscomp_tobe;
2465 sccomp = sccomp_tobe;
2466 cscomp->compress_init();
2467 sccomp->decompress_init();
2469 * Set IVs after keys. Here we use the exchange hash from the
2470 * _first_ key exchange.
2473 memcpy(first_exchange_hash, exchange_hash, sizeof(exchange_hash));
2474 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'C', keyspace);
2475 cscipher->setcskey(keyspace);
2476 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'D', keyspace);
2477 sccipher->setsckey(keyspace);
2478 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'A', keyspace);
2479 cscipher->setcsiv(keyspace);
2480 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'B', keyspace);
2481 sccipher->setsciv(keyspace);
2482 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'E', keyspace);
2483 csmac->setcskey(keyspace);
2484 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'F', keyspace);
2485 scmac->setsckey(keyspace);
2488 * If this is the first key exchange phase, we must pass the
2489 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2490 * wants to see it but because it will need time to initialise
2491 * itself before it sees an actual packet. In subsequent key
2492 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2493 * it would only confuse the layer above.
2501 * Now we're encrypting. Begin returning 1 to the protocol main
2502 * function so that other things can run on top of the
2503 * transport. If we ever see a KEXINIT, we must go back to the
2506 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
2509 logevent("Server initiated key re-exchange");
2510 goto begin_key_exchange;
2516 * Add data to an SSH2 channel output buffer.
2518 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len) {
2519 if (c->v2.outbufsize <
2520 c->v2.outbuflen + len) {
2522 c->v2.outbuflen + len + 1024;
2523 c->v2.outbuffer = srealloc(c->v2.outbuffer,
2526 memcpy(c->v2.outbuffer + c->v2.outbuflen,
2528 c->v2.outbuflen += len;
2532 * Attempt to send data on an SSH2 channel.
2534 static void ssh2_try_send(struct ssh_channel *c) {
2535 while (c->v2.remwindow > 0 &&
2536 c->v2.outbuflen > 0) {
2537 unsigned len = c->v2.remwindow;
2538 if (len > c->v2.outbuflen)
2539 len = c->v2.outbuflen;
2540 if (len > c->v2.remmaxpkt)
2541 len = c->v2.remmaxpkt;
2542 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2543 ssh2_pkt_adduint32(c->remoteid);
2544 ssh2_pkt_addstring_start();
2545 ssh2_pkt_addstring_data(c->v2.outbuffer, len);
2547 c->v2.outbuflen -= len;
2548 memmove(c->v2.outbuffer, c->v2.outbuffer+len,
2550 c->v2.remwindow -= len;
2555 * Handle the SSH2 userauth and connection layers.
2557 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2559 static unsigned long remote_winsize;
2560 static unsigned long remote_maxpkt;
2565 * Request userauth protocol, and await a response to it.
2567 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2568 ssh2_pkt_addstring("ssh-userauth");
2570 crWaitUntilV(ispkt);
2571 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2572 bombout(("Server refused user authentication protocol"));
2577 * FIXME: currently we support only password authentication.
2578 * (This places us technically in violation of the SSH2 spec.
2579 * We must fix this.)
2583 * Get a username and a password.
2585 static char username[100];
2586 static char password[100];
2590 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2591 c_write("login as: ", 10);
2594 crWaitUntilV(!ispkt);
2595 while (inlen--) switch (c = *in++) {
2602 c_write("\b \b", 3);
2608 c_write("\b \b", 3);
2617 if (((c >= ' ' && c <= '~') ||
2618 ((unsigned char)c >= 160)) && pos < 40) {
2619 username[pos++] = c;
2626 username[strcspn(username, "\n\r")] = '\0';
2629 strncpy(username, cfg.username, 99);
2630 username[99] = '\0';
2631 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
2632 sprintf(stuff, "Using username \"%s\".\r\n", username);
2633 c_write(stuff, strlen(stuff));
2637 if (ssh_get_password) {
2639 sprintf(prompt, "%.90s@%.90s's password: ", username, savedhost);
2640 if (!ssh_get_password(prompt, password, sizeof(password))) {
2642 * get_password failed to get a password (for
2643 * example because one was supplied on the command
2644 * line which has already failed to work).
2647 logevent("No more passwords to try");
2648 ssh_state = SSH_STATE_CLOSED;
2652 c_write("password: ", 10);
2657 crWaitUntilV(!ispkt);
2658 while (inlen--) switch (c = *in++) {
2675 if (((c >= ' ' && c <= '~') ||
2676 ((unsigned char)c >= 160)) && pos < 40)
2677 password[pos++] = c;
2685 * We send the password packet lumped tightly together with
2686 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
2687 * string long enough to make the total length of the two
2688 * packets constant. This should ensure that a passive
2689 * listener doing traffic analyis can't work out the length
2692 * For this to work, we need an assumption about the
2693 * maximum length of the password packet. I think 256 is
2694 * pretty conservative. Anyone using a password longer than
2695 * that probably doesn't have much to worry about from
2696 * people who find out how long their password is!
2698 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2699 ssh2_pkt_addstring(username);
2700 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2701 ssh2_pkt_addstring("password");
2702 ssh2_pkt_addbool(FALSE);
2703 ssh2_pkt_addstring(password);
2706 * We'll include a string that's an exact multiple of the
2707 * cipher block size. If the cipher is NULL for some
2708 * reason, we don't do this trick at all because we gain
2713 ssh2_pkt_init(SSH2_MSG_IGNORE);
2714 ssh2_pkt_addstring_start();
2715 for (i = deferred_len; i <= 256; i += cscipher->blksize) {
2716 for (j = 0; j < cscipher->blksize; j++) {
2717 char c = (char)random_byte();
2718 ssh2_pkt_addstring_data(&c, 1);
2723 ssh2_pkt_defersend();
2725 crWaitUntilV(ispkt);
2726 if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
2727 c_write("Access denied\r\n", 15);
2728 logevent("Authentication refused");
2734 * Now we're authenticated for the connection protocol. The
2735 * connection protocol will automatically have started at this
2736 * point; there's no need to send SERVICE_REQUEST.
2740 * So now create a channel with a session in it.
2742 mainchan = smalloc(sizeof(struct ssh_channel));
2743 mainchan->localid = 100; /* as good as any */
2744 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
2745 ssh2_pkt_addstring("session");
2746 ssh2_pkt_adduint32(mainchan->localid);
2747 ssh2_pkt_adduint32(0x8000UL); /* our window size */
2748 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
2750 crWaitUntilV(ispkt);
2751 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
2752 bombout(("Server refused to open a session"));
2754 /* FIXME: error data comes back in FAILURE packet */
2756 if (ssh2_pkt_getuint32() != mainchan->localid) {
2757 bombout(("Server's channel confirmation cited wrong channel"));
2760 mainchan->remoteid = ssh2_pkt_getuint32();
2761 mainchan->type = CHAN_MAINSESSION;
2762 mainchan->closes = 0;
2763 mainchan->v2.remwindow = ssh2_pkt_getuint32();
2764 mainchan->v2.remmaxpkt = ssh2_pkt_getuint32();
2765 mainchan->v2.outbuffer = NULL;
2766 mainchan->v2.outbuflen = mainchan->v2.outbufsize = 0;
2767 ssh_channels = newtree234(ssh_channelcmp);
2768 add234(ssh_channels, mainchan);
2769 logevent("Opened channel for session");
2772 * Potentially enable X11 forwarding.
2774 if (cfg.x11_forward) {
2775 char proto[20], data[64];
2776 logevent("Requesting X11 forwarding");
2777 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2778 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2779 ssh2_pkt_adduint32(mainchan->remoteid);
2780 ssh2_pkt_addstring("x11-req");
2781 ssh2_pkt_addbool(1); /* want reply */
2782 ssh2_pkt_addbool(0); /* many connections */
2783 ssh2_pkt_addstring(proto);
2784 ssh2_pkt_addstring(data);
2785 ssh2_pkt_adduint32(0); /* screen number */
2789 crWaitUntilV(ispkt);
2790 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2791 unsigned i = ssh2_pkt_getuint32();
2792 struct ssh_channel *c;
2793 c = find234(ssh_channels, &i, ssh_channelfind);
2795 continue; /* nonexistent channel */
2796 c->v2.remwindow += ssh2_pkt_getuint32();
2798 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2800 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2801 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2802 bombout(("Server got confused by X11 forwarding request"));
2805 logevent("X11 forwarding refused");
2807 logevent("X11 forwarding enabled");
2808 ssh_X11_fwd_enabled = TRUE;
2813 * Now allocate a pty for the session.
2816 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2817 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2818 ssh2_pkt_addstring("pty-req");
2819 ssh2_pkt_addbool(1); /* want reply */
2820 ssh2_pkt_addstring(cfg.termtype);
2821 ssh2_pkt_adduint32(cols);
2822 ssh2_pkt_adduint32(rows);
2823 ssh2_pkt_adduint32(0); /* pixel width */
2824 ssh2_pkt_adduint32(0); /* pixel height */
2825 ssh2_pkt_addstring_start();
2826 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
2828 ssh_state = SSH_STATE_INTERMED;
2831 crWaitUntilV(ispkt);
2832 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2833 unsigned i = ssh2_pkt_getuint32();
2834 struct ssh_channel *c;
2835 c = find234(ssh_channels, &i, ssh_channelfind);
2837 continue; /* nonexistent channel */
2838 c->v2.remwindow += ssh2_pkt_getuint32();
2840 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2842 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2843 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2844 bombout(("Server got confused by pty request"));
2847 c_write("Server refused to allocate pty\r\n", 32);
2848 ssh_editing = ssh_echoing = 1;
2850 logevent("Allocated pty");
2853 ssh_editing = ssh_echoing = 1;
2857 * Start a shell or a remote command.
2859 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2860 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2861 if (*cfg.remote_cmd) {
2862 ssh2_pkt_addstring("exec");
2863 ssh2_pkt_addbool(1); /* want reply */
2864 ssh2_pkt_addstring(cfg.remote_cmd);
2866 ssh2_pkt_addstring("shell");
2867 ssh2_pkt_addbool(1); /* want reply */
2871 crWaitUntilV(ispkt);
2872 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2873 unsigned i = ssh2_pkt_getuint32();
2874 struct ssh_channel *c;
2875 c = find234(ssh_channels, &i, ssh_channelfind);
2877 continue; /* nonexistent channel */
2878 c->v2.remwindow += ssh2_pkt_getuint32();
2880 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2881 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2882 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2883 bombout(("Server got confused by shell/command request"));
2886 bombout(("Server refused to start a shell/command"));
2889 logevent("Started a shell/command");
2892 ssh_state = SSH_STATE_SESSION;
2896 ssh_special(TS_EOF);
2901 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
2904 static int try_send;
2908 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
2909 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
2912 unsigned i = ssh2_pkt_getuint32();
2913 struct ssh_channel *c;
2914 c = find234(ssh_channels, &i, ssh_channelfind);
2916 continue; /* nonexistent channel */
2917 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
2918 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
2919 continue; /* extended but not stderr */
2920 ssh2_pkt_getstring(&data, &length);
2923 case CHAN_MAINSESSION:
2924 from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
2928 x11_send(c->u.x11.s, data, length);
2932 * Enlarge the window again at the remote
2933 * side, just in case it ever runs down and
2934 * they fail to send us any more data.
2936 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2937 ssh2_pkt_adduint32(c->remoteid);
2938 ssh2_pkt_adduint32(length);
2941 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
2942 ssh_state = SSH_STATE_CLOSED;
2943 logevent("Received disconnect message");
2945 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2946 continue; /* exit status et al; ignore (FIXME?) */
2947 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
2948 unsigned i = ssh2_pkt_getuint32();
2949 struct ssh_channel *c;
2951 c = find234(ssh_channels, &i, ssh_channelfind);
2953 continue; /* nonexistent channel */
2955 if (c->type == CHAN_X11) {
2957 * Remote EOF on an X11 channel means we should
2958 * wrap up and close the channel ourselves.
2960 x11_close(c->u.x11.s);
2963 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
2964 unsigned i = ssh2_pkt_getuint32();
2965 struct ssh_channel *c;
2968 c = find234(ssh_channels, &i, ssh_channelfind);
2970 continue; /* nonexistent channel */
2971 if (c->closes == 0) {
2972 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2973 ssh2_pkt_adduint32(c->remoteid);
2976 /* Do pre-close processing on the channel. */
2978 case CHAN_MAINSESSION:
2979 break; /* nothing to see here, move along */
2983 del234(ssh_channels, c);
2984 sfree(c->v2.outbuffer);
2988 * See if that was the last channel left open.
2990 c = first234(ssh_channels, &e);
2992 logevent("All channels closed. Disconnecting");
2993 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
2994 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
2995 ssh2_pkt_addstring("All open channels closed");
2996 ssh2_pkt_addstring("en"); /* language tag */
2998 ssh_state = SSH_STATE_CLOSED;
3001 continue; /* remote sends close; ignore (FIXME) */
3002 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3003 unsigned i = ssh2_pkt_getuint32();
3004 struct ssh_channel *c;
3005 c = find234(ssh_channels, &i, ssh_channelfind);
3007 continue; /* nonexistent channel */
3008 mainchan->v2.remwindow += ssh2_pkt_getuint32();
3010 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
3014 struct ssh_channel *c;
3015 ssh2_pkt_getstring(&type, &typelen);
3016 c = smalloc(sizeof(struct ssh_channel));
3018 if (typelen == 3 && !memcmp(type, "x11", 3)) {
3019 if (!ssh_X11_fwd_enabled)
3020 error = "X11 forwarding is not enabled";
3021 else if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
3022 error = "Unable to open an X11 connection";
3027 error = "Unsupported channel type requested";
3030 c->remoteid = ssh2_pkt_getuint32();
3032 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
3033 ssh2_pkt_adduint32(c->remoteid);
3034 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
3035 ssh2_pkt_addstring(error);
3036 ssh2_pkt_addstring("en"); /* language tag */
3040 struct ssh_channel *d;
3044 for (i=1, d = first234(ssh_channels, &e); d;
3047 break; /* found a free number */
3052 c->v2.remwindow = ssh2_pkt_getuint32();
3053 c->v2.remmaxpkt = ssh2_pkt_getuint32();
3054 c->v2.outbuffer = NULL;
3055 c->v2.outbuflen = c->v2.outbufsize = 0;
3056 add234(ssh_channels, c);
3057 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
3058 ssh2_pkt_adduint32(c->remoteid);
3059 ssh2_pkt_adduint32(c->localid);
3060 ssh2_pkt_adduint32(0x8000UL); /* our window size */
3061 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
3065 bombout(("Strange packet received: type %d", pktin.type));
3070 * We have spare data. Add it to the channel buffer.
3072 ssh2_add_channel_data(mainchan, in, inlen);
3077 struct ssh_channel *c;
3079 * Try to send data on all channels if we can.
3081 for (c = first234(ssh_channels, &e); c; c = next234(&e))
3090 * Handle the top-level SSH2 protocol.
3092 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
3094 if (do_ssh2_transport(in, inlen, ispkt) == 0)
3096 do_ssh2_authconn(in, inlen, ispkt);
3100 * Called to set up the connection.
3102 * Returns an error message, or NULL on success.
3104 static char *ssh_init (char *host, int port, char **realhost) {
3108 if(crypto_startup() == 0)
3109 return "Microsoft high encryption pack not installed!";
3116 p = connect_to_host(host, port, realhost);
3124 * Called to send data down the Telnet connection.
3126 static void ssh_send (char *buf, int len) {
3127 if (s == NULL || ssh_protocol == NULL)
3130 ssh_protocol(buf, len, 0);
3134 * Called to set the size of the window from SSH's POV.
3136 static void ssh_size(void) {
3137 switch (ssh_state) {
3138 case SSH_STATE_BEFORE_SIZE:
3139 case SSH_STATE_PREPACKET:
3140 case SSH_STATE_CLOSED:
3141 break; /* do nothing */
3142 case SSH_STATE_INTERMED:
3143 size_needed = TRUE; /* buffer for later */
3145 case SSH_STATE_SESSION:
3147 if (ssh_version == 1) {
3148 send_packet(SSH1_CMSG_WINDOW_SIZE,
3149 PKT_INT, rows, PKT_INT, cols,
3150 PKT_INT, 0, PKT_INT, 0, PKT_END);
3152 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3153 ssh2_pkt_adduint32(mainchan->remoteid);
3154 ssh2_pkt_addstring("window-change");
3155 ssh2_pkt_addbool(0);
3156 ssh2_pkt_adduint32(cols);
3157 ssh2_pkt_adduint32(rows);
3158 ssh2_pkt_adduint32(0);
3159 ssh2_pkt_adduint32(0);
3168 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3169 * can send an EOF and collect resulting output (e.g. `plink
3172 static void ssh_special (Telnet_Special code) {
3173 if (code == TS_EOF) {
3174 if (ssh_state != SSH_STATE_SESSION) {
3176 * Buffer the EOF in case we are pre-SESSION, so we can
3177 * send it as soon as we reach SESSION.
3183 if (ssh_version == 1) {
3184 send_packet(SSH1_CMSG_EOF, PKT_END);
3186 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
3187 ssh2_pkt_adduint32(mainchan->remoteid);
3190 logevent("Sent EOF message");
3191 } else if (code == TS_PING) {
3192 if (ssh_state == SSH_STATE_CLOSED || ssh_state == SSH_STATE_PREPACKET)
3194 if (ssh_version == 1) {
3195 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
3197 ssh2_pkt_init(SSH2_MSG_IGNORE);
3198 ssh2_pkt_addstring_start();
3206 static Socket ssh_socket(void) { return s; }
3208 static int ssh_sendok(void) { return ssh_send_ok; }
3210 static int ssh_ldisc(int option) {
3211 if (option == LD_ECHO) return ssh_echoing;
3212 if (option == LD_EDIT) return ssh_editing;
3216 Backend ssh_backend = {