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, sk_close(s), \
23 s = NULL, connection_fatal msg )
25 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
26 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
27 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
28 #define SSH1_CMSG_USER 4 /* 0x4 */
29 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
30 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
31 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
32 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
33 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
34 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
35 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
36 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
37 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
38 #define SSH1_SMSG_FAILURE 15 /* 0xf */
39 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
40 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
41 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
42 #define SSH1_CMSG_EOF 19 /* 0x13 */
43 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
44 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
45 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
46 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
47 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
48 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
49 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
50 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
51 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
52 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
53 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
54 #define SSH1_MSG_IGNORE 32 /* 0x20 */
55 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
56 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
57 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
58 #define SSH1_MSG_DEBUG 36 /* 0x24 */
59 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
60 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
61 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
62 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
63 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
64 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
65 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
67 #define SSH1_AUTH_TIS 5 /* 0x5 */
68 #define SSH1_AUTH_CCARD 16 /* 0x10 */
70 #define SSH_AGENTC_REQUEST_RSA_IDENTITIES 1 /* 0x1 */
71 #define SSH_AGENT_RSA_IDENTITIES_ANSWER 2 /* 0x2 */
72 #define SSH_AGENTC_RSA_CHALLENGE 3 /* 0x3 */
73 #define SSH_AGENT_RSA_RESPONSE 4 /* 0x4 */
74 #define SSH_AGENT_FAILURE 5 /* 0x5 */
75 #define SSH_AGENT_SUCCESS 6 /* 0x6 */
76 #define SSH_AGENTC_ADD_RSA_IDENTITY 7 /* 0x7 */
77 #define SSH_AGENTC_REMOVE_RSA_IDENTITY 8 /* 0x8 */
79 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
80 #define SSH2_MSG_IGNORE 2 /* 0x2 */
81 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
82 #define SSH2_MSG_DEBUG 4 /* 0x4 */
83 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
84 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
85 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
86 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
87 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
88 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
89 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
90 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
91 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
92 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
93 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
94 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
95 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
96 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
97 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
98 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
99 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
100 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
101 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
102 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
103 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
104 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
105 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
106 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
107 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
108 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
110 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
111 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
112 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
113 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
114 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
115 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
116 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
117 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
118 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
119 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
120 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
122 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
123 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
124 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
125 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
127 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
129 #define GET_32BIT(cp) \
130 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
131 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
132 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
133 ((unsigned long)(unsigned char)(cp)[3]))
135 #define PUT_32BIT(cp, value) { \
136 (cp)[0] = (unsigned char)((value) >> 24); \
137 (cp)[1] = (unsigned char)((value) >> 16); \
138 (cp)[2] = (unsigned char)((value) >> 8); \
139 (cp)[3] = (unsigned char)(value); }
141 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
143 /* Coroutine mechanics for the sillier bits of the code */
144 #define crBegin1 static int crLine = 0;
145 #define crBegin2 switch(crLine) { case 0:;
146 #define crBegin crBegin1; crBegin2;
147 #define crFinish(z) } crLine = 0; return (z)
148 #define crFinishV } crLine = 0; return
149 #define crReturn(z) \
151 crLine=__LINE__; return (z); case __LINE__:;\
155 crLine=__LINE__; return; case __LINE__:;\
157 #define crStop(z) do{ crLine = 0; return (z); }while(0)
158 #define crStopV do{ crLine = 0; return; }while(0)
159 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
160 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
162 extern const struct ssh_cipher ssh_3des;
163 extern const struct ssh_cipher ssh_3des_ssh2;
164 extern const struct ssh_cipher ssh_des;
165 extern const struct ssh_cipher ssh_blowfish_ssh1;
166 extern const struct ssh_cipher ssh_blowfish_ssh2;
168 extern char *x11_init (Socket *, char *, void *);
169 extern void x11_close (Socket);
170 extern void x11_send (Socket , char *, int);
171 extern void x11_invent_auth(char *, int, char *, int);
174 * Ciphers for SSH2. We miss out single-DES because it isn't
175 * supported; also 3DES and Blowfish are both done differently from
176 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
177 * endianness and different-sized keys.)
179 const static struct ssh_cipher *ciphers[] = { &ssh_blowfish_ssh2, &ssh_3des_ssh2 };
181 extern const struct ssh_kex ssh_diffiehellman;
182 const static struct ssh_kex *kex_algs[] = { &ssh_diffiehellman };
184 extern const struct ssh_signkey ssh_dss;
185 const static struct ssh_signkey *hostkey_algs[] = { &ssh_dss };
187 extern const struct ssh_mac ssh_md5, ssh_sha1, ssh_sha1_buggy;
189 static void nullmac_key(unsigned char *key) { }
190 static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
191 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
192 const static struct ssh_mac ssh_mac_none = {
193 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
195 const static struct ssh_mac *macs[] = {
196 &ssh_sha1, &ssh_md5, &ssh_mac_none };
197 const static struct ssh_mac *buggymacs[] = {
198 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none };
200 static void ssh_comp_none_init(void) { }
201 static int ssh_comp_none_block(unsigned char *block, int len,
202 unsigned char **outblock, int *outlen) {
205 const static struct ssh_compress ssh_comp_none = {
207 ssh_comp_none_init, ssh_comp_none_block,
208 ssh_comp_none_init, ssh_comp_none_block
210 extern const struct ssh_compress ssh_zlib;
211 const static struct ssh_compress *compressions[] = {
212 &ssh_zlib, &ssh_comp_none };
214 enum { /* channel types */
221 * 2-3-4 tree storing channels.
224 unsigned remoteid, localid;
227 struct ssh2_data_channel {
228 unsigned char *outbuffer;
229 unsigned outbuflen, outbufsize;
230 unsigned remwindow, remmaxpkt;
233 struct ssh_agent_channel {
234 unsigned char *message;
235 unsigned char msglen[4];
236 int lensofar, totallen;
238 struct ssh_x11_channel {
253 static SHA_State exhash, exhashbase;
255 static Socket s = NULL;
257 static unsigned char session_key[32];
258 static int ssh1_compressing;
259 static int ssh_agentfwd_enabled;
260 static int ssh_X11_fwd_enabled;
261 static const struct ssh_cipher *cipher = NULL;
262 static const struct ssh_cipher *cscipher = NULL;
263 static const struct ssh_cipher *sccipher = NULL;
264 static const struct ssh_mac *csmac = NULL;
265 static const struct ssh_mac *scmac = NULL;
266 static const struct ssh_compress *cscomp = NULL;
267 static const struct ssh_compress *sccomp = NULL;
268 static const struct ssh_kex *kex = NULL;
269 static const struct ssh_signkey *hostkey = NULL;
270 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
272 static char *savedhost;
273 static int savedport;
274 static int ssh_send_ok;
276 static tree234 *ssh_channels; /* indexed by local id */
277 static struct ssh_channel *mainchan; /* primary session channel */
281 SSH_STATE_BEFORE_SIZE,
285 } ssh_state = SSH_STATE_PREPACKET;
287 static int size_needed = FALSE, eof_needed = FALSE;
289 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
290 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
292 static int ssh_version;
293 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
294 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
295 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
296 static void ssh_size(void);
297 static void ssh_special (Telnet_Special);
298 static void ssh2_try_send(struct ssh_channel *c);
299 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
301 static int (*s_rdpkt)(unsigned char **data, int *datalen);
303 static struct rdpkt1_state_tag {
304 long len, pad, biglen, to_read;
305 unsigned long realcrc, gotcrc;
311 static struct rdpkt2_state_tag {
312 long len, pad, payload, packetlen, maclen;
315 unsigned long incoming_sequence;
318 static int ssh_channelcmp(void *av, void *bv) {
319 struct ssh_channel *a = (struct ssh_channel *)av;
320 struct ssh_channel *b = (struct ssh_channel *)bv;
321 if (a->localid < b->localid) return -1;
322 if (a->localid > b->localid) return +1;
325 static int ssh_channelfind(void *av, void *bv) {
326 unsigned *a = (unsigned *)av;
327 struct ssh_channel *b = (struct ssh_channel *)bv;
328 if (*a < b->localid) return -1;
329 if (*a > b->localid) return +1;
333 static void c_write (char *buf, int len) {
334 if ((flags & FLAG_STDERR)) {
336 for (i = 0; i < len; i++)
338 fputc(buf[i], stderr);
341 from_backend(1, buf, len);
345 * Collect incoming data in the incoming packet buffer.
346 * Decipher and verify the packet when it is completely read.
347 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
348 * Update the *data and *datalen variables.
349 * Return the additional nr of bytes needed, or 0 when
350 * a complete packet is available.
352 static int ssh1_rdpkt(unsigned char **data, int *datalen)
354 struct rdpkt1_state_tag *st = &rdpkt1_state;
363 for (st->i = st->len = 0; st->i < 4; st->i++) {
364 while ((*datalen) == 0)
366 st->len = (st->len << 8) + **data;
367 (*data)++, (*datalen)--;
371 if (st->len == 0x52656d6f) { /* "Remo"te server has closed ... */
372 st->len = 0x300; /* big enough to carry to end */
376 st->pad = 8 - (st->len % 8);
377 st->biglen = st->len + st->pad;
378 pktin.length = st->len - 5;
380 if (pktin.maxlen < st->biglen) {
381 pktin.maxlen = st->biglen;
382 pktin.data = (pktin.data == NULL ? smalloc(st->biglen+APIEXTRA) :
383 srealloc(pktin.data, st->biglen+APIEXTRA));
385 fatalbox("Out of memory");
388 st->to_read = st->biglen;
390 while (st->to_read > 0) {
391 st->chunk = st->to_read;
392 while ((*datalen) == 0)
393 crReturn(st->to_read);
394 if (st->chunk > (*datalen))
395 st->chunk = (*datalen);
396 memcpy(st->p, *data, st->chunk);
398 *datalen -= st->chunk;
400 st->to_read -= st->chunk;
404 cipher->decrypt(pktin.data, st->biglen);
406 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
407 for (st->i = 0; st->i < st->biglen; st->i++)
408 debug((" %02x", (unsigned char)pktin.data[st->i]));
412 st->realcrc = crc32(pktin.data, st->biglen-4);
413 st->gotcrc = GET_32BIT(pktin.data+st->biglen-4);
414 if (st->gotcrc != st->realcrc) {
415 bombout(("Incorrect CRC received on packet"));
419 pktin.body = pktin.data + st->pad + 1;
421 if (ssh1_compressing) {
422 unsigned char *decompblk;
426 debug(("Packet payload pre-decompression:\n"));
427 for (i = -1; i < pktin.length; i++)
428 debug((" %02x", (unsigned char)pktin.body[i]));
431 zlib_decompress_block(pktin.body-1, pktin.length+1,
432 &decompblk, &decomplen);
434 if (pktin.maxlen < st->pad + decomplen) {
435 pktin.maxlen = st->pad + decomplen;
436 pktin.data = srealloc(pktin.data, pktin.maxlen+APIEXTRA);
437 pktin.body = pktin.data + st->pad + 1;
439 fatalbox("Out of memory");
442 memcpy(pktin.body-1, decompblk, decomplen);
444 pktin.length = decomplen-1;
446 debug(("Packet payload post-decompression:\n"));
447 for (i = -1; i < pktin.length; i++)
448 debug((" %02x", (unsigned char)pktin.body[i]));
453 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
454 pktin.type == SSH1_SMSG_STDERR_DATA ||
455 pktin.type == SSH1_MSG_DEBUG ||
456 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
457 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
458 long strlen = GET_32BIT(pktin.body);
459 if (strlen + 4 != pktin.length) {
460 bombout(("Received data packet with bogus string length"));
465 pktin.type = pktin.body[-1];
467 if (pktin.type == SSH1_MSG_DEBUG) {
468 /* log debug message */
470 int strlen = GET_32BIT(pktin.body);
471 strcpy(buf, "Remote: ");
472 if (strlen > 70) strlen = 70;
473 memcpy(buf+8, pktin.body+4, strlen);
474 buf[8+strlen] = '\0';
477 } else if (pktin.type == SSH1_MSG_IGNORE) {
485 static int ssh2_rdpkt(unsigned char **data, int *datalen)
487 struct rdpkt2_state_tag *st = &rdpkt2_state;
495 st->cipherblk = sccipher->blksize;
498 if (st->cipherblk < 8)
501 if (pktin.maxlen < st->cipherblk) {
502 pktin.maxlen = st->cipherblk;
503 pktin.data = (pktin.data == NULL ? smalloc(st->cipherblk+APIEXTRA) :
504 srealloc(pktin.data, st->cipherblk+APIEXTRA));
506 fatalbox("Out of memory");
510 * Acquire and decrypt the first block of the packet. This will
511 * contain the length and padding details.
513 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
514 while ((*datalen) == 0)
515 crReturn(st->cipherblk-st->i);
516 pktin.data[st->i] = *(*data)++;
520 if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
525 sccipher->decrypt(pktin.data, st->cipherblk);
528 * Now get the length and padding figures.
530 st->len = GET_32BIT(pktin.data);
531 st->pad = pktin.data[4];
534 * This enables us to deduce the payload length.
536 st->payload = st->len - st->pad - 1;
538 pktin.length = st->payload + 5;
541 * So now we can work out the total packet length.
543 st->packetlen = st->len + 4;
544 st->maclen = scmac ? scmac->len : 0;
547 * Adjust memory allocation if packet is too big.
549 if (pktin.maxlen < st->packetlen+st->maclen) {
550 pktin.maxlen = st->packetlen+st->maclen;
551 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
552 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
554 fatalbox("Out of memory");
558 * Read and decrypt the remainder of the packet.
560 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen; st->i++) {
561 while ((*datalen) == 0)
562 crReturn(st->packetlen + st->maclen - st->i);
563 pktin.data[st->i] = *(*data)++;
566 /* Decrypt everything _except_ the MAC. */
568 sccipher->decrypt(pktin.data + st->cipherblk,
569 st->packetlen - st->cipherblk);
572 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
573 for (st->i = 0; st->i < st->packetlen; st->i++)
574 debug((" %02x", (unsigned char)pktin.data[st->i]));
581 if (scmac && !scmac->verify(pktin.data, st->len+4, st->incoming_sequence)) {
582 bombout(("Incorrect MAC received on packet"));
585 st->incoming_sequence++; /* whether or not we MACed */
588 * Decompress packet payload.
591 unsigned char *newpayload;
593 if (sccomp && sccomp->decompress(pktin.data+5, pktin.length-5,
594 &newpayload, &newlen)) {
595 if (pktin.maxlen < newlen+5) {
596 pktin.maxlen = newlen+5;
597 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
598 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
600 fatalbox("Out of memory");
602 pktin.length = 5 + newlen;
603 memcpy(pktin.data+5, newpayload, newlen);
605 debug(("Post-decompression payload:\r\n"));
606 for (st->i = 0; st->i < newlen; st->i++)
607 debug((" %02x", (unsigned char)pktin.data[5+st->i]));
616 pktin.type = pktin.data[5];
618 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
619 goto next_packet; /* FIXME: print DEBUG message */
624 static void ssh1_pktout_size(int len) {
627 len += 5; /* type and CRC */
631 pktout.length = len-5;
632 if (pktout.maxlen < biglen) {
633 pktout.maxlen = biglen;
635 /* Allocate enough buffer space for extra block
636 * for MS CryptEncrypt() */
637 pktout.data = (pktout.data == NULL ? smalloc(biglen+12) :
638 srealloc(pktout.data, biglen+12));
640 pktout.data = (pktout.data == NULL ? smalloc(biglen+4) :
641 srealloc(pktout.data, biglen+4));
644 fatalbox("Out of memory");
646 pktout.body = pktout.data+4+pad+1;
649 static void s_wrpkt_start(int type, int len) {
650 ssh1_pktout_size(len);
654 static void s_wrpkt(void) {
655 int pad, len, biglen, i;
658 pktout.body[-1] = pktout.type;
660 if (ssh1_compressing) {
661 unsigned char *compblk;
664 debug(("Packet payload pre-compression:\n"));
665 for (i = -1; i < pktout.length; i++)
666 debug((" %02x", (unsigned char)pktout.body[i]));
669 zlib_compress_block(pktout.body-1, pktout.length+1,
671 ssh1_pktout_size(complen-1);
672 memcpy(pktout.body-1, compblk, complen);
675 debug(("Packet payload post-compression:\n"));
676 for (i = -1; i < pktout.length; i++)
677 debug((" %02x", (unsigned char)pktout.body[i]));
682 len = pktout.length + 5; /* type and CRC */
686 for (i=0; i<pad; i++)
687 pktout.data[i+4] = random_byte();
688 crc = crc32(pktout.data+4, biglen-4);
689 PUT_32BIT(pktout.data+biglen, crc);
690 PUT_32BIT(pktout.data, len);
693 debug(("Sending packet len=%d\r\n", biglen+4));
694 for (i = 0; i < biglen+4; i++)
695 debug((" %02x", (unsigned char)pktout.data[i]));
699 cipher->encrypt(pktout.data+4, biglen);
701 sk_write(s, pktout.data, biglen+4);
705 * Construct a packet with the specified contents and
706 * send it to the server.
708 static void send_packet(int pkttype, ...)
711 unsigned char *p, *argp, argchar;
712 unsigned long argint;
713 int pktlen, argtype, arglen;
717 va_start(args, pkttype);
718 while ((argtype = va_arg(args, int)) != PKT_END) {
721 (void) va_arg(args, int);
725 (void) va_arg(args, char);
729 (void) va_arg(args, unsigned char *);
730 arglen = va_arg(args, int);
734 argp = va_arg(args, unsigned char *);
735 arglen = strlen(argp);
736 pktlen += 4 + arglen;
739 bn = va_arg(args, Bignum);
740 pktlen += ssh1_bignum_length(bn);
748 s_wrpkt_start(pkttype, pktlen);
751 va_start(args, pkttype);
752 while ((argtype = va_arg(args, int)) != PKT_END) {
755 argint = va_arg(args, int);
756 PUT_32BIT(p, argint);
760 argchar = va_arg(args, unsigned char);
765 argp = va_arg(args, unsigned char *);
766 arglen = va_arg(args, int);
767 memcpy(p, argp, arglen);
771 argp = va_arg(args, unsigned char *);
772 arglen = strlen(argp);
773 PUT_32BIT(p, arglen);
774 memcpy(p + 4, argp, arglen);
778 bn = va_arg(args, Bignum);
779 p += ssh1_write_bignum(p, bn);
788 static int ssh_versioncmp(char *a, char *b) {
790 unsigned long av, bv;
792 av = strtoul(a, &ae, 10);
793 bv = strtoul(b, &be, 10);
794 if (av != bv) return (av < bv ? -1 : +1);
795 if (*ae == '.') ae++;
796 if (*be == '.') be++;
797 av = strtoul(ae, &ae, 10);
798 bv = strtoul(be, &be, 10);
799 if (av != bv) return (av < bv ? -1 : +1);
805 * Utility routine for putting an SSH-protocol `string' into a SHA
809 static void sha_string(SHA_State *s, void *str, int len) {
810 unsigned char lenblk[4];
811 PUT_32BIT(lenblk, len);
812 SHA_Bytes(s, lenblk, 4);
813 SHA_Bytes(s, str, len);
817 * SSH2 packet construction functions.
819 static void ssh2_pkt_ensure(int length) {
820 if (pktout.maxlen < length) {
821 pktout.maxlen = length + 256;
822 pktout.data = (pktout.data == NULL ? smalloc(pktout.maxlen+APIEXTRA) :
823 srealloc(pktout.data, pktout.maxlen+APIEXTRA));
825 fatalbox("Out of memory");
828 static void ssh2_pkt_adddata(void *data, int len) {
829 pktout.length += len;
830 ssh2_pkt_ensure(pktout.length);
831 memcpy(pktout.data+pktout.length-len, data, len);
833 static void ssh2_pkt_addbyte(unsigned char byte) {
834 ssh2_pkt_adddata(&byte, 1);
836 static void ssh2_pkt_init(int pkt_type) {
838 ssh2_pkt_addbyte((unsigned char)pkt_type);
840 static void ssh2_pkt_addbool(unsigned char value) {
841 ssh2_pkt_adddata(&value, 1);
843 static void ssh2_pkt_adduint32(unsigned long value) {
846 ssh2_pkt_adddata(x, 4);
848 static void ssh2_pkt_addstring_start(void) {
849 ssh2_pkt_adduint32(0);
850 pktout.savedpos = pktout.length;
852 static void ssh2_pkt_addstring_str(char *data) {
853 ssh2_pkt_adddata(data, strlen(data));
854 PUT_32BIT(pktout.data + pktout.savedpos - 4,
855 pktout.length - pktout.savedpos);
857 static void ssh2_pkt_addstring_data(char *data, int len) {
858 ssh2_pkt_adddata(data, len);
859 PUT_32BIT(pktout.data + pktout.savedpos - 4,
860 pktout.length - pktout.savedpos);
862 static void ssh2_pkt_addstring(char *data) {
863 ssh2_pkt_addstring_start();
864 ssh2_pkt_addstring_str(data);
866 static char *ssh2_mpint_fmt(Bignum b, int *len) {
869 p = smalloc(n * 2 + 1);
871 fatalbox("out of memory");
873 for (i = 0; i < n; i++) {
874 p[i*2+1] = (b[n-i] >> 8) & 0xFF;
875 p[i*2+2] = (b[n-i] ) & 0xFF;
878 while (p[i] == 0 && (p[i+1] & 0x80) == 0)
880 memmove(p, p+i, n*2+1-i);
884 static void ssh2_pkt_addmp(Bignum b) {
887 p = ssh2_mpint_fmt(b, &len);
888 ssh2_pkt_addstring_start();
889 ssh2_pkt_addstring_data(p, len);
892 static void ssh2_pkt_send(void) {
893 int cipherblk, maclen, padding, i;
894 static unsigned long outgoing_sequence = 0;
897 * Compress packet payload.
900 debug(("Pre-compression payload:\r\n"));
901 for (i = 5; i < pktout.length; i++)
902 debug((" %02x", (unsigned char)pktout.data[i]));
906 unsigned char *newpayload;
908 if (cscomp && cscomp->compress(pktout.data+5, pktout.length-5,
909 &newpayload, &newlen)) {
911 ssh2_pkt_adddata(newpayload, newlen);
917 * Add padding. At least four bytes, and must also bring total
918 * length (minus MAC) up to a multiple of the block size.
920 cipherblk = cipher ? cipher->blksize : 8; /* block size */
921 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
923 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
924 maclen = csmac ? csmac->len : 0;
925 ssh2_pkt_ensure(pktout.length + padding + maclen);
926 pktout.data[4] = padding;
927 for (i = 0; i < padding; i++)
928 pktout.data[pktout.length + i] = random_byte();
929 PUT_32BIT(pktout.data, pktout.length + padding - 4);
931 csmac->generate(pktout.data, pktout.length + padding,
933 outgoing_sequence++; /* whether or not we MACed */
936 debug(("Sending packet len=%d\r\n", pktout.length+padding));
937 for (i = 0; i < pktout.length+padding; i++)
938 debug((" %02x", (unsigned char)pktout.data[i]));
943 cscipher->encrypt(pktout.data, pktout.length + padding);
945 sk_write(s, pktout.data, pktout.length + padding + maclen);
949 void bndebug(char *string, Bignum b) {
952 p = ssh2_mpint_fmt(b, &len);
953 debug(("%s", string));
954 for (i = 0; i < len; i++)
955 debug((" %02x", p[i]));
961 static void sha_mpint(SHA_State *s, Bignum b) {
964 p = ssh2_mpint_fmt(b, &len);
965 sha_string(s, p, len);
970 * SSH2 packet decode functions.
972 static unsigned long ssh2_pkt_getuint32(void) {
974 if (pktin.length - pktin.savedpos < 4)
975 return 0; /* arrgh, no way to decline (FIXME?) */
976 value = GET_32BIT(pktin.data+pktin.savedpos);
980 static void ssh2_pkt_getstring(char **p, int *length) {
982 if (pktin.length - pktin.savedpos < 4)
984 *length = GET_32BIT(pktin.data+pktin.savedpos);
986 if (pktin.length - pktin.savedpos < *length)
988 *p = pktin.data+pktin.savedpos;
989 pktin.savedpos += *length;
991 static Bignum ssh2_pkt_getmp(void) {
996 ssh2_pkt_getstring(&p, &length);
1000 bombout(("internal error: Can't handle negative mpints"));
1003 b = newbn((length+1)/2);
1004 for (i = 0; i < length; i++) {
1007 b[j/2+1] |= ((unsigned char)p[i]) << 8;
1009 b[j/2+1] |= ((unsigned char)p[i]);
1011 while (b[0] > 1 && b[b[0]] == 0) b[0]--;
1015 static int do_ssh_init(unsigned char c) {
1017 static char version[10];
1018 static char vstring[80];
1019 static char vlog[sizeof(vstring)+20];
1024 /* Search for the string "SSH-" in the input. */
1027 static const int transS[] = { 1, 2, 2, 1 };
1028 static const int transH[] = { 0, 0, 3, 0 };
1029 static const int transminus[] = { 0, 0, 0, -1 };
1030 if (c == 'S') i = transS[i];
1031 else if (c == 'H') i = transH[i];
1032 else if (c == '-') i = transminus[i];
1036 crReturn(1); /* get another character */
1039 strcpy(vstring, "SSH-");
1043 crReturn(1); /* get another char */
1044 if (vsp < vstring+sizeof(vstring)-1)
1050 } else if (i < sizeof(version)-1)
1057 ssh_agentfwd_enabled = FALSE;
1058 rdpkt2_state.incoming_sequence = 0;
1061 sprintf(vlog, "Server version: %s", vstring);
1062 vlog[strcspn(vlog, "\r\n")] = '\0';
1066 * Server version "1.99" means we can choose whether we use v1
1067 * or v2 protocol. Choice is based on cfg.sshprot.
1069 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1071 * This is a v2 server. Begin v2 protocol.
1073 char *verstring = "SSH-2.0-PuTTY";
1074 SHA_Init(&exhashbase);
1076 * Hash our version string and their version string.
1078 sha_string(&exhashbase, verstring, strlen(verstring));
1079 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1080 sprintf(vstring, "%s\n", verstring);
1081 sprintf(vlog, "We claim version: %s", verstring);
1083 logevent("Using SSH protocol version 2");
1084 sk_write(s, vstring, strlen(vstring));
1085 ssh_protocol = ssh2_protocol;
1087 s_rdpkt = ssh2_rdpkt;
1090 * This is a v1 server. Begin v1 protocol.
1092 sprintf(vstring, "SSH-%s-PuTTY\n",
1093 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1094 sprintf(vlog, "We claim version: %s", vstring);
1095 vlog[strcspn(vlog, "\r\n")] = '\0';
1097 logevent("Using SSH protocol version 1");
1098 sk_write(s, vstring, strlen(vstring));
1099 ssh_protocol = ssh1_protocol;
1101 s_rdpkt = ssh1_rdpkt;
1103 ssh_state = SSH_STATE_BEFORE_SIZE;
1108 static void ssh_gotdata(unsigned char *data, int datalen)
1113 * To begin with, feed the characters one by one to the
1114 * protocol initialisation / selection function do_ssh_init().
1115 * When that returns 0, we're done with the initial greeting
1116 * exchange and can move on to packet discipline.
1121 crReturnV; /* more data please */
1122 ret = do_ssh_init(*data);
1129 * We emerge from that loop when the initial negotiation is
1130 * over and we have selected an s_rdpkt function. Now pass
1131 * everything to s_rdpkt, and then pass the resulting packets
1132 * to the proper protocol handler.
1137 while (datalen > 0) {
1138 if ( s_rdpkt(&data, &datalen) == 0 ) {
1139 ssh_protocol(NULL, 0, 1);
1140 if (ssh_state == SSH_STATE_CLOSED) {
1150 static int ssh_receive(Socket skt, int urgent, char *data, int len) {
1152 /* Connection has closed. */
1153 ssh_state = SSH_STATE_CLOSED;
1158 ssh_gotdata (data, len);
1159 if (ssh_state == SSH_STATE_CLOSED) {
1170 * Connect to specified host and port.
1171 * Returns an error message, or NULL on success.
1172 * Also places the canonical host name into `realhost'.
1174 static char *connect_to_host(char *host, int port, char **realhost)
1183 savedhost = smalloc(1+strlen(host));
1185 fatalbox("Out of memory");
1186 strcpy(savedhost, host);
1189 port = 22; /* default ssh port */
1202 addr = sk_namelookup(host, realhost);
1203 if ( (err = sk_addr_error(addr)) )
1213 s = sk_new(addr, port, 0, ssh_receive);
1214 if ( (err = sk_socket_error(s)) )
1218 sk_write(s, "connect ", 8);
1219 sk_write(s, FWhost, strlen(FWhost));
1222 sprintf(buf, " %d\n", FWport);
1223 sk_write(s, buf, strlen(buf));
1231 * Handle the key exchange and user authentication phases.
1233 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1236 unsigned char *rsabuf, *keystr1, *keystr2;
1237 unsigned char cookie[8];
1238 struct RSAKey servkey, hostkey;
1239 struct MD5Context md5c;
1240 static unsigned long supported_ciphers_mask, supported_auths_mask;
1241 static int tried_publickey;
1242 static unsigned char session_id[16];
1244 static char username[100];
1248 if (!ispkt) crWaitUntil(ispkt);
1250 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1251 bombout(("Public key packet not received"));
1255 logevent("Received public keys");
1257 memcpy(cookie, pktin.body, 8);
1259 i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1260 j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1263 * Log the host key fingerprint.
1267 logevent("Host key fingerprint is:");
1268 strcpy(logmsg, " ");
1269 hostkey.comment = NULL;
1270 rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
1275 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1276 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1279 MD5Update(&md5c, keystr2, hostkey.bytes);
1280 MD5Update(&md5c, keystr1, servkey.bytes);
1281 MD5Update(&md5c, pktin.body, 8);
1282 MD5Final(session_id, &md5c);
1284 for (i=0; i<32; i++)
1285 session_key[i] = random_byte();
1287 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1289 rsabuf = smalloc(len);
1291 fatalbox("Out of memory");
1294 * Verify the host key.
1298 * First format the key into a string.
1300 int len = rsastr_len(&hostkey);
1301 char fingerprint[100];
1302 char *keystr = smalloc(len);
1304 fatalbox("Out of memory");
1305 rsastr_fmt(keystr, &hostkey);
1306 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
1307 verify_ssh_host_key(savedhost, savedport, "rsa", keystr, fingerprint);
1311 for (i=0; i<32; i++) {
1312 rsabuf[i] = session_key[i];
1314 rsabuf[i] ^= session_id[i];
1317 if (hostkey.bytes > servkey.bytes) {
1318 rsaencrypt(rsabuf, 32, &servkey);
1319 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1321 rsaencrypt(rsabuf, 32, &hostkey);
1322 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1325 logevent("Encrypted session key");
1327 cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
1328 cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES :
1330 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1331 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1332 cipher_type = SSH_CIPHER_3DES;
1334 switch (cipher_type) {
1335 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1336 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1337 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1340 send_packet(SSH1_CMSG_SESSION_KEY,
1341 PKT_CHAR, cipher_type,
1342 PKT_DATA, cookie, 8,
1343 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1344 PKT_DATA, rsabuf, len,
1348 logevent("Trying to enable encryption...");
1352 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1353 cipher_type == SSH_CIPHER_DES ? &ssh_des :
1355 cipher->sesskey(session_key);
1359 if (pktin.type != SSH1_SMSG_SUCCESS) {
1360 bombout(("Encryption not successfully enabled"));
1364 logevent("Successfully started encryption");
1370 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1371 c_write("login as: ", 10);
1374 crWaitUntil(!ispkt);
1375 while (inlen--) switch (c = *in++) {
1382 c_write("\b \b", 3);
1388 c_write("\b \b", 3);
1397 if (((c >= ' ' && c <= '~') ||
1398 ((unsigned char)c >= 160)) && pos < 40) {
1399 username[pos++] = c;
1406 username[strcspn(username, "\n\r")] = '\0';
1408 strncpy(username, cfg.username, 99);
1409 username[99] = '\0';
1412 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1414 char userlog[22+sizeof(username)];
1415 sprintf(userlog, "Sent username \"%s\"", username);
1417 if (flags & FLAG_INTERACTIVE &&
1418 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
1419 strcat(userlog, "\r\n");
1420 c_write(userlog, strlen(userlog));
1427 tried_publickey = 0;
1429 while (pktin.type == SSH1_SMSG_FAILURE) {
1430 static char password[100];
1431 static char prompt[200];
1434 static int pwpkt_type;
1436 * Show password prompt, having first obtained it via a TIS
1437 * or CryptoCard exchange if we're doing TIS or CryptoCard
1440 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1441 if (agent_exists()) {
1443 * Attempt RSA authentication using Pageant.
1445 static unsigned char request[5], *response, *p;
1446 static int responselen;
1447 static int i, nkeys;
1448 static int authed = FALSE;
1451 logevent("Pageant is running. Requesting keys.");
1453 /* Request the keys held by the agent. */
1454 PUT_32BIT(request, 1);
1455 request[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
1456 agent_query(request, 5, &r, &responselen);
1457 response = (unsigned char *)r;
1460 nkeys = GET_32BIT(p); p += 4;
1461 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
1463 for (i = 0; i < nkeys; i++) {
1464 static struct RSAKey key;
1465 static Bignum challenge;
1466 static char *commentp;
1467 static int commentlen;
1469 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1472 p += ssh1_read_bignum(p, &key.exponent);
1473 p += ssh1_read_bignum(p, &key.modulus);
1474 commentlen = GET_32BIT(p); p += 4;
1475 commentp = p; p += commentlen;
1476 send_packet(SSH1_CMSG_AUTH_RSA,
1477 PKT_BIGNUM, key.modulus, PKT_END);
1479 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1480 logevent("Key refused");
1483 logevent("Received RSA challenge");
1484 ssh1_read_bignum(pktin.body, &challenge);
1486 char *agentreq, *q, *ret;
1488 len = 1 + 4; /* message type, bit count */
1489 len += ssh1_bignum_length(key.exponent);
1490 len += ssh1_bignum_length(key.modulus);
1491 len += ssh1_bignum_length(challenge);
1492 len += 16; /* session id */
1493 len += 4; /* response format */
1494 agentreq = smalloc(4 + len);
1495 PUT_32BIT(agentreq, len);
1497 *q++ = SSH_AGENTC_RSA_CHALLENGE;
1498 PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1500 q += ssh1_write_bignum(q, key.exponent);
1501 q += ssh1_write_bignum(q, key.modulus);
1502 q += ssh1_write_bignum(q, challenge);
1503 memcpy(q, session_id, 16); q += 16;
1504 PUT_32BIT(q, 1); /* response format */
1505 agent_query(agentreq, len+4, &ret, &retlen);
1508 if (ret[4] == SSH_AGENT_RSA_RESPONSE) {
1509 logevent("Sending Pageant's response");
1510 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1511 PKT_DATA, ret+5, 16, PKT_END);
1514 if (pktin.type == SSH1_SMSG_SUCCESS) {
1515 logevent("Pageant's response accepted");
1516 if (flags & FLAG_VERBOSE) {
1517 c_write("Authenticated using RSA key \"",
1519 c_write(commentp, commentlen);
1520 c_write("\" from agent\r\n", 14);
1524 logevent("Pageant's response not accepted");
1526 logevent("Pageant failed to answer challenge");
1530 logevent("No reply received from Pageant");
1533 freebn(key.exponent);
1534 freebn(key.modulus);
1543 if (*cfg.keyfile && !tried_publickey)
1544 pwpkt_type = SSH1_CMSG_AUTH_RSA;
1546 if (pktin.type == SSH1_SMSG_FAILURE &&
1548 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1549 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1550 logevent("Requested TIS authentication");
1551 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1553 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1554 logevent("TIS authentication declined");
1555 if (flags & FLAG_INTERACTIVE)
1556 c_write("TIS authentication refused.\r\n", 29);
1558 int challengelen = ((pktin.body[0] << 24) |
1559 (pktin.body[1] << 16) |
1560 (pktin.body[2] << 8) |
1562 logevent("Received TIS challenge");
1563 if (challengelen > sizeof(prompt)-1)
1564 challengelen = sizeof(prompt)-1; /* prevent overrun */
1565 memcpy(prompt, pktin.body+4, challengelen);
1566 prompt[challengelen] = '\0';
1569 if (pktin.type == SSH1_SMSG_FAILURE &&
1571 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1572 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1573 logevent("Requested CryptoCard authentication");
1574 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1576 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1577 logevent("CryptoCard authentication declined");
1578 c_write("CryptoCard authentication refused.\r\n", 29);
1580 int challengelen = ((pktin.body[0] << 24) |
1581 (pktin.body[1] << 16) |
1582 (pktin.body[2] << 8) |
1584 logevent("Received CryptoCard challenge");
1585 if (challengelen > sizeof(prompt)-1)
1586 challengelen = sizeof(prompt)-1; /* prevent overrun */
1587 memcpy(prompt, pktin.body+4, challengelen);
1588 strncpy(prompt + challengelen, "\r\nResponse : ",
1589 sizeof(prompt)-challengelen);
1590 prompt[sizeof(prompt)-1] = '\0';
1593 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1594 sprintf(prompt, "%.90s@%.90s's password: ",
1595 username, savedhost);
1597 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1598 char *comment = NULL;
1599 if (flags & FLAG_VERBOSE)
1600 c_write("Trying public key authentication.\r\n", 35);
1601 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1602 if (flags & FLAG_VERBOSE)
1603 c_write("No passphrase required.\r\n", 25);
1606 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
1610 if (ssh_get_password) {
1611 if (!ssh_get_password(prompt, password, sizeof(password))) {
1613 * get_password failed to get a password (for
1614 * example because one was supplied on the command
1615 * line which has already failed to work).
1618 logevent("No more passwords to try");
1619 ssh_state = SSH_STATE_CLOSED;
1623 c_write(prompt, strlen(prompt));
1627 crWaitUntil(!ispkt);
1628 while (inlen--) switch (c = *in++) {
1645 if (((c >= ' ' && c <= '~') ||
1646 ((unsigned char)c >= 160)) && pos < sizeof(password))
1647 password[pos++] = c;
1655 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1657 * Try public key authentication with the specified
1660 static struct RSAKey pubkey;
1661 static Bignum challenge, response;
1663 static unsigned char buffer[32];
1665 tried_publickey = 1;
1666 i = loadrsakey(cfg.keyfile, &pubkey, NULL, password);
1668 c_write("Couldn't load public key from ", 30);
1669 c_write(cfg.keyfile, strlen(cfg.keyfile));
1670 c_write(".\r\n", 3);
1671 continue; /* go and try password */
1674 c_write("Wrong passphrase.\r\n", 19);
1675 tried_publickey = 0;
1676 continue; /* try again */
1680 * Send a public key attempt.
1682 send_packet(SSH1_CMSG_AUTH_RSA,
1683 PKT_BIGNUM, pubkey.modulus, PKT_END);
1686 if (pktin.type == SSH1_SMSG_FAILURE) {
1687 c_write("Server refused our public key.\r\n", 32);
1688 continue; /* go and try password */
1690 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1691 bombout(("Bizarre response to offer of public key"));
1694 ssh1_read_bignum(pktin.body, &challenge);
1695 response = rsadecrypt(challenge, &pubkey);
1696 freebn(pubkey.private_exponent); /* burn the evidence */
1698 for (i = 0; i < 32; i += 2) {
1699 buffer[i] = response[16-i/2] >> 8;
1700 buffer[i+1] = response[16-i/2] & 0xFF;
1704 MD5Update(&md5c, buffer, 32);
1705 MD5Update(&md5c, session_id, 16);
1706 MD5Final(buffer, &md5c);
1708 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1709 PKT_DATA, buffer, 16, PKT_END);
1712 if (pktin.type == SSH1_SMSG_FAILURE) {
1713 if (flags & FLAG_VERBOSE)
1714 c_write("Failed to authenticate with our public key.\r\n",
1716 continue; /* go and try password */
1717 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1718 bombout(("Bizarre response to RSA authentication response"));
1722 break; /* we're through! */
1724 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1726 logevent("Sent password");
1727 memset(password, 0, strlen(password));
1729 if (pktin.type == SSH1_SMSG_FAILURE) {
1730 if (flags & FLAG_VERBOSE)
1731 c_write("Access denied\r\n", 15);
1732 logevent("Authentication refused");
1733 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1734 logevent("Received disconnect request");
1735 ssh_state = SSH_STATE_CLOSED;
1737 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1738 bombout(("Strange packet received, type %d", pktin.type));
1743 logevent("Authentication successful");
1748 void sshfwd_close(struct ssh_channel *c) {
1750 if (ssh_version == 1) {
1751 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END);
1753 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
1754 ssh2_pkt_adduint32(c->remoteid);
1758 if (c->type == CHAN_X11) {
1760 logevent("X11 connection terminated");
1765 void sshfwd_write(struct ssh_channel *c, char *buf, int len) {
1766 if (ssh_version == 1) {
1767 send_packet(SSH1_MSG_CHANNEL_DATA,
1768 PKT_INT, c->remoteid,
1773 ssh2_add_channel_data(c, buf, len);
1778 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1783 while (!do_ssh1_login(in, inlen, ispkt)) {
1786 if (ssh_state == SSH_STATE_CLOSED)
1789 if (cfg.agentfwd && agent_exists()) {
1790 logevent("Requesting agent forwarding");
1791 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1792 do { crReturnV; } while (!ispkt);
1793 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1794 bombout(("Protocol confusion"));
1796 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1797 logevent("Agent forwarding refused");
1799 logevent("Agent forwarding enabled");
1800 ssh_agentfwd_enabled = TRUE;
1804 if (cfg.x11_forward) {
1805 char proto[20], data[64];
1806 logevent("Requesting X11 forwarding");
1807 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
1808 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
1809 PKT_STR, proto, PKT_STR, data,
1812 do { crReturnV; } while (!ispkt);
1813 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1814 bombout(("Protocol confusion"));
1816 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1817 logevent("X11 forwarding refused");
1819 logevent("X11 forwarding enabled");
1820 ssh_X11_fwd_enabled = TRUE;
1825 send_packet(SSH1_CMSG_REQUEST_PTY,
1826 PKT_STR, cfg.termtype,
1827 PKT_INT, rows, PKT_INT, cols,
1828 PKT_INT, 0, PKT_INT, 0,
1831 ssh_state = SSH_STATE_INTERMED;
1832 do { crReturnV; } while (!ispkt);
1833 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1834 bombout(("Protocol confusion"));
1836 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1837 c_write("Server refused to allocate pty\r\n", 32);
1839 logevent("Allocated pty");
1842 if (cfg.compression) {
1843 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
1844 do { crReturnV; } while (!ispkt);
1845 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1846 bombout(("Protocol confusion"));
1848 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1849 c_write("Server refused to compress\r\n", 32);
1851 logevent("Started compression");
1852 ssh1_compressing = TRUE;
1853 zlib_compress_init();
1854 zlib_decompress_init();
1857 if (*cfg.remote_cmd)
1858 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1860 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1861 logevent("Started session");
1863 ssh_state = SSH_STATE_SESSION;
1867 ssh_special(TS_EOF);
1870 ssh_channels = newtree234(ssh_channelcmp);
1875 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1876 pktin.type == SSH1_SMSG_STDERR_DATA) {
1877 long len = GET_32BIT(pktin.body);
1878 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
1880 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1881 ssh_state = SSH_STATE_CLOSED;
1882 logevent("Received disconnect request");
1884 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
1885 /* Remote side is trying to open a channel to talk to our
1886 * X-Server. Give them back a local channel number. */
1888 struct ssh_channel *c, *d;
1891 logevent("Received X11 connect request");
1892 /* Refuse if X11 forwarding is disabled. */
1893 if (!ssh_X11_fwd_enabled) {
1894 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1895 PKT_INT, GET_32BIT(pktin.body),
1897 logevent("Rejected X11 connect request");
1899 c = smalloc(sizeof(struct ssh_channel));
1901 if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
1902 logevent("opening X11 forward connection failed");
1904 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1905 PKT_INT, GET_32BIT(pktin.body),
1908 logevent("opening X11 forward connection succeeded");
1909 for (i=1, d = first234(ssh_channels, &e); d; d = next234(&e)) {
1911 break; /* found a free number */
1914 c->remoteid = GET_32BIT(pktin.body);
1917 c->type = CHAN_X11; /* identify channel type */
1918 add234(ssh_channels, c);
1919 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1920 PKT_INT, c->remoteid, PKT_INT, c->localid,
1922 logevent("Opened X11 forward channel");
1925 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
1926 /* Remote side is trying to open a channel to talk to our
1927 * agent. Give them back a local channel number. */
1929 struct ssh_channel *c;
1932 /* Refuse if agent forwarding is disabled. */
1933 if (!ssh_agentfwd_enabled) {
1934 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1935 PKT_INT, GET_32BIT(pktin.body),
1939 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
1941 break; /* found a free number */
1944 c = smalloc(sizeof(struct ssh_channel));
1945 c->remoteid = GET_32BIT(pktin.body);
1948 c->type = CHAN_AGENT; /* identify channel type */
1949 c->u.a.lensofar = 0;
1950 add234(ssh_channels, c);
1951 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1952 PKT_INT, c->remoteid, PKT_INT, c->localid,
1955 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
1956 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
1957 /* Remote side closes a channel. */
1958 unsigned i = GET_32BIT(pktin.body);
1959 struct ssh_channel *c;
1960 c = find234(ssh_channels, &i, ssh_channelfind);
1963 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
1964 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
1965 if ((c->closes == 0) && (c->type == CHAN_X11)) {
1966 logevent("X11 connection closed");
1967 assert(c->u.x11.s != NULL);
1968 x11_close(c->u.x11.s);
1971 c->closes |= closetype;
1972 if (c->closes == 3) {
1973 del234(ssh_channels, c);
1977 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
1978 /* Data sent down one of our channels. */
1979 int i = GET_32BIT(pktin.body);
1980 int len = GET_32BIT(pktin.body+4);
1981 unsigned char *p = pktin.body+8;
1982 struct ssh_channel *c;
1983 c = find234(ssh_channels, &i, ssh_channelfind);
1987 x11_send(c->u.x11.s, p, len);
1990 /* Data for an agent message. Buffer it. */
1992 if (c->u.a.lensofar < 4) {
1993 int l = min(4 - c->u.a.lensofar, len);
1994 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
1995 p += l; len -= l; c->u.a.lensofar += l;
1997 if (c->u.a.lensofar == 4) {
1998 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
1999 c->u.a.message = smalloc(c->u.a.totallen);
2000 memcpy(c->u.a.message, c->u.a.msglen, 4);
2002 if (c->u.a.lensofar >= 4 && len > 0) {
2003 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
2004 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
2005 p += l; len -= l; c->u.a.lensofar += l;
2007 if (c->u.a.lensofar == c->u.a.totallen) {
2008 void *reply, *sentreply;
2010 agent_query(c->u.a.message, c->u.a.totallen,
2015 /* Fake SSH_AGENT_FAILURE. */
2016 sentreply = "\0\0\0\1\5";
2019 send_packet(SSH1_MSG_CHANNEL_DATA,
2020 PKT_INT, c->remoteid,
2022 PKT_DATA, sentreply, replylen,
2026 sfree(c->u.a.message);
2027 c->u.a.lensofar = 0;
2033 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
2034 /* may be from EXEC_SHELL on some servers */
2035 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2036 /* may be from EXEC_SHELL on some servers
2037 * if no pty is available or in other odd cases. Ignore */
2038 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2039 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2041 bombout(("Strange packet received: type %d", pktin.type));
2046 int len = min(inlen, 512);
2047 send_packet(SSH1_CMSG_STDIN_DATA,
2048 PKT_INT, len, PKT_DATA, in, len, PKT_END);
2059 * Utility routine for decoding comma-separated strings in KEXINIT.
2061 static int in_commasep_string(char *needle, char *haystack, int haylen) {
2062 int needlen = strlen(needle);
2065 * Is it at the start of the string?
2067 if (haylen >= needlen && /* haystack is long enough */
2068 !memcmp(needle, haystack, needlen) && /* initial match */
2069 (haylen == needlen || haystack[needlen] == ',')
2070 /* either , or EOS follows */
2074 * If not, search for the next comma and resume after that.
2075 * If no comma found, terminate.
2077 while (haylen > 0 && *haystack != ',')
2078 haylen--, haystack++;
2081 haylen--, haystack++; /* skip over comma itself */
2086 * SSH2 key creation method.
2088 static void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
2090 /* First 20 bytes. */
2093 SHA_Bytes(&s, H, 20);
2094 SHA_Bytes(&s, &chr, 1);
2095 SHA_Bytes(&s, H, 20);
2096 SHA_Final(&s, keyspace);
2097 /* Next 20 bytes. */
2100 SHA_Bytes(&s, H, 20);
2101 SHA_Bytes(&s, keyspace, 20);
2102 SHA_Final(&s, keyspace+20);
2106 * Handle the SSH2 transport layer.
2108 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
2112 static Bignum e, f, K;
2113 static const struct ssh_mac **maclist;
2115 static const struct ssh_cipher *cscipher_tobe = NULL;
2116 static const struct ssh_cipher *sccipher_tobe = NULL;
2117 static const struct ssh_mac *csmac_tobe = NULL;
2118 static const struct ssh_mac *scmac_tobe = NULL;
2119 static const struct ssh_compress *cscomp_tobe = NULL;
2120 static const struct ssh_compress *sccomp_tobe = NULL;
2121 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
2122 static int hostkeylen, siglen;
2123 static void *hkey; /* actual host key */
2124 static unsigned char exchange_hash[20];
2125 static unsigned char keyspace[40];
2126 static const struct ssh_cipher *preferred_cipher;
2127 static const struct ssh_compress *preferred_comp;
2128 static int first_kex;
2135 * Set up the preferred cipher and compression.
2137 if (cfg.cipher == CIPHER_BLOWFISH) {
2138 preferred_cipher = &ssh_blowfish_ssh2;
2139 } else if (cfg.cipher == CIPHER_DES) {
2140 logevent("Single DES not supported in SSH2; using 3DES");
2141 preferred_cipher = &ssh_3des_ssh2;
2142 } else if (cfg.cipher == CIPHER_3DES) {
2143 preferred_cipher = &ssh_3des_ssh2;
2145 /* Shouldn't happen, but we do want to initialise to _something_. */
2146 preferred_cipher = &ssh_3des_ssh2;
2148 if (cfg.compression)
2149 preferred_comp = &ssh_zlib;
2151 preferred_comp = &ssh_comp_none;
2154 * Be prepared to work around the buggy MAC problem.
2157 maclist = buggymacs, nmacs = lenof(buggymacs);
2159 maclist = macs, nmacs = lenof(macs);
2163 * Construct and send our key exchange packet.
2165 ssh2_pkt_init(SSH2_MSG_KEXINIT);
2166 for (i = 0; i < 16; i++)
2167 ssh2_pkt_addbyte((unsigned char)random_byte());
2168 /* List key exchange algorithms. */
2169 ssh2_pkt_addstring_start();
2170 for (i = 0; i < lenof(kex_algs); i++) {
2171 ssh2_pkt_addstring_str(kex_algs[i]->name);
2172 if (i < lenof(kex_algs)-1)
2173 ssh2_pkt_addstring_str(",");
2175 /* List server host key algorithms. */
2176 ssh2_pkt_addstring_start();
2177 for (i = 0; i < lenof(hostkey_algs); i++) {
2178 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
2179 if (i < lenof(hostkey_algs)-1)
2180 ssh2_pkt_addstring_str(",");
2182 /* List client->server encryption algorithms. */
2183 ssh2_pkt_addstring_start();
2184 for (i = 0; i < lenof(ciphers)+1; i++) {
2185 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2186 ssh2_pkt_addstring_str(c->name);
2187 if (i < lenof(ciphers))
2188 ssh2_pkt_addstring_str(",");
2190 /* List server->client encryption algorithms. */
2191 ssh2_pkt_addstring_start();
2192 for (i = 0; i < lenof(ciphers)+1; i++) {
2193 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2194 ssh2_pkt_addstring_str(c->name);
2195 if (i < lenof(ciphers))
2196 ssh2_pkt_addstring_str(",");
2198 /* List client->server MAC algorithms. */
2199 ssh2_pkt_addstring_start();
2200 for (i = 0; i < nmacs; i++) {
2201 ssh2_pkt_addstring_str(maclist[i]->name);
2203 ssh2_pkt_addstring_str(",");
2205 /* List server->client MAC algorithms. */
2206 ssh2_pkt_addstring_start();
2207 for (i = 0; i < nmacs; i++) {
2208 ssh2_pkt_addstring_str(maclist[i]->name);
2210 ssh2_pkt_addstring_str(",");
2212 /* List client->server compression algorithms. */
2213 ssh2_pkt_addstring_start();
2214 for (i = 0; i < lenof(compressions)+1; i++) {
2215 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2216 ssh2_pkt_addstring_str(c->name);
2217 if (i < lenof(compressions))
2218 ssh2_pkt_addstring_str(",");
2220 /* List server->client compression algorithms. */
2221 ssh2_pkt_addstring_start();
2222 for (i = 0; i < lenof(compressions)+1; i++) {
2223 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2224 ssh2_pkt_addstring_str(c->name);
2225 if (i < lenof(compressions))
2226 ssh2_pkt_addstring_str(",");
2228 /* List client->server languages. Empty list. */
2229 ssh2_pkt_addstring_start();
2230 /* List server->client languages. Empty list. */
2231 ssh2_pkt_addstring_start();
2232 /* First KEX packet does _not_ follow, because we're not that brave. */
2233 ssh2_pkt_addbool(FALSE);
2235 ssh2_pkt_adduint32(0);
2237 exhash = exhashbase;
2238 sha_string(&exhash, pktout.data+5, pktout.length-5);
2242 if (!ispkt) crWaitUntil(ispkt);
2243 sha_string(&exhash, pktin.data+5, pktin.length-5);
2246 * Now examine the other side's KEXINIT to see what we're up
2249 if (pktin.type != SSH2_MSG_KEXINIT) {
2250 bombout(("expected key exchange packet from server"));
2253 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
2254 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
2255 pktin.savedpos += 16; /* skip garbage cookie */
2256 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
2257 for (i = 0; i < lenof(kex_algs); i++) {
2258 if (in_commasep_string(kex_algs[i]->name, str, len)) {
2263 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
2264 for (i = 0; i < lenof(hostkey_algs); i++) {
2265 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
2266 hostkey = hostkey_algs[i];
2270 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
2271 for (i = 0; i < lenof(ciphers)+1; i++) {
2272 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2273 if (in_commasep_string(c->name, str, len)) {
2278 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
2279 for (i = 0; i < lenof(ciphers)+1; i++) {
2280 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2281 if (in_commasep_string(c->name, str, len)) {
2286 ssh2_pkt_getstring(&str, &len); /* client->server mac */
2287 for (i = 0; i < nmacs; i++) {
2288 if (in_commasep_string(maclist[i]->name, str, len)) {
2289 csmac_tobe = maclist[i];
2293 ssh2_pkt_getstring(&str, &len); /* server->client mac */
2294 for (i = 0; i < nmacs; i++) {
2295 if (in_commasep_string(maclist[i]->name, str, len)) {
2296 scmac_tobe = maclist[i];
2300 ssh2_pkt_getstring(&str, &len); /* client->server compression */
2301 for (i = 0; i < lenof(compressions)+1; i++) {
2302 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2303 if (in_commasep_string(c->name, str, len)) {
2308 ssh2_pkt_getstring(&str, &len); /* server->client compression */
2309 for (i = 0; i < lenof(compressions)+1; i++) {
2310 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2311 if (in_commasep_string(c->name, str, len)) {
2318 * Currently we only support Diffie-Hellman and DSS, so let's
2319 * bomb out if those aren't selected.
2321 if (kex != &ssh_diffiehellman || hostkey != &ssh_dss) {
2322 bombout(("internal fault: chaos in SSH 2 transport layer"));
2327 * Now we begin the fun. Generate and send e for Diffie-Hellman.
2330 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
2335 if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
2336 bombout(("expected key exchange packet from server"));
2339 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2340 f = ssh2_pkt_getmp();
2341 ssh2_pkt_getstring(&sigdata, &siglen);
2345 sha_string(&exhash, hostkeydata, hostkeylen);
2346 sha_mpint(&exhash, e);
2347 sha_mpint(&exhash, f);
2348 sha_mpint(&exhash, K);
2349 SHA_Final(&exhash, exchange_hash);
2352 debug(("Exchange hash is:\r\n"));
2353 for (i = 0; i < 20; i++)
2354 debug((" %02x", exchange_hash[i]));
2358 hkey = hostkey->newkey(hostkeydata, hostkeylen);
2359 if (!hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
2360 bombout(("Server failed host key check"));
2365 * Expect SSH2_MSG_NEWKEYS from server.
2368 if (pktin.type != SSH2_MSG_NEWKEYS) {
2369 bombout(("expected new-keys packet from server"));
2374 * Authenticate remote host: verify host key. (We've already
2375 * checked the signature of the exchange hash.)
2377 keystr = hostkey->fmtkey(hkey);
2378 fingerprint = hostkey->fingerprint(hkey);
2379 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
2380 keystr, fingerprint);
2381 logevent("Host key fingerprint is:");
2382 logevent(fingerprint);
2385 hostkey->freekey(hkey);
2388 * Send SSH2_MSG_NEWKEYS.
2390 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2394 * Create and initialise session keys.
2396 cscipher = cscipher_tobe;
2397 sccipher = sccipher_tobe;
2400 cscomp = cscomp_tobe;
2401 sccomp = sccomp_tobe;
2402 cscomp->compress_init();
2403 sccomp->decompress_init();
2405 * Set IVs after keys.
2407 ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
2408 ssh2_mkkey(K, exchange_hash, 'D', keyspace); sccipher->setsckey(keyspace);
2409 ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
2410 ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
2411 ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
2412 ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
2415 * If this is the first key exchange phase, we must pass the
2416 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2417 * wants to see it but because it will need time to initialise
2418 * itself before it sees an actual packet. In subsequent key
2419 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2420 * it would only confuse the layer above.
2428 * Now we're encrypting. Begin returning 1 to the protocol main
2429 * function so that other things can run on top of the
2430 * transport. If we ever see a KEXINIT, we must go back to the
2435 } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
2436 goto begin_key_exchange;
2442 * Add data to an SSH2 channel output buffer.
2444 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len) {
2445 if (c->v2.outbufsize <
2446 c->v2.outbuflen + len) {
2448 c->v2.outbuflen + len + 1024;
2449 c->v2.outbuffer = srealloc(c->v2.outbuffer,
2452 memcpy(c->v2.outbuffer + c->v2.outbuflen,
2454 c->v2.outbuflen += len;
2458 * Attempt to send data on an SSH2 channel.
2460 static void ssh2_try_send(struct ssh_channel *c) {
2461 while (c->v2.remwindow > 0 &&
2462 c->v2.outbuflen > 0) {
2463 unsigned len = c->v2.remwindow;
2464 if (len > c->v2.outbuflen)
2465 len = c->v2.outbuflen;
2466 if (len > c->v2.remmaxpkt)
2467 len = c->v2.remmaxpkt;
2468 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2469 ssh2_pkt_adduint32(c->remoteid);
2470 ssh2_pkt_addstring_start();
2471 ssh2_pkt_addstring_data(c->v2.outbuffer, len);
2473 c->v2.outbuflen -= len;
2474 memmove(c->v2.outbuffer, c->v2.outbuffer+len,
2476 c->v2.remwindow -= len;
2481 * Handle the SSH2 userauth and connection layers.
2483 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2485 static unsigned long remote_winsize;
2486 static unsigned long remote_maxpkt;
2491 * Request userauth protocol, and await a response to it.
2493 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2494 ssh2_pkt_addstring("ssh-userauth");
2496 crWaitUntilV(ispkt);
2497 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2498 bombout(("Server refused user authentication protocol"));
2503 * FIXME: currently we support only password authentication.
2504 * (This places us technically in violation of the SSH2 spec.
2505 * We must fix this.)
2509 * Get a username and a password.
2511 static char username[100];
2512 static char password[100];
2516 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2517 c_write("login as: ", 10);
2520 crWaitUntilV(!ispkt);
2521 while (inlen--) switch (c = *in++) {
2528 c_write("\b \b", 3);
2534 c_write("\b \b", 3);
2543 if (((c >= ' ' && c <= '~') ||
2544 ((unsigned char)c >= 160)) && pos < 40) {
2545 username[pos++] = c;
2552 username[strcspn(username, "\n\r")] = '\0';
2555 strncpy(username, cfg.username, 99);
2556 username[99] = '\0';
2557 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
2558 sprintf(stuff, "Using username \"%s\".\r\n", username);
2559 c_write(stuff, strlen(stuff));
2563 if (ssh_get_password) {
2565 sprintf(prompt, "%.90s@%.90s's password: ", username, savedhost);
2566 if (!ssh_get_password(prompt, password, sizeof(password))) {
2568 * get_password failed to get a password (for
2569 * example because one was supplied on the command
2570 * line which has already failed to work).
2573 logevent("No more passwords to try");
2574 ssh_state = SSH_STATE_CLOSED;
2578 c_write("password: ", 10);
2583 crWaitUntilV(!ispkt);
2584 while (inlen--) switch (c = *in++) {
2601 if (((c >= ' ' && c <= '~') ||
2602 ((unsigned char)c >= 160)) && pos < 40)
2603 password[pos++] = c;
2610 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2611 ssh2_pkt_addstring(username);
2612 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2613 ssh2_pkt_addstring("password");
2614 ssh2_pkt_addbool(FALSE);
2615 ssh2_pkt_addstring(password);
2618 crWaitUntilV(ispkt);
2619 if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
2620 c_write("Access denied\r\n", 15);
2621 logevent("Authentication refused");
2627 * Now we're authenticated for the connection protocol. The
2628 * connection protocol will automatically have started at this
2629 * point; there's no need to send SERVICE_REQUEST.
2633 * So now create a channel with a session in it.
2635 mainchan = smalloc(sizeof(struct ssh_channel));
2636 mainchan->localid = 100; /* as good as any */
2637 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
2638 ssh2_pkt_addstring("session");
2639 ssh2_pkt_adduint32(mainchan->localid);
2640 ssh2_pkt_adduint32(0x8000UL); /* our window size */
2641 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
2643 crWaitUntilV(ispkt);
2644 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
2645 bombout(("Server refused to open a session"));
2647 /* FIXME: error data comes back in FAILURE packet */
2649 if (ssh2_pkt_getuint32() != mainchan->localid) {
2650 bombout(("Server's channel confirmation cited wrong channel"));
2653 mainchan->remoteid = ssh2_pkt_getuint32();
2654 mainchan->type = CHAN_MAINSESSION;
2655 mainchan->closes = 0;
2656 mainchan->v2.remwindow = ssh2_pkt_getuint32();
2657 mainchan->v2.remmaxpkt = ssh2_pkt_getuint32();
2658 mainchan->v2.outbuffer = NULL;
2659 mainchan->v2.outbuflen = mainchan->v2.outbufsize = 0;
2660 ssh_channels = newtree234(ssh_channelcmp);
2661 add234(ssh_channels, mainchan);
2662 logevent("Opened channel for session");
2665 * Potentially enable X11 forwarding.
2667 if (cfg.x11_forward) {
2668 char proto[20], data[64];
2669 logevent("Requesting X11 forwarding");
2670 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2671 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2672 ssh2_pkt_adduint32(mainchan->remoteid);
2673 ssh2_pkt_addstring("x11-req");
2674 ssh2_pkt_addbool(1); /* want reply */
2675 ssh2_pkt_addbool(0); /* many connections */
2676 ssh2_pkt_addstring(proto);
2677 ssh2_pkt_addstring(data);
2678 ssh2_pkt_adduint32(0); /* screen number */
2682 crWaitUntilV(ispkt);
2683 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2684 unsigned i = ssh2_pkt_getuint32();
2685 struct ssh_channel *c;
2686 c = find234(ssh_channels, &i, ssh_channelfind);
2688 continue; /* nonexistent channel */
2689 c->v2.remwindow += ssh2_pkt_getuint32();
2691 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2693 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2694 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2695 bombout(("Server got confused by X11 forwarding request"));
2698 logevent("X11 forwarding refused");
2700 logevent("X11 forwarding enabled");
2701 ssh_X11_fwd_enabled = TRUE;
2706 * Now allocate a pty for the session.
2709 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2710 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2711 ssh2_pkt_addstring("pty-req");
2712 ssh2_pkt_addbool(1); /* want reply */
2713 ssh2_pkt_addstring(cfg.termtype);
2714 ssh2_pkt_adduint32(cols);
2715 ssh2_pkt_adduint32(rows);
2716 ssh2_pkt_adduint32(0); /* pixel width */
2717 ssh2_pkt_adduint32(0); /* pixel height */
2718 ssh2_pkt_addstring_start();
2719 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
2721 ssh_state = SSH_STATE_INTERMED;
2724 crWaitUntilV(ispkt);
2725 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2726 unsigned i = ssh2_pkt_getuint32();
2727 struct ssh_channel *c;
2728 c = find234(ssh_channels, &i, ssh_channelfind);
2730 continue; /* nonexistent channel */
2731 c->v2.remwindow += ssh2_pkt_getuint32();
2733 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2735 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2736 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2737 bombout(("Server got confused by pty request"));
2740 c_write("Server refused to allocate pty\r\n", 32);
2742 logevent("Allocated pty");
2747 * Start a shell or a remote command.
2749 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2750 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2751 if (*cfg.remote_cmd) {
2752 ssh2_pkt_addstring("exec");
2753 ssh2_pkt_addbool(1); /* want reply */
2754 ssh2_pkt_addstring(cfg.remote_cmd);
2756 ssh2_pkt_addstring("shell");
2757 ssh2_pkt_addbool(1); /* want reply */
2761 crWaitUntilV(ispkt);
2762 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2763 unsigned i = ssh2_pkt_getuint32();
2764 struct ssh_channel *c;
2765 c = find234(ssh_channels, &i, ssh_channelfind);
2767 continue; /* nonexistent channel */
2768 c->v2.remwindow += ssh2_pkt_getuint32();
2770 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2771 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2772 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2773 bombout(("Server got confused by shell/command request"));
2776 bombout(("Server refused to start a shell/command"));
2779 logevent("Started a shell/command");
2782 ssh_state = SSH_STATE_SESSION;
2786 ssh_special(TS_EOF);
2794 static int try_send;
2798 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
2799 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
2802 unsigned i = ssh2_pkt_getuint32();
2803 struct ssh_channel *c;
2804 c = find234(ssh_channels, &i, ssh_channelfind);
2806 continue; /* nonexistent channel */
2807 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
2808 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
2809 continue; /* extended but not stderr */
2810 ssh2_pkt_getstring(&data, &length);
2813 case CHAN_MAINSESSION:
2814 from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
2818 x11_send(c->u.x11.s, data, length);
2822 * Enlarge the window again at the remote
2823 * side, just in case it ever runs down and
2824 * they fail to send us any more data.
2826 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2827 ssh2_pkt_adduint32(c->remoteid);
2828 ssh2_pkt_adduint32(length);
2831 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
2832 ssh_state = SSH_STATE_CLOSED;
2833 logevent("Received disconnect message");
2835 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2836 continue; /* exit status et al; ignore (FIXME?) */
2837 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
2838 unsigned i = ssh2_pkt_getuint32();
2839 struct ssh_channel *c;
2841 c = find234(ssh_channels, &i, ssh_channelfind);
2843 continue; /* nonexistent channel */
2845 if (c->type == CHAN_X11) {
2847 * Remote EOF on an X11 channel means we should
2848 * wrap up and close the channel ourselves.
2850 x11_close(c->u.x11.s);
2853 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
2854 unsigned i = ssh2_pkt_getuint32();
2855 struct ssh_channel *c;
2858 c = find234(ssh_channels, &i, ssh_channelfind);
2860 continue; /* nonexistent channel */
2861 if (c->closes == 0) {
2862 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2863 ssh2_pkt_adduint32(c->remoteid);
2866 /* Do pre-close processing on the channel. */
2868 case CHAN_MAINSESSION:
2869 break; /* nothing to see here, move along */
2873 del234(ssh_channels, c);
2874 sfree(c->v2.outbuffer);
2878 * See if that was the last channel left open.
2880 c = first234(ssh_channels, &e);
2882 logevent("All channels closed. Disconnecting");
2883 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
2884 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
2885 ssh2_pkt_addstring("All open channels closed");
2886 ssh2_pkt_addstring("en"); /* language tag */
2888 ssh_state = SSH_STATE_CLOSED;
2891 continue; /* remote sends close; ignore (FIXME) */
2892 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2893 unsigned i = ssh2_pkt_getuint32();
2894 struct ssh_channel *c;
2895 c = find234(ssh_channels, &i, ssh_channelfind);
2897 continue; /* nonexistent channel */
2898 mainchan->v2.remwindow += ssh2_pkt_getuint32();
2900 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
2904 struct ssh_channel *c;
2905 ssh2_pkt_getstring(&type, &typelen);
2906 c = smalloc(sizeof(struct ssh_channel));
2908 if (typelen == 3 && !memcmp(type, "x11", 3)) {
2909 if (!ssh_X11_fwd_enabled)
2910 error = "X11 forwarding is not enabled";
2911 else if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
2912 error = "Unable to open an X11 connection";
2917 error = "Unsupported channel type requested";
2920 c->remoteid = ssh2_pkt_getuint32();
2922 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
2923 ssh2_pkt_adduint32(c->remoteid);
2924 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
2925 ssh2_pkt_addstring(error);
2926 ssh2_pkt_addstring("en"); /* language tag */
2930 struct ssh_channel *d;
2934 for (i=1, d = first234(ssh_channels, &e); d;
2937 break; /* found a free number */
2942 c->v2.remwindow = ssh2_pkt_getuint32();
2943 c->v2.remmaxpkt = ssh2_pkt_getuint32();
2944 c->v2.outbuffer = NULL;
2945 c->v2.outbuflen = c->v2.outbufsize = 0;
2946 add234(ssh_channels, c);
2947 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
2948 ssh2_pkt_adduint32(c->remoteid);
2949 ssh2_pkt_adduint32(c->localid);
2950 ssh2_pkt_adduint32(0x8000UL); /* our window size */
2951 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
2955 bombout(("Strange packet received: type %d", pktin.type));
2960 * We have spare data. Add it to the channel buffer.
2962 ssh2_add_channel_data(mainchan, in, inlen);
2967 struct ssh_channel *c;
2969 * Try to send data on all channels if we can.
2971 for (c = first234(ssh_channels, &e); c; c = next234(&e))
2980 * Handle the top-level SSH2 protocol.
2982 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2984 if (do_ssh2_transport(in, inlen, ispkt) == 0)
2986 do_ssh2_authconn(in, inlen, ispkt);
2990 * Called to set up the connection.
2992 * Returns an error message, or NULL on success.
2994 static char *ssh_init (char *host, int port, char **realhost) {
2998 if(crypto_startup() == 0)
2999 return "Microsoft high encryption pack not installed!";
3004 p = connect_to_host(host, port, realhost);
3012 * Called to send data down the Telnet connection.
3014 static void ssh_send (char *buf, int len) {
3015 if (s == NULL || ssh_protocol == NULL)
3018 ssh_protocol(buf, len, 0);
3022 * Called to set the size of the window from SSH's POV.
3024 static void ssh_size(void) {
3025 switch (ssh_state) {
3026 case SSH_STATE_BEFORE_SIZE:
3027 case SSH_STATE_PREPACKET:
3028 case SSH_STATE_CLOSED:
3029 break; /* do nothing */
3030 case SSH_STATE_INTERMED:
3031 size_needed = TRUE; /* buffer for later */
3033 case SSH_STATE_SESSION:
3035 if (ssh_version == 1) {
3036 send_packet(SSH1_CMSG_WINDOW_SIZE,
3037 PKT_INT, rows, PKT_INT, cols,
3038 PKT_INT, 0, PKT_INT, 0, PKT_END);
3040 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3041 ssh2_pkt_adduint32(mainchan->remoteid);
3042 ssh2_pkt_addstring("window-change");
3043 ssh2_pkt_addbool(0);
3044 ssh2_pkt_adduint32(cols);
3045 ssh2_pkt_adduint32(rows);
3046 ssh2_pkt_adduint32(0);
3047 ssh2_pkt_adduint32(0);
3056 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3057 * can send an EOF and collect resulting output (e.g. `plink
3060 static void ssh_special (Telnet_Special code) {
3061 if (code == TS_EOF) {
3062 if (ssh_state != SSH_STATE_SESSION) {
3064 * Buffer the EOF in case we are pre-SESSION, so we can
3065 * send it as soon as we reach SESSION.
3071 if (ssh_version == 1) {
3072 send_packet(SSH1_CMSG_EOF, PKT_END);
3074 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
3075 ssh2_pkt_adduint32(mainchan->remoteid);
3078 logevent("Sent EOF message");
3079 } else if (code == TS_PING) {
3080 if (ssh_state == SSH_STATE_CLOSED || ssh_state == SSH_STATE_PREPACKET)
3082 if (ssh_version == 1) {
3083 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
3085 ssh2_pkt_init(SSH2_MSG_IGNORE);
3086 ssh2_pkt_addstring_start();
3094 static Socket ssh_socket(void) { return s; }
3096 static int ssh_sendok(void) { return ssh_send_ok; }
3098 Backend ssh_backend = {