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 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) {
872 int i, n = (ssh1_bignum_bitcount(b)+7)/8;
875 fatalbox("out of memory");
877 for (i = 1; i <= n; i++)
878 p[i] = bignum_byte(b, n-i);
880 while (i <= n && p[i] == 0 && (p[i+1] & 0x80) == 0)
882 memmove(p, p+i, n+1-i);
886 static void ssh2_pkt_addmp(Bignum b) {
889 p = ssh2_mpint_fmt(b, &len);
890 ssh2_pkt_addstring_start();
891 ssh2_pkt_addstring_data(p, len);
896 * Construct an SSH2 final-form packet: compress it, encrypt it,
897 * put the MAC on it. Final packet, ready to be sent, is stored in
898 * pktout.data. Total length is returned.
900 static int ssh2_pkt_construct(void) {
901 int cipherblk, maclen, padding, i;
902 static unsigned long outgoing_sequence = 0;
905 * Compress packet payload.
908 debug(("Pre-compression payload:\r\n"));
909 for (i = 5; i < pktout.length; i++)
910 debug((" %02x", (unsigned char)pktout.data[i]));
914 unsigned char *newpayload;
916 if (cscomp && cscomp->compress(pktout.data+5, pktout.length-5,
917 &newpayload, &newlen)) {
919 ssh2_pkt_adddata(newpayload, newlen);
925 * Add padding. At least four bytes, and must also bring total
926 * length (minus MAC) up to a multiple of the block size.
928 cipherblk = cipher ? cipher->blksize : 8; /* block size */
929 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
931 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
932 maclen = csmac ? csmac->len : 0;
933 ssh2_pkt_ensure(pktout.length + padding + maclen);
934 pktout.data[4] = padding;
935 for (i = 0; i < padding; i++)
936 pktout.data[pktout.length + i] = random_byte();
937 PUT_32BIT(pktout.data, pktout.length + padding - 4);
939 csmac->generate(pktout.data, pktout.length + padding,
941 outgoing_sequence++; /* whether or not we MACed */
944 debug(("Sending packet len=%d\r\n", pktout.length+padding));
945 for (i = 0; i < pktout.length+padding; i++)
946 debug((" %02x", (unsigned char)pktout.data[i]));
951 cscipher->encrypt(pktout.data, pktout.length + padding);
953 /* Ready-to-send packet starts at pktout.data. We return length. */
954 return pktout.length + padding + maclen;
958 * Construct and send an SSH2 packet immediately.
960 static void ssh2_pkt_send(void) {
961 int len = ssh2_pkt_construct();
962 sk_write(s, pktout.data, len);
966 * Construct an SSH2 packet and add it to a deferred data block.
967 * Useful for sending multiple packets in a single sk_write() call,
968 * to prevent a traffic-analysing listener from being able to work
969 * out the length of any particular packet (such as the password
972 * Note that because SSH2 sequence-numbers its packets, this can
973 * NOT be used as an m4-style `defer' allowing packets to be
974 * constructed in one order and sent in another.
976 static void ssh2_pkt_defer(void) {
977 int len = ssh2_pkt_construct();
978 if (deferred_len + len > deferred_size) {
979 deferred_size = deferred_len + len + 128;
980 deferred_send_data = srealloc(deferred_send_data, deferred_size);
982 memcpy(deferred_send_data+deferred_len, pktout.data, len);
987 * Send the whole deferred data block constructed by
990 static void ssh2_pkt_defersend(void) {
991 sk_write(s, deferred_send_data, deferred_len);
992 deferred_len = deferred_size = 0;
993 sfree(deferred_send_data);
994 deferred_send_data = NULL;
998 void bndebug(char *string, Bignum b) {
1001 p = ssh2_mpint_fmt(b, &len);
1002 debug(("%s", string));
1003 for (i = 0; i < len; i++)
1004 debug((" %02x", p[i]));
1010 static void sha_mpint(SHA_State *s, Bignum b) {
1013 p = ssh2_mpint_fmt(b, &len);
1014 sha_string(s, p, len);
1019 * SSH2 packet decode functions.
1021 static unsigned long ssh2_pkt_getuint32(void) {
1022 unsigned long value;
1023 if (pktin.length - pktin.savedpos < 4)
1024 return 0; /* arrgh, no way to decline (FIXME?) */
1025 value = GET_32BIT(pktin.data+pktin.savedpos);
1026 pktin.savedpos += 4;
1029 static void ssh2_pkt_getstring(char **p, int *length) {
1031 if (pktin.length - pktin.savedpos < 4)
1033 *length = GET_32BIT(pktin.data+pktin.savedpos);
1034 pktin.savedpos += 4;
1035 if (pktin.length - pktin.savedpos < *length)
1037 *p = pktin.data+pktin.savedpos;
1038 pktin.savedpos += *length;
1040 static Bignum ssh2_pkt_getmp(void) {
1045 ssh2_pkt_getstring(&p, &length);
1049 bombout(("internal error: Can't handle negative mpints"));
1052 b = bignum_from_bytes(p, length);
1056 static int do_ssh_init(unsigned char c) {
1058 static char version[10];
1059 static char vstring[80];
1060 static char vlog[sizeof(vstring)+20];
1065 /* Search for the string "SSH-" in the input. */
1068 static const int transS[] = { 1, 2, 2, 1 };
1069 static const int transH[] = { 0, 0, 3, 0 };
1070 static const int transminus[] = { 0, 0, 0, -1 };
1071 if (c == 'S') i = transS[i];
1072 else if (c == 'H') i = transH[i];
1073 else if (c == '-') i = transminus[i];
1077 crReturn(1); /* get another character */
1080 strcpy(vstring, "SSH-");
1084 crReturn(1); /* get another char */
1085 if (vsp < vstring+sizeof(vstring)-1)
1091 } else if (i < sizeof(version)-1)
1098 ssh_agentfwd_enabled = FALSE;
1099 rdpkt2_state.incoming_sequence = 0;
1102 sprintf(vlog, "Server version: %s", vstring);
1103 vlog[strcspn(vlog, "\r\n")] = '\0';
1107 * Server version "1.99" means we can choose whether we use v1
1108 * or v2 protocol. Choice is based on cfg.sshprot.
1110 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1112 * This is a v2 server. Begin v2 protocol.
1114 char *verstring = "SSH-2.0-PuTTY";
1115 SHA_Init(&exhashbase);
1117 * Hash our version string and their version string.
1119 sha_string(&exhashbase, verstring, strlen(verstring));
1120 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1121 sprintf(vstring, "%s\n", verstring);
1122 sprintf(vlog, "We claim version: %s", verstring);
1124 logevent("Using SSH protocol version 2");
1125 sk_write(s, vstring, strlen(vstring));
1126 ssh_protocol = ssh2_protocol;
1128 s_rdpkt = ssh2_rdpkt;
1131 * This is a v1 server. Begin v1 protocol.
1133 sprintf(vstring, "SSH-%s-PuTTY\n",
1134 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1135 sprintf(vlog, "We claim version: %s", vstring);
1136 vlog[strcspn(vlog, "\r\n")] = '\0';
1138 logevent("Using SSH protocol version 1");
1139 sk_write(s, vstring, strlen(vstring));
1140 ssh_protocol = ssh1_protocol;
1142 s_rdpkt = ssh1_rdpkt;
1144 ssh_state = SSH_STATE_BEFORE_SIZE;
1149 static void ssh_gotdata(unsigned char *data, int datalen)
1154 * To begin with, feed the characters one by one to the
1155 * protocol initialisation / selection function do_ssh_init().
1156 * When that returns 0, we're done with the initial greeting
1157 * exchange and can move on to packet discipline.
1162 crReturnV; /* more data please */
1163 ret = do_ssh_init(*data);
1170 * We emerge from that loop when the initial negotiation is
1171 * over and we have selected an s_rdpkt function. Now pass
1172 * everything to s_rdpkt, and then pass the resulting packets
1173 * to the proper protocol handler.
1178 while (datalen > 0) {
1179 if ( s_rdpkt(&data, &datalen) == 0 ) {
1180 ssh_protocol(NULL, 0, 1);
1181 if (ssh_state == SSH_STATE_CLOSED) {
1191 static int ssh_receive(Socket skt, int urgent, char *data, int len) {
1193 /* A socket error has occurred. */
1194 ssh_state = SSH_STATE_CLOSED;
1197 connection_fatal(data);
1200 /* Connection has closed. */
1201 ssh_state = SSH_STATE_CLOSED;
1206 ssh_gotdata (data, len);
1207 if (ssh_state == SSH_STATE_CLOSED) {
1218 * Connect to specified host and port.
1219 * Returns an error message, or NULL on success.
1220 * Also places the canonical host name into `realhost'.
1222 static char *connect_to_host(char *host, int port, char **realhost)
1231 savedhost = smalloc(1+strlen(host));
1233 fatalbox("Out of memory");
1234 strcpy(savedhost, host);
1237 port = 22; /* default ssh port */
1250 addr = sk_namelookup(host, realhost);
1251 if ( (err = sk_addr_error(addr)) )
1261 s = sk_new(addr, port, 0, 1, ssh_receive);
1262 if ( (err = sk_socket_error(s)) )
1266 sk_write(s, "connect ", 8);
1267 sk_write(s, FWhost, strlen(FWhost));
1270 sprintf(buf, " %d\n", FWport);
1271 sk_write(s, buf, strlen(buf));
1279 * Handle the key exchange and user authentication phases.
1281 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1284 unsigned char *rsabuf, *keystr1, *keystr2;
1285 unsigned char cookie[8];
1286 struct RSAKey servkey, hostkey;
1287 struct MD5Context md5c;
1288 static unsigned long supported_ciphers_mask, supported_auths_mask;
1289 static int tried_publickey;
1290 static unsigned char session_id[16];
1292 static char username[100];
1296 if (!ispkt) crWaitUntil(ispkt);
1298 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1299 bombout(("Public key packet not received"));
1303 logevent("Received public keys");
1305 memcpy(cookie, pktin.body, 8);
1307 i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1308 j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1311 * Log the host key fingerprint.
1315 logevent("Host key fingerprint is:");
1316 strcpy(logmsg, " ");
1317 hostkey.comment = NULL;
1318 rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
1323 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1324 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1327 MD5Update(&md5c, keystr2, hostkey.bytes);
1328 MD5Update(&md5c, keystr1, servkey.bytes);
1329 MD5Update(&md5c, pktin.body, 8);
1330 MD5Final(session_id, &md5c);
1332 for (i=0; i<32; i++)
1333 session_key[i] = random_byte();
1335 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1337 rsabuf = smalloc(len);
1339 fatalbox("Out of memory");
1342 * Verify the host key.
1346 * First format the key into a string.
1348 int len = rsastr_len(&hostkey);
1349 char fingerprint[100];
1350 char *keystr = smalloc(len);
1352 fatalbox("Out of memory");
1353 rsastr_fmt(keystr, &hostkey);
1354 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
1355 verify_ssh_host_key(savedhost, savedport, "rsa", keystr, fingerprint);
1359 for (i=0; i<32; i++) {
1360 rsabuf[i] = session_key[i];
1362 rsabuf[i] ^= session_id[i];
1365 if (hostkey.bytes > servkey.bytes) {
1366 rsaencrypt(rsabuf, 32, &servkey);
1367 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1369 rsaencrypt(rsabuf, 32, &hostkey);
1370 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1373 logevent("Encrypted session key");
1375 cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
1376 cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES :
1378 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1379 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1380 cipher_type = SSH_CIPHER_3DES;
1382 switch (cipher_type) {
1383 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1384 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1385 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1388 send_packet(SSH1_CMSG_SESSION_KEY,
1389 PKT_CHAR, cipher_type,
1390 PKT_DATA, cookie, 8,
1391 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1392 PKT_DATA, rsabuf, len,
1396 logevent("Trying to enable encryption...");
1400 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1401 cipher_type == SSH_CIPHER_DES ? &ssh_des :
1403 cipher->sesskey(session_key);
1407 if (pktin.type != SSH1_SMSG_SUCCESS) {
1408 bombout(("Encryption not successfully enabled"));
1412 logevent("Successfully started encryption");
1418 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1419 c_write("login as: ", 10);
1422 crWaitUntil(!ispkt);
1423 while (inlen--) switch (c = *in++) {
1430 c_write("\b \b", 3);
1436 c_write("\b \b", 3);
1445 if (((c >= ' ' && c <= '~') ||
1446 ((unsigned char)c >= 160)) && pos < 40) {
1447 username[pos++] = c;
1454 username[strcspn(username, "\n\r")] = '\0';
1456 strncpy(username, cfg.username, 99);
1457 username[99] = '\0';
1460 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1462 char userlog[22+sizeof(username)];
1463 sprintf(userlog, "Sent username \"%s\"", username);
1465 if (flags & FLAG_INTERACTIVE &&
1466 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
1467 strcat(userlog, "\r\n");
1468 c_write(userlog, strlen(userlog));
1475 tried_publickey = 0;
1477 while (pktin.type == SSH1_SMSG_FAILURE) {
1478 static char password[100];
1479 static char prompt[200];
1482 static int pwpkt_type;
1484 * Show password prompt, having first obtained it via a TIS
1485 * or CryptoCard exchange if we're doing TIS or CryptoCard
1488 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1489 if (agent_exists()) {
1491 * Attempt RSA authentication using Pageant.
1493 static unsigned char request[5], *response, *p;
1494 static int responselen;
1495 static int i, nkeys;
1496 static int authed = FALSE;
1499 logevent("Pageant is running. Requesting keys.");
1501 /* Request the keys held by the agent. */
1502 PUT_32BIT(request, 1);
1503 request[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
1504 agent_query(request, 5, &r, &responselen);
1505 response = (unsigned char *)r;
1508 nkeys = GET_32BIT(p); p += 4;
1509 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
1511 for (i = 0; i < nkeys; i++) {
1512 static struct RSAKey key;
1513 static Bignum challenge;
1514 static char *commentp;
1515 static int commentlen;
1517 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1520 p += ssh1_read_bignum(p, &key.exponent);
1521 p += ssh1_read_bignum(p, &key.modulus);
1522 commentlen = GET_32BIT(p); p += 4;
1523 commentp = p; p += commentlen;
1524 send_packet(SSH1_CMSG_AUTH_RSA,
1525 PKT_BIGNUM, key.modulus, PKT_END);
1527 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1528 logevent("Key refused");
1531 logevent("Received RSA challenge");
1532 ssh1_read_bignum(pktin.body, &challenge);
1534 char *agentreq, *q, *ret;
1536 len = 1 + 4; /* message type, bit count */
1537 len += ssh1_bignum_length(key.exponent);
1538 len += ssh1_bignum_length(key.modulus);
1539 len += ssh1_bignum_length(challenge);
1540 len += 16; /* session id */
1541 len += 4; /* response format */
1542 agentreq = smalloc(4 + len);
1543 PUT_32BIT(agentreq, len);
1545 *q++ = SSH_AGENTC_RSA_CHALLENGE;
1546 PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1548 q += ssh1_write_bignum(q, key.exponent);
1549 q += ssh1_write_bignum(q, key.modulus);
1550 q += ssh1_write_bignum(q, challenge);
1551 memcpy(q, session_id, 16); q += 16;
1552 PUT_32BIT(q, 1); /* response format */
1553 agent_query(agentreq, len+4, &ret, &retlen);
1556 if (ret[4] == SSH_AGENT_RSA_RESPONSE) {
1557 logevent("Sending Pageant's response");
1558 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1559 PKT_DATA, ret+5, 16, PKT_END);
1562 if (pktin.type == SSH1_SMSG_SUCCESS) {
1563 logevent("Pageant's response accepted");
1564 if (flags & FLAG_VERBOSE) {
1565 c_write("Authenticated using RSA key \"",
1567 c_write(commentp, commentlen);
1568 c_write("\" from agent\r\n", 14);
1572 logevent("Pageant's response not accepted");
1574 logevent("Pageant failed to answer challenge");
1578 logevent("No reply received from Pageant");
1581 freebn(key.exponent);
1582 freebn(key.modulus);
1591 if (*cfg.keyfile && !tried_publickey)
1592 pwpkt_type = SSH1_CMSG_AUTH_RSA;
1594 if (pktin.type == SSH1_SMSG_FAILURE &&
1596 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1597 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1598 logevent("Requested TIS authentication");
1599 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1601 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1602 logevent("TIS authentication declined");
1603 if (flags & FLAG_INTERACTIVE)
1604 c_write("TIS authentication refused.\r\n", 29);
1606 int challengelen = ((pktin.body[0] << 24) |
1607 (pktin.body[1] << 16) |
1608 (pktin.body[2] << 8) |
1610 logevent("Received TIS challenge");
1611 if (challengelen > sizeof(prompt)-1)
1612 challengelen = sizeof(prompt)-1; /* prevent overrun */
1613 memcpy(prompt, pktin.body+4, challengelen);
1614 prompt[challengelen] = '\0';
1617 if (pktin.type == SSH1_SMSG_FAILURE &&
1619 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1620 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1621 logevent("Requested CryptoCard authentication");
1622 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1624 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1625 logevent("CryptoCard authentication declined");
1626 c_write("CryptoCard authentication refused.\r\n", 29);
1628 int challengelen = ((pktin.body[0] << 24) |
1629 (pktin.body[1] << 16) |
1630 (pktin.body[2] << 8) |
1632 logevent("Received CryptoCard challenge");
1633 if (challengelen > sizeof(prompt)-1)
1634 challengelen = sizeof(prompt)-1; /* prevent overrun */
1635 memcpy(prompt, pktin.body+4, challengelen);
1636 strncpy(prompt + challengelen, "\r\nResponse : ",
1637 sizeof(prompt)-challengelen);
1638 prompt[sizeof(prompt)-1] = '\0';
1641 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1642 sprintf(prompt, "%.90s@%.90s's password: ",
1643 username, savedhost);
1645 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1646 char *comment = NULL;
1647 if (flags & FLAG_VERBOSE)
1648 c_write("Trying public key authentication.\r\n", 35);
1649 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1650 if (flags & FLAG_VERBOSE)
1651 c_write("No passphrase required.\r\n", 25);
1654 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
1658 if (ssh_get_password) {
1659 if (!ssh_get_password(prompt, password, sizeof(password))) {
1661 * get_password failed to get a password (for
1662 * example because one was supplied on the command
1663 * line which has already failed to work).
1666 logevent("No more passwords to try");
1667 ssh_state = SSH_STATE_CLOSED;
1671 c_write(prompt, strlen(prompt));
1675 crWaitUntil(!ispkt);
1676 while (inlen--) switch (c = *in++) {
1693 if (((c >= ' ' && c <= '~') ||
1694 ((unsigned char)c >= 160)) && pos < sizeof(password))
1695 password[pos++] = c;
1703 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1705 * Try public key authentication with the specified
1708 static struct RSAKey pubkey;
1709 static Bignum challenge, response;
1711 static unsigned char buffer[32];
1713 tried_publickey = 1;
1714 i = loadrsakey(cfg.keyfile, &pubkey, NULL, password);
1716 c_write("Couldn't load public key from ", 30);
1717 c_write(cfg.keyfile, strlen(cfg.keyfile));
1718 c_write(".\r\n", 3);
1719 continue; /* go and try password */
1722 c_write("Wrong passphrase.\r\n", 19);
1723 tried_publickey = 0;
1724 continue; /* try again */
1728 * Send a public key attempt.
1730 send_packet(SSH1_CMSG_AUTH_RSA,
1731 PKT_BIGNUM, pubkey.modulus, PKT_END);
1734 if (pktin.type == SSH1_SMSG_FAILURE) {
1735 c_write("Server refused our public key.\r\n", 32);
1736 continue; /* go and try password */
1738 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1739 bombout(("Bizarre response to offer of public key"));
1742 ssh1_read_bignum(pktin.body, &challenge);
1743 response = rsadecrypt(challenge, &pubkey);
1744 freebn(pubkey.private_exponent); /* burn the evidence */
1746 for (i = 0; i < 32; i++) {
1747 buffer[i] = bignum_byte(response, 31-i);
1751 MD5Update(&md5c, buffer, 32);
1752 MD5Update(&md5c, session_id, 16);
1753 MD5Final(buffer, &md5c);
1755 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1756 PKT_DATA, buffer, 16, PKT_END);
1759 if (pktin.type == SSH1_SMSG_FAILURE) {
1760 if (flags & FLAG_VERBOSE)
1761 c_write("Failed to authenticate with our public key.\r\n",
1763 continue; /* go and try password */
1764 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1765 bombout(("Bizarre response to RSA authentication response"));
1769 break; /* we're through! */
1771 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1773 logevent("Sent password");
1774 memset(password, 0, strlen(password));
1776 if (pktin.type == SSH1_SMSG_FAILURE) {
1777 if (flags & FLAG_VERBOSE)
1778 c_write("Access denied\r\n", 15);
1779 logevent("Authentication refused");
1780 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1781 logevent("Received disconnect request");
1782 ssh_state = SSH_STATE_CLOSED;
1784 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1785 bombout(("Strange packet received, type %d", pktin.type));
1790 logevent("Authentication successful");
1795 void sshfwd_close(struct ssh_channel *c) {
1797 if (ssh_version == 1) {
1798 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END);
1800 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
1801 ssh2_pkt_adduint32(c->remoteid);
1805 if (c->type == CHAN_X11) {
1807 logevent("X11 connection terminated");
1812 void sshfwd_write(struct ssh_channel *c, char *buf, int len) {
1813 if (ssh_version == 1) {
1814 send_packet(SSH1_MSG_CHANNEL_DATA,
1815 PKT_INT, c->remoteid,
1820 ssh2_add_channel_data(c, buf, len);
1825 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1830 while (!do_ssh1_login(in, inlen, ispkt)) {
1833 if (ssh_state == SSH_STATE_CLOSED)
1836 if (cfg.agentfwd && agent_exists()) {
1837 logevent("Requesting agent forwarding");
1838 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1839 do { crReturnV; } while (!ispkt);
1840 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1841 bombout(("Protocol confusion"));
1843 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1844 logevent("Agent forwarding refused");
1846 logevent("Agent forwarding enabled");
1847 ssh_agentfwd_enabled = TRUE;
1851 if (cfg.x11_forward) {
1852 char proto[20], data[64];
1853 logevent("Requesting X11 forwarding");
1854 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
1855 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
1856 PKT_STR, proto, PKT_STR, data,
1859 do { crReturnV; } while (!ispkt);
1860 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1861 bombout(("Protocol confusion"));
1863 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1864 logevent("X11 forwarding refused");
1866 logevent("X11 forwarding enabled");
1867 ssh_X11_fwd_enabled = TRUE;
1872 send_packet(SSH1_CMSG_REQUEST_PTY,
1873 PKT_STR, cfg.termtype,
1874 PKT_INT, rows, PKT_INT, cols,
1875 PKT_INT, 0, PKT_INT, 0,
1878 ssh_state = SSH_STATE_INTERMED;
1879 do { crReturnV; } while (!ispkt);
1880 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1881 bombout(("Protocol confusion"));
1883 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1884 c_write("Server refused to allocate pty\r\n", 32);
1885 ssh_editing = ssh_echoing = 1;
1887 logevent("Allocated pty");
1889 ssh_editing = ssh_echoing = 1;
1892 if (cfg.compression) {
1893 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
1894 do { crReturnV; } while (!ispkt);
1895 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1896 bombout(("Protocol confusion"));
1898 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1899 c_write("Server refused to compress\r\n", 32);
1901 logevent("Started compression");
1902 ssh1_compressing = TRUE;
1903 zlib_compress_init();
1904 zlib_decompress_init();
1907 if (*cfg.remote_cmd)
1908 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1910 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1911 logevent("Started session");
1913 ssh_state = SSH_STATE_SESSION;
1917 ssh_special(TS_EOF);
1919 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
1921 ssh_channels = newtree234(ssh_channelcmp);
1925 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1926 pktin.type == SSH1_SMSG_STDERR_DATA) {
1927 long len = GET_32BIT(pktin.body);
1928 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
1930 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1931 ssh_state = SSH_STATE_CLOSED;
1932 logevent("Received disconnect request");
1934 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
1935 /* Remote side is trying to open a channel to talk to our
1936 * X-Server. Give them back a local channel number. */
1938 struct ssh_channel *c, *d;
1941 logevent("Received X11 connect request");
1942 /* Refuse if X11 forwarding is disabled. */
1943 if (!ssh_X11_fwd_enabled) {
1944 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1945 PKT_INT, GET_32BIT(pktin.body),
1947 logevent("Rejected X11 connect request");
1949 c = smalloc(sizeof(struct ssh_channel));
1951 if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
1952 logevent("opening X11 forward connection failed");
1954 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1955 PKT_INT, GET_32BIT(pktin.body),
1958 logevent("opening X11 forward connection succeeded");
1959 for (i=1, d = first234(ssh_channels, &e); d; d = next234(&e)) {
1961 break; /* found a free number */
1964 c->remoteid = GET_32BIT(pktin.body);
1967 c->type = CHAN_X11; /* identify channel type */
1968 add234(ssh_channels, c);
1969 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1970 PKT_INT, c->remoteid, PKT_INT, c->localid,
1972 logevent("Opened X11 forward channel");
1975 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
1976 /* Remote side is trying to open a channel to talk to our
1977 * agent. Give them back a local channel number. */
1979 struct ssh_channel *c;
1982 /* Refuse if agent forwarding is disabled. */
1983 if (!ssh_agentfwd_enabled) {
1984 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1985 PKT_INT, GET_32BIT(pktin.body),
1989 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
1991 break; /* found a free number */
1994 c = smalloc(sizeof(struct ssh_channel));
1995 c->remoteid = GET_32BIT(pktin.body);
1998 c->type = CHAN_AGENT; /* identify channel type */
1999 c->u.a.lensofar = 0;
2000 add234(ssh_channels, c);
2001 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2002 PKT_INT, c->remoteid, PKT_INT, c->localid,
2005 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2006 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
2007 /* Remote side closes a channel. */
2008 unsigned i = GET_32BIT(pktin.body);
2009 struct ssh_channel *c;
2010 c = find234(ssh_channels, &i, ssh_channelfind);
2013 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2014 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
2015 if ((c->closes == 0) && (c->type == CHAN_X11)) {
2016 logevent("X11 connection closed");
2017 assert(c->u.x11.s != NULL);
2018 x11_close(c->u.x11.s);
2021 c->closes |= closetype;
2022 if (c->closes == 3) {
2023 del234(ssh_channels, c);
2027 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2028 /* Data sent down one of our channels. */
2029 int i = GET_32BIT(pktin.body);
2030 int len = GET_32BIT(pktin.body+4);
2031 unsigned char *p = pktin.body+8;
2032 struct ssh_channel *c;
2033 c = find234(ssh_channels, &i, ssh_channelfind);
2037 x11_send(c->u.x11.s, p, len);
2040 /* Data for an agent message. Buffer it. */
2042 if (c->u.a.lensofar < 4) {
2043 int l = min(4 - c->u.a.lensofar, len);
2044 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
2045 p += l; len -= l; c->u.a.lensofar += l;
2047 if (c->u.a.lensofar == 4) {
2048 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
2049 c->u.a.message = smalloc(c->u.a.totallen);
2050 memcpy(c->u.a.message, c->u.a.msglen, 4);
2052 if (c->u.a.lensofar >= 4 && len > 0) {
2053 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
2054 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
2055 p += l; len -= l; c->u.a.lensofar += l;
2057 if (c->u.a.lensofar == c->u.a.totallen) {
2058 void *reply, *sentreply;
2060 agent_query(c->u.a.message, c->u.a.totallen,
2065 /* Fake SSH_AGENT_FAILURE. */
2066 sentreply = "\0\0\0\1\5";
2069 send_packet(SSH1_MSG_CHANNEL_DATA,
2070 PKT_INT, c->remoteid,
2072 PKT_DATA, sentreply, replylen,
2076 sfree(c->u.a.message);
2077 c->u.a.lensofar = 0;
2083 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
2084 /* may be from EXEC_SHELL on some servers */
2085 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2086 /* may be from EXEC_SHELL on some servers
2087 * if no pty is available or in other odd cases. Ignore */
2088 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2089 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2091 bombout(("Strange packet received: type %d", pktin.type));
2096 int len = min(inlen, 512);
2097 send_packet(SSH1_CMSG_STDIN_DATA,
2098 PKT_INT, len, PKT_DATA, in, len, PKT_END);
2109 * Utility routine for decoding comma-separated strings in KEXINIT.
2111 static int in_commasep_string(char *needle, char *haystack, int haylen) {
2112 int needlen = strlen(needle);
2115 * Is it at the start of the string?
2117 if (haylen >= needlen && /* haystack is long enough */
2118 !memcmp(needle, haystack, needlen) && /* initial match */
2119 (haylen == needlen || haystack[needlen] == ',')
2120 /* either , or EOS follows */
2124 * If not, search for the next comma and resume after that.
2125 * If no comma found, terminate.
2127 while (haylen > 0 && *haystack != ',')
2128 haylen--, haystack++;
2131 haylen--, haystack++; /* skip over comma itself */
2136 * SSH2 key creation method.
2138 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr, char *keyspace) {
2140 /* First 20 bytes. */
2143 SHA_Bytes(&s, H, 20);
2144 SHA_Bytes(&s, &chr, 1);
2145 SHA_Bytes(&s, sessid, 20);
2146 SHA_Final(&s, keyspace);
2147 /* Next 20 bytes. */
2150 SHA_Bytes(&s, H, 20);
2151 SHA_Bytes(&s, keyspace, 20);
2152 SHA_Final(&s, keyspace+20);
2156 * Handle the SSH2 transport layer.
2158 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
2162 static Bignum e, f, K;
2163 static const struct ssh_mac **maclist;
2165 static const struct ssh_cipher *cscipher_tobe = NULL;
2166 static const struct ssh_cipher *sccipher_tobe = NULL;
2167 static const struct ssh_mac *csmac_tobe = NULL;
2168 static const struct ssh_mac *scmac_tobe = NULL;
2169 static const struct ssh_compress *cscomp_tobe = NULL;
2170 static const struct ssh_compress *sccomp_tobe = NULL;
2171 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
2172 static int hostkeylen, siglen;
2173 static void *hkey; /* actual host key */
2174 static unsigned char exchange_hash[20];
2175 static unsigned char first_exchange_hash[20];
2176 static unsigned char keyspace[40];
2177 static const struct ssh_cipher *preferred_cipher;
2178 static const struct ssh_compress *preferred_comp;
2179 static int first_kex;
2186 * Set up the preferred cipher and compression.
2188 if (cfg.cipher == CIPHER_BLOWFISH) {
2189 preferred_cipher = &ssh_blowfish_ssh2;
2190 } else if (cfg.cipher == CIPHER_DES) {
2191 logevent("Single DES not supported in SSH2; using 3DES");
2192 preferred_cipher = &ssh_3des_ssh2;
2193 } else if (cfg.cipher == CIPHER_3DES) {
2194 preferred_cipher = &ssh_3des_ssh2;
2196 /* Shouldn't happen, but we do want to initialise to _something_. */
2197 preferred_cipher = &ssh_3des_ssh2;
2199 if (cfg.compression)
2200 preferred_comp = &ssh_zlib;
2202 preferred_comp = &ssh_comp_none;
2205 * Be prepared to work around the buggy MAC problem.
2208 maclist = buggymacs, nmacs = lenof(buggymacs);
2210 maclist = macs, nmacs = lenof(macs);
2214 * Construct and send our key exchange packet.
2216 ssh2_pkt_init(SSH2_MSG_KEXINIT);
2217 for (i = 0; i < 16; i++)
2218 ssh2_pkt_addbyte((unsigned char)random_byte());
2219 /* List key exchange algorithms. */
2220 ssh2_pkt_addstring_start();
2221 for (i = 0; i < lenof(kex_algs); i++) {
2222 ssh2_pkt_addstring_str(kex_algs[i]->name);
2223 if (i < lenof(kex_algs)-1)
2224 ssh2_pkt_addstring_str(",");
2226 /* List server host key algorithms. */
2227 ssh2_pkt_addstring_start();
2228 for (i = 0; i < lenof(hostkey_algs); i++) {
2229 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
2230 if (i < lenof(hostkey_algs)-1)
2231 ssh2_pkt_addstring_str(",");
2233 /* List client->server encryption algorithms. */
2234 ssh2_pkt_addstring_start();
2235 for (i = 0; i < lenof(ciphers)+1; i++) {
2236 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2237 ssh2_pkt_addstring_str(c->name);
2238 if (i < lenof(ciphers))
2239 ssh2_pkt_addstring_str(",");
2241 /* List server->client encryption algorithms. */
2242 ssh2_pkt_addstring_start();
2243 for (i = 0; i < lenof(ciphers)+1; i++) {
2244 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2245 ssh2_pkt_addstring_str(c->name);
2246 if (i < lenof(ciphers))
2247 ssh2_pkt_addstring_str(",");
2249 /* List client->server MAC algorithms. */
2250 ssh2_pkt_addstring_start();
2251 for (i = 0; i < nmacs; i++) {
2252 ssh2_pkt_addstring_str(maclist[i]->name);
2254 ssh2_pkt_addstring_str(",");
2256 /* List server->client MAC algorithms. */
2257 ssh2_pkt_addstring_start();
2258 for (i = 0; i < nmacs; i++) {
2259 ssh2_pkt_addstring_str(maclist[i]->name);
2261 ssh2_pkt_addstring_str(",");
2263 /* List client->server compression algorithms. */
2264 ssh2_pkt_addstring_start();
2265 for (i = 0; i < lenof(compressions)+1; i++) {
2266 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2267 ssh2_pkt_addstring_str(c->name);
2268 if (i < lenof(compressions))
2269 ssh2_pkt_addstring_str(",");
2271 /* List server->client compression algorithms. */
2272 ssh2_pkt_addstring_start();
2273 for (i = 0; i < lenof(compressions)+1; i++) {
2274 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2275 ssh2_pkt_addstring_str(c->name);
2276 if (i < lenof(compressions))
2277 ssh2_pkt_addstring_str(",");
2279 /* List client->server languages. Empty list. */
2280 ssh2_pkt_addstring_start();
2281 /* List server->client languages. Empty list. */
2282 ssh2_pkt_addstring_start();
2283 /* First KEX packet does _not_ follow, because we're not that brave. */
2284 ssh2_pkt_addbool(FALSE);
2286 ssh2_pkt_adduint32(0);
2288 exhash = exhashbase;
2289 sha_string(&exhash, pktout.data+5, pktout.length-5);
2293 if (!ispkt) crWaitUntil(ispkt);
2294 sha_string(&exhash, pktin.data+5, pktin.length-5);
2297 * Now examine the other side's KEXINIT to see what we're up
2300 if (pktin.type != SSH2_MSG_KEXINIT) {
2301 bombout(("expected key exchange packet from server"));
2304 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
2305 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
2306 pktin.savedpos += 16; /* skip garbage cookie */
2307 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
2308 for (i = 0; i < lenof(kex_algs); i++) {
2309 if (in_commasep_string(kex_algs[i]->name, str, len)) {
2314 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
2315 for (i = 0; i < lenof(hostkey_algs); i++) {
2316 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
2317 hostkey = hostkey_algs[i];
2321 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
2322 for (i = 0; i < lenof(ciphers)+1; i++) {
2323 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2324 if (in_commasep_string(c->name, str, len)) {
2329 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
2330 for (i = 0; i < lenof(ciphers)+1; i++) {
2331 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2332 if (in_commasep_string(c->name, str, len)) {
2337 ssh2_pkt_getstring(&str, &len); /* client->server mac */
2338 for (i = 0; i < nmacs; i++) {
2339 if (in_commasep_string(maclist[i]->name, str, len)) {
2340 csmac_tobe = maclist[i];
2344 ssh2_pkt_getstring(&str, &len); /* server->client mac */
2345 for (i = 0; i < nmacs; i++) {
2346 if (in_commasep_string(maclist[i]->name, str, len)) {
2347 scmac_tobe = maclist[i];
2351 ssh2_pkt_getstring(&str, &len); /* client->server compression */
2352 for (i = 0; i < lenof(compressions)+1; i++) {
2353 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2354 if (in_commasep_string(c->name, str, len)) {
2359 ssh2_pkt_getstring(&str, &len); /* server->client compression */
2360 for (i = 0; i < lenof(compressions)+1; i++) {
2361 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2362 if (in_commasep_string(c->name, str, len)) {
2369 * Currently we only support Diffie-Hellman and DSS, so let's
2370 * bomb out if those aren't selected.
2372 if (kex != &ssh_diffiehellman || hostkey != &ssh_dss) {
2373 bombout(("internal fault: chaos in SSH 2 transport layer"));
2378 * Now we begin the fun. Generate and send e for Diffie-Hellman.
2383 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
2388 if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
2389 bombout(("expected key exchange packet from server"));
2392 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2393 f = ssh2_pkt_getmp();
2394 ssh2_pkt_getstring(&sigdata, &siglen);
2398 sha_string(&exhash, hostkeydata, hostkeylen);
2399 sha_mpint(&exhash, e);
2400 sha_mpint(&exhash, f);
2401 sha_mpint(&exhash, K);
2402 SHA_Final(&exhash, exchange_hash);
2407 debug(("Exchange hash is:\r\n"));
2408 for (i = 0; i < 20; i++)
2409 debug((" %02x", exchange_hash[i]));
2413 hkey = hostkey->newkey(hostkeydata, hostkeylen);
2414 if (!hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
2415 bombout(("Server failed host key check"));
2420 * Expect SSH2_MSG_NEWKEYS from server.
2423 if (pktin.type != SSH2_MSG_NEWKEYS) {
2424 bombout(("expected new-keys packet from server"));
2429 * Authenticate remote host: verify host key. (We've already
2430 * checked the signature of the exchange hash.)
2432 keystr = hostkey->fmtkey(hkey);
2433 fingerprint = hostkey->fingerprint(hkey);
2434 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
2435 keystr, fingerprint);
2436 if (first_kex) { /* don't bother logging this in rekeys */
2437 logevent("Host key fingerprint is:");
2438 logevent(fingerprint);
2442 hostkey->freekey(hkey);
2445 * Send SSH2_MSG_NEWKEYS.
2447 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2451 * Create and initialise session keys.
2453 cscipher = cscipher_tobe;
2454 sccipher = sccipher_tobe;
2457 cscomp = cscomp_tobe;
2458 sccomp = sccomp_tobe;
2459 cscomp->compress_init();
2460 sccomp->decompress_init();
2462 * Set IVs after keys. Here we use the exchange hash from the
2463 * _first_ key exchange.
2466 memcpy(first_exchange_hash, exchange_hash, sizeof(exchange_hash));
2467 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'C', keyspace);
2468 cscipher->setcskey(keyspace);
2469 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'D', keyspace);
2470 sccipher->setsckey(keyspace);
2471 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'A', keyspace);
2472 cscipher->setcsiv(keyspace);
2473 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'B', keyspace);
2474 sccipher->setsciv(keyspace);
2475 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'E', keyspace);
2476 csmac->setcskey(keyspace);
2477 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'F', keyspace);
2478 scmac->setsckey(keyspace);
2481 * If this is the first key exchange phase, we must pass the
2482 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2483 * wants to see it but because it will need time to initialise
2484 * itself before it sees an actual packet. In subsequent key
2485 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2486 * it would only confuse the layer above.
2494 * Now we're encrypting. Begin returning 1 to the protocol main
2495 * function so that other things can run on top of the
2496 * transport. If we ever see a KEXINIT, we must go back to the
2499 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
2502 logevent("Server initiated key re-exchange");
2503 goto begin_key_exchange;
2509 * Add data to an SSH2 channel output buffer.
2511 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len) {
2512 if (c->v2.outbufsize <
2513 c->v2.outbuflen + len) {
2515 c->v2.outbuflen + len + 1024;
2516 c->v2.outbuffer = srealloc(c->v2.outbuffer,
2519 memcpy(c->v2.outbuffer + c->v2.outbuflen,
2521 c->v2.outbuflen += len;
2525 * Attempt to send data on an SSH2 channel.
2527 static void ssh2_try_send(struct ssh_channel *c) {
2528 while (c->v2.remwindow > 0 &&
2529 c->v2.outbuflen > 0) {
2530 unsigned len = c->v2.remwindow;
2531 if (len > c->v2.outbuflen)
2532 len = c->v2.outbuflen;
2533 if (len > c->v2.remmaxpkt)
2534 len = c->v2.remmaxpkt;
2535 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2536 ssh2_pkt_adduint32(c->remoteid);
2537 ssh2_pkt_addstring_start();
2538 ssh2_pkt_addstring_data(c->v2.outbuffer, len);
2540 c->v2.outbuflen -= len;
2541 memmove(c->v2.outbuffer, c->v2.outbuffer+len,
2543 c->v2.remwindow -= len;
2548 * Handle the SSH2 userauth and connection layers.
2550 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2552 static unsigned long remote_winsize;
2553 static unsigned long remote_maxpkt;
2558 * Request userauth protocol, and await a response to it.
2560 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2561 ssh2_pkt_addstring("ssh-userauth");
2563 crWaitUntilV(ispkt);
2564 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2565 bombout(("Server refused user authentication protocol"));
2570 * FIXME: currently we support only password authentication.
2571 * (This places us technically in violation of the SSH2 spec.
2572 * We must fix this.)
2576 * Get a username and a password.
2578 static char username[100];
2579 static char password[100];
2583 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2584 c_write("login as: ", 10);
2587 crWaitUntilV(!ispkt);
2588 while (inlen--) switch (c = *in++) {
2595 c_write("\b \b", 3);
2601 c_write("\b \b", 3);
2610 if (((c >= ' ' && c <= '~') ||
2611 ((unsigned char)c >= 160)) && pos < 40) {
2612 username[pos++] = c;
2619 username[strcspn(username, "\n\r")] = '\0';
2622 strncpy(username, cfg.username, 99);
2623 username[99] = '\0';
2624 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
2625 sprintf(stuff, "Using username \"%s\".\r\n", username);
2626 c_write(stuff, strlen(stuff));
2630 if (ssh_get_password) {
2632 sprintf(prompt, "%.90s@%.90s's password: ", username, savedhost);
2633 if (!ssh_get_password(prompt, password, sizeof(password))) {
2635 * get_password failed to get a password (for
2636 * example because one was supplied on the command
2637 * line which has already failed to work).
2640 logevent("No more passwords to try");
2641 ssh_state = SSH_STATE_CLOSED;
2645 c_write("password: ", 10);
2650 crWaitUntilV(!ispkt);
2651 while (inlen--) switch (c = *in++) {
2668 if (((c >= ' ' && c <= '~') ||
2669 ((unsigned char)c >= 160)) && pos < 40)
2670 password[pos++] = c;
2678 * We send the password packet lumped tightly together with
2679 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
2680 * string long enough to make the total length of the two
2681 * packets constant. This should ensure that a passive
2682 * listener doing traffic analyis can't work out the length
2685 * For this to work, we need an assumption about the
2686 * maximum length of the password packet. I think 256 is
2687 * pretty conservative. Anyone using a password longer than
2688 * that probably doesn't have much to worry about from
2689 * people who find out how long their password is!
2691 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2692 ssh2_pkt_addstring(username);
2693 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2694 ssh2_pkt_addstring("password");
2695 ssh2_pkt_addbool(FALSE);
2696 ssh2_pkt_addstring(password);
2699 * We'll include a string that's an exact multiple of the
2700 * cipher block size. If the cipher is NULL for some
2701 * reason, we don't do this trick at all because we gain
2706 ssh2_pkt_init(SSH2_MSG_IGNORE);
2707 ssh2_pkt_addstring_start();
2708 for (i = deferred_len; i <= 256; i += cscipher->blksize) {
2709 for (j = 0; j < cscipher->blksize; j++) {
2710 char c = (char)random_byte();
2711 ssh2_pkt_addstring_data(&c, 1);
2716 ssh2_pkt_defersend();
2718 crWaitUntilV(ispkt);
2719 if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
2720 c_write("Access denied\r\n", 15);
2721 logevent("Authentication refused");
2727 * Now we're authenticated for the connection protocol. The
2728 * connection protocol will automatically have started at this
2729 * point; there's no need to send SERVICE_REQUEST.
2733 * So now create a channel with a session in it.
2735 mainchan = smalloc(sizeof(struct ssh_channel));
2736 mainchan->localid = 100; /* as good as any */
2737 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
2738 ssh2_pkt_addstring("session");
2739 ssh2_pkt_adduint32(mainchan->localid);
2740 ssh2_pkt_adduint32(0x8000UL); /* our window size */
2741 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
2743 crWaitUntilV(ispkt);
2744 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
2745 bombout(("Server refused to open a session"));
2747 /* FIXME: error data comes back in FAILURE packet */
2749 if (ssh2_pkt_getuint32() != mainchan->localid) {
2750 bombout(("Server's channel confirmation cited wrong channel"));
2753 mainchan->remoteid = ssh2_pkt_getuint32();
2754 mainchan->type = CHAN_MAINSESSION;
2755 mainchan->closes = 0;
2756 mainchan->v2.remwindow = ssh2_pkt_getuint32();
2757 mainchan->v2.remmaxpkt = ssh2_pkt_getuint32();
2758 mainchan->v2.outbuffer = NULL;
2759 mainchan->v2.outbuflen = mainchan->v2.outbufsize = 0;
2760 ssh_channels = newtree234(ssh_channelcmp);
2761 add234(ssh_channels, mainchan);
2762 logevent("Opened channel for session");
2765 * Potentially enable X11 forwarding.
2767 if (cfg.x11_forward) {
2768 char proto[20], data[64];
2769 logevent("Requesting X11 forwarding");
2770 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2771 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2772 ssh2_pkt_adduint32(mainchan->remoteid);
2773 ssh2_pkt_addstring("x11-req");
2774 ssh2_pkt_addbool(1); /* want reply */
2775 ssh2_pkt_addbool(0); /* many connections */
2776 ssh2_pkt_addstring(proto);
2777 ssh2_pkt_addstring(data);
2778 ssh2_pkt_adduint32(0); /* screen number */
2782 crWaitUntilV(ispkt);
2783 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2784 unsigned i = ssh2_pkt_getuint32();
2785 struct ssh_channel *c;
2786 c = find234(ssh_channels, &i, ssh_channelfind);
2788 continue; /* nonexistent channel */
2789 c->v2.remwindow += ssh2_pkt_getuint32();
2791 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2793 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2794 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2795 bombout(("Server got confused by X11 forwarding request"));
2798 logevent("X11 forwarding refused");
2800 logevent("X11 forwarding enabled");
2801 ssh_X11_fwd_enabled = TRUE;
2806 * Now allocate a pty for the session.
2809 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2810 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2811 ssh2_pkt_addstring("pty-req");
2812 ssh2_pkt_addbool(1); /* want reply */
2813 ssh2_pkt_addstring(cfg.termtype);
2814 ssh2_pkt_adduint32(cols);
2815 ssh2_pkt_adduint32(rows);
2816 ssh2_pkt_adduint32(0); /* pixel width */
2817 ssh2_pkt_adduint32(0); /* pixel height */
2818 ssh2_pkt_addstring_start();
2819 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
2821 ssh_state = SSH_STATE_INTERMED;
2824 crWaitUntilV(ispkt);
2825 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2826 unsigned i = ssh2_pkt_getuint32();
2827 struct ssh_channel *c;
2828 c = find234(ssh_channels, &i, ssh_channelfind);
2830 continue; /* nonexistent channel */
2831 c->v2.remwindow += ssh2_pkt_getuint32();
2833 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2835 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2836 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2837 bombout(("Server got confused by pty request"));
2840 c_write("Server refused to allocate pty\r\n", 32);
2841 ssh_editing = ssh_echoing = 1;
2843 logevent("Allocated pty");
2846 ssh_editing = ssh_echoing = 1;
2850 * Start a shell or a remote command.
2852 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2853 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2854 if (cfg.ssh_subsys) {
2855 ssh2_pkt_addstring("subsystem");
2856 ssh2_pkt_addbool(1); /* want reply */
2857 ssh2_pkt_addstring(cfg.remote_cmd);
2858 } else if (*cfg.remote_cmd) {
2859 ssh2_pkt_addstring("exec");
2860 ssh2_pkt_addbool(1); /* want reply */
2861 ssh2_pkt_addstring(cfg.remote_cmd);
2863 ssh2_pkt_addstring("shell");
2864 ssh2_pkt_addbool(1); /* want reply */
2868 crWaitUntilV(ispkt);
2869 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2870 unsigned i = ssh2_pkt_getuint32();
2871 struct ssh_channel *c;
2872 c = find234(ssh_channels, &i, ssh_channelfind);
2874 continue; /* nonexistent channel */
2875 c->v2.remwindow += ssh2_pkt_getuint32();
2877 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2878 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2879 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2880 bombout(("Server got confused by shell/command request"));
2883 bombout(("Server refused to start a shell/command"));
2886 logevent("Started a shell/command");
2889 ssh_state = SSH_STATE_SESSION;
2893 ssh_special(TS_EOF);
2898 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
2901 static int try_send;
2905 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
2906 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
2909 unsigned i = ssh2_pkt_getuint32();
2910 struct ssh_channel *c;
2911 c = find234(ssh_channels, &i, ssh_channelfind);
2913 continue; /* nonexistent channel */
2914 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
2915 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
2916 continue; /* extended but not stderr */
2917 ssh2_pkt_getstring(&data, &length);
2920 case CHAN_MAINSESSION:
2921 from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
2925 x11_send(c->u.x11.s, data, length);
2929 * Enlarge the window again at the remote
2930 * side, just in case it ever runs down and
2931 * they fail to send us any more data.
2933 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2934 ssh2_pkt_adduint32(c->remoteid);
2935 ssh2_pkt_adduint32(length);
2938 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
2939 ssh_state = SSH_STATE_CLOSED;
2940 logevent("Received disconnect message");
2942 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2943 continue; /* exit status et al; ignore (FIXME?) */
2944 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
2945 unsigned i = ssh2_pkt_getuint32();
2946 struct ssh_channel *c;
2948 c = find234(ssh_channels, &i, ssh_channelfind);
2950 continue; /* nonexistent channel */
2952 if (c->type == CHAN_X11) {
2954 * Remote EOF on an X11 channel means we should
2955 * wrap up and close the channel ourselves.
2957 x11_close(c->u.x11.s);
2960 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
2961 unsigned i = ssh2_pkt_getuint32();
2962 struct ssh_channel *c;
2965 c = find234(ssh_channels, &i, ssh_channelfind);
2967 continue; /* nonexistent channel */
2968 if (c->closes == 0) {
2969 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2970 ssh2_pkt_adduint32(c->remoteid);
2973 /* Do pre-close processing on the channel. */
2975 case CHAN_MAINSESSION:
2976 break; /* nothing to see here, move along */
2980 del234(ssh_channels, c);
2981 sfree(c->v2.outbuffer);
2985 * See if that was the last channel left open.
2987 c = first234(ssh_channels, &e);
2989 logevent("All channels closed. Disconnecting");
2990 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
2991 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
2992 ssh2_pkt_addstring("All open channels closed");
2993 ssh2_pkt_addstring("en"); /* language tag */
2995 ssh_state = SSH_STATE_CLOSED;
2998 continue; /* remote sends close; ignore (FIXME) */
2999 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3000 unsigned i = ssh2_pkt_getuint32();
3001 struct ssh_channel *c;
3002 c = find234(ssh_channels, &i, ssh_channelfind);
3004 continue; /* nonexistent channel */
3005 mainchan->v2.remwindow += ssh2_pkt_getuint32();
3007 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
3011 struct ssh_channel *c;
3012 ssh2_pkt_getstring(&type, &typelen);
3013 c = smalloc(sizeof(struct ssh_channel));
3015 if (typelen == 3 && !memcmp(type, "x11", 3)) {
3016 if (!ssh_X11_fwd_enabled)
3017 error = "X11 forwarding is not enabled";
3018 else if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
3019 error = "Unable to open an X11 connection";
3024 error = "Unsupported channel type requested";
3027 c->remoteid = ssh2_pkt_getuint32();
3029 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
3030 ssh2_pkt_adduint32(c->remoteid);
3031 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
3032 ssh2_pkt_addstring(error);
3033 ssh2_pkt_addstring("en"); /* language tag */
3037 struct ssh_channel *d;
3041 for (i=1, d = first234(ssh_channels, &e); d;
3044 break; /* found a free number */
3049 c->v2.remwindow = ssh2_pkt_getuint32();
3050 c->v2.remmaxpkt = ssh2_pkt_getuint32();
3051 c->v2.outbuffer = NULL;
3052 c->v2.outbuflen = c->v2.outbufsize = 0;
3053 add234(ssh_channels, c);
3054 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
3055 ssh2_pkt_adduint32(c->remoteid);
3056 ssh2_pkt_adduint32(c->localid);
3057 ssh2_pkt_adduint32(0x8000UL); /* our window size */
3058 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
3062 bombout(("Strange packet received: type %d", pktin.type));
3067 * We have spare data. Add it to the channel buffer.
3069 ssh2_add_channel_data(mainchan, in, inlen);
3074 struct ssh_channel *c;
3076 * Try to send data on all channels if we can.
3078 for (c = first234(ssh_channels, &e); c; c = next234(&e))
3087 * Handle the top-level SSH2 protocol.
3089 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
3091 if (do_ssh2_transport(in, inlen, ispkt) == 0)
3093 do_ssh2_authconn(in, inlen, ispkt);
3097 * Called to set up the connection.
3099 * Returns an error message, or NULL on success.
3101 static char *ssh_init (char *host, int port, char **realhost) {
3105 if(crypto_startup() == 0)
3106 return "Microsoft high encryption pack not installed!";
3113 p = connect_to_host(host, port, realhost);
3121 * Called to send data down the Telnet connection.
3123 static void ssh_send (char *buf, int len) {
3124 if (s == NULL || ssh_protocol == NULL)
3127 ssh_protocol(buf, len, 0);
3131 * Called to set the size of the window from SSH's POV.
3133 static void ssh_size(void) {
3134 switch (ssh_state) {
3135 case SSH_STATE_BEFORE_SIZE:
3136 case SSH_STATE_PREPACKET:
3137 case SSH_STATE_CLOSED:
3138 break; /* do nothing */
3139 case SSH_STATE_INTERMED:
3140 size_needed = TRUE; /* buffer for later */
3142 case SSH_STATE_SESSION:
3144 if (ssh_version == 1) {
3145 send_packet(SSH1_CMSG_WINDOW_SIZE,
3146 PKT_INT, rows, PKT_INT, cols,
3147 PKT_INT, 0, PKT_INT, 0, PKT_END);
3149 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3150 ssh2_pkt_adduint32(mainchan->remoteid);
3151 ssh2_pkt_addstring("window-change");
3152 ssh2_pkt_addbool(0);
3153 ssh2_pkt_adduint32(cols);
3154 ssh2_pkt_adduint32(rows);
3155 ssh2_pkt_adduint32(0);
3156 ssh2_pkt_adduint32(0);
3165 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3166 * can send an EOF and collect resulting output (e.g. `plink
3169 static void ssh_special (Telnet_Special code) {
3170 if (code == TS_EOF) {
3171 if (ssh_state != SSH_STATE_SESSION) {
3173 * Buffer the EOF in case we are pre-SESSION, so we can
3174 * send it as soon as we reach SESSION.
3180 if (ssh_version == 1) {
3181 send_packet(SSH1_CMSG_EOF, PKT_END);
3183 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
3184 ssh2_pkt_adduint32(mainchan->remoteid);
3187 logevent("Sent EOF message");
3188 } else if (code == TS_PING) {
3189 if (ssh_state == SSH_STATE_CLOSED || ssh_state == SSH_STATE_PREPACKET)
3191 if (ssh_version == 1) {
3192 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
3194 ssh2_pkt_init(SSH2_MSG_IGNORE);
3195 ssh2_pkt_addstring_start();
3203 static Socket ssh_socket(void) { return s; }
3205 static int ssh_sendok(void) { return ssh_send_ok; }
3207 static int ssh_ldisc(int option) {
3208 if (option == LD_ECHO) return ssh_echoing;
3209 if (option == LD_EDIT) return ssh_editing;
3213 Backend ssh_backend = {