18 #define logevent(s) { logevent(s); \
19 if (!(flags & FLAG_CONNECTION) && (flags & FLAG_VERBOSE)) \
20 fprintf(stderr, "%s\n", s); }
22 #define SSH1_MSG_DISCONNECT 1
23 #define SSH1_SMSG_PUBLIC_KEY 2
24 #define SSH1_CMSG_SESSION_KEY 3
25 #define SSH1_CMSG_USER 4
26 #define SSH1_CMSG_AUTH_RSA 6
27 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7
28 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8
29 #define SSH1_CMSG_AUTH_PASSWORD 9
30 #define SSH1_CMSG_REQUEST_PTY 10
31 #define SSH1_CMSG_WINDOW_SIZE 11
32 #define SSH1_CMSG_EXEC_SHELL 12
33 #define SSH1_CMSG_EXEC_CMD 13
34 #define SSH1_SMSG_SUCCESS 14
35 #define SSH1_SMSG_FAILURE 15
36 #define SSH1_CMSG_STDIN_DATA 16
37 #define SSH1_SMSG_STDOUT_DATA 17
38 #define SSH1_SMSG_STDERR_DATA 18
39 #define SSH1_CMSG_EOF 19
40 #define SSH1_SMSG_EXIT_STATUS 20
41 #define SSH1_CMSG_EXIT_CONFIRMATION 33
42 #define SSH1_MSG_IGNORE 32
43 #define SSH1_MSG_DEBUG 36
44 #define SSH1_CMSG_AUTH_TIS 39
45 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40
46 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41
48 #define SSH1_AUTH_TIS 5
50 #define SSH2_MSG_DISCONNECT 1
51 #define SSH2_MSG_IGNORE 2
52 #define SSH2_MSG_UNIMPLEMENTED 3
53 #define SSH2_MSG_DEBUG 4
54 #define SSH2_MSG_SERVICE_REQUEST 5
55 #define SSH2_MSG_SERVICE_ACCEPT 6
56 #define SSH2_MSG_KEXINIT 20
57 #define SSH2_MSG_NEWKEYS 21
58 #define SSH2_MSG_KEXDH_INIT 30
59 #define SSH2_MSG_KEXDH_REPLY 31
60 #define SSH2_MSG_USERAUTH_REQUEST 50
61 #define SSH2_MSG_USERAUTH_FAILURE 51
62 #define SSH2_MSG_USERAUTH_SUCCESS 52
63 #define SSH2_MSG_USERAUTH_BANNER 53
64 #define SSH2_MSG_USERAUTH_PK_OK 60
65 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60
66 #define SSH2_MSG_GLOBAL_REQUEST 80
67 #define SSH2_MSG_REQUEST_SUCCESS 81
68 #define SSH2_MSG_REQUEST_FAILURE 82
69 #define SSH2_MSG_CHANNEL_OPEN 90
70 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91
71 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92
72 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93
73 #define SSH2_MSG_CHANNEL_DATA 94
74 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95
75 #define SSH2_MSG_CHANNEL_EOF 96
76 #define SSH2_MSG_CHANNEL_CLOSE 97
77 #define SSH2_MSG_CHANNEL_REQUEST 98
78 #define SSH2_MSG_CHANNEL_SUCCESS 99
79 #define SSH2_MSG_CHANNEL_FAILURE 100
81 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1
82 #define SSH2_OPEN_CONNECT_FAILED 2
83 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3
84 #define SSH2_OPEN_RESOURCE_SHORTAGE 4
85 #define SSH2_EXTENDED_DATA_STDERR 1
87 #define GET_32BIT(cp) \
88 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
89 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
90 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
91 ((unsigned long)(unsigned char)(cp)[3]))
93 #define PUT_32BIT(cp, value) { \
94 (cp)[0] = (unsigned char)((value) >> 24); \
95 (cp)[1] = (unsigned char)((value) >> 16); \
96 (cp)[2] = (unsigned char)((value) >> 8); \
97 (cp)[3] = (unsigned char)(value); }
99 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
101 /* Coroutine mechanics for the sillier bits of the code */
102 #define crBegin1 static int crLine = 0;
103 #define crBegin2 switch(crLine) { case 0:;
104 #define crBegin crBegin1; crBegin2;
105 #define crFinish(z) } crLine = 0; return (z)
106 #define crFinishV } crLine = 0; return
107 #define crReturn(z) \
109 crLine=__LINE__; return (z); case __LINE__:;\
113 crLine=__LINE__; return; case __LINE__:;\
115 #define crStop(z) do{ crLine = 0; return (z); }while(0)
116 #define crStopV do{ crLine = 0; return; }while(0)
117 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
118 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
120 extern struct ssh_cipher ssh_3des;
121 extern struct ssh_cipher ssh_3des_ssh2;
122 extern struct ssh_cipher ssh_des;
123 extern struct ssh_cipher ssh_blowfish;
125 /* for ssh 2; we miss out single-DES because it isn't supported */
126 struct ssh_cipher *ciphers[] = { &ssh_3des_ssh2, &ssh_blowfish };
128 extern struct ssh_kex ssh_diffiehellman;
129 struct ssh_kex *kex_algs[] = { &ssh_diffiehellman };
131 extern struct ssh_hostkey ssh_dss;
132 struct ssh_hostkey *hostkey_algs[] = { &ssh_dss };
134 extern struct ssh_mac ssh_sha1;
138 static void nullmac_key(unsigned char *key) { }
139 static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
140 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
141 struct ssh_mac ssh_mac_none = {
142 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
144 struct ssh_mac *macs[] = { &ssh_sha1, &ssh_mac_none };
146 struct ssh_compress ssh_comp_none = {
149 struct ssh_compress *compressions[] = { &ssh_comp_none };
151 static SOCKET s = INVALID_SOCKET;
153 static unsigned char session_key[32];
154 static struct ssh_cipher *cipher = NULL;
155 static struct ssh_cipher *cscipher = NULL;
156 static struct ssh_cipher *sccipher = NULL;
157 static struct ssh_mac *csmac = NULL;
158 static struct ssh_mac *scmac = NULL;
159 static struct ssh_compress *cscomp = NULL;
160 static struct ssh_compress *sccomp = NULL;
161 static struct ssh_kex *kex = NULL;
162 static struct ssh_hostkey *hostkey = NULL;
163 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
165 static char *savedhost;
166 static int ssh_send_ok;
169 SSH_STATE_BEFORE_SIZE,
173 } ssh_state = SSH_STATE_BEFORE_SIZE;
175 static int size_needed = FALSE;
177 static void s_write (char *buf, int len) {
179 int i = send (s, buf, len, 0);
182 fatalbox("Lost connection while sending");
188 static int s_read (char *buf, int len) {
191 int i = recv (s, buf, len, 0);
194 len -= i, buf += i, ret += i;
201 static void c_write (char *buf, int len) {
202 if (!(flags & FLAG_CONNECTION)) {
204 for (i = 0; i < len; i++)
206 fputc(buf[i], stderr);
222 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
223 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
225 static int ssh_version;
226 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
227 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
228 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
229 static void ssh_size(void);
231 static int (*s_rdpkt)(unsigned char **data, int *datalen);
234 * Collect incoming data in the incoming packet buffer.
235 * Decipher and verify the packet when it is completely read.
236 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
237 * Update the *data and *datalen variables.
238 * Return the additional nr of bytes needed, or 0 when
239 * a complete packet is available.
241 static int ssh1_rdpkt(unsigned char **data, int *datalen)
243 static long len, pad, biglen, to_read;
244 static unsigned long realcrc, gotcrc;
245 static unsigned char *p;
255 for (i = len = 0; i < 4; i++) {
256 while ((*datalen) == 0)
258 len = (len << 8) + **data;
259 (*data)++, (*datalen)--;
263 if (len == 0x52656d6f) { /* "Remo"te server has closed ... */
264 len = 0x300; /* big enough to carry to end */
270 pktin.length = len - 5;
272 if (pktin.maxlen < biglen) {
273 pktin.maxlen = biglen;
274 pktin.data = (pktin.data == NULL ? malloc(biglen+APIEXTRA) :
275 realloc(pktin.data, biglen+APIEXTRA));
277 fatalbox("Out of memory");
282 while (to_read > 0) {
285 while ((*datalen) == 0)
287 if (chunk > (*datalen))
289 memcpy(p, *data, chunk);
297 cipher->decrypt(pktin.data, biglen);
299 pktin.type = pktin.data[pad];
300 pktin.body = pktin.data + pad + 1;
302 realcrc = crc32(pktin.data, biglen-4);
303 gotcrc = GET_32BIT(pktin.data+biglen-4);
304 if (gotcrc != realcrc) {
305 fatalbox("Incorrect CRC received on packet");
308 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
309 pktin.type == SSH1_SMSG_STDERR_DATA ||
310 pktin.type == SSH1_MSG_DEBUG ||
311 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE) {
312 long strlen = GET_32BIT(pktin.body);
313 if (strlen + 4 != pktin.length)
314 fatalbox("Received data packet with bogus string length");
317 if (pktin.type == SSH1_MSG_DEBUG) {
318 /* log debug message */
320 int strlen = GET_32BIT(pktin.body);
321 strcpy(buf, "Remote: ");
322 if (strlen > 70) strlen = 70;
323 memcpy(buf+8, pktin.body+4, strlen);
324 buf[8+strlen] = '\0';
327 } else if (pktin.type == SSH1_MSG_IGNORE) {
335 static int ssh2_rdpkt(unsigned char **data, int *datalen)
337 static long len, pad, payload, packetlen, maclen;
339 static int cipherblk;
340 static unsigned long incoming_sequence = 0;
350 cipherblk = cipher->blksize;
356 if (pktin.maxlen < cipherblk) {
357 pktin.maxlen = cipherblk;
358 pktin.data = (pktin.data == NULL ? malloc(cipherblk+APIEXTRA) :
359 realloc(pktin.data, cipherblk+APIEXTRA));
361 fatalbox("Out of memory");
365 * Acquire and decrypt the first block of the packet. This will
366 * contain the length and padding details.
368 for (i = len = 0; i < cipherblk; i++) {
369 while ((*datalen) == 0)
370 crReturn(cipherblk-i);
371 pktin.data[i] = *(*data)++;
375 if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
380 sccipher->decrypt(pktin.data, cipherblk);
383 * Now get the length and padding figures.
385 len = GET_32BIT(pktin.data);
389 * This enables us to deduce the payload length.
391 payload = len - pad - 1;
393 pktin.length = payload + 5;
396 * So now we can work out the total packet length.
399 maclen = scmac ? scmac->len : 0;
402 * Adjust memory allocation if packet is too big.
404 if (pktin.maxlen < packetlen) {
405 pktin.maxlen = packetlen;
406 pktin.data = (pktin.data == NULL ? malloc(packetlen+APIEXTRA) :
407 realloc(pktin.data, packetlen+APIEXTRA));
409 fatalbox("Out of memory");
413 * Read and decrypt the remainder of the packet.
415 for (i = cipherblk; i < packetlen + maclen; i++) {
416 while ((*datalen) == 0)
417 crReturn(packetlen + maclen - i);
418 pktin.data[i] = *(*data)++;
421 /* Decrypt everything _except_ the MAC. */
423 sccipher->decrypt(pktin.data + cipherblk, packetlen - cipherblk);
426 debug(("Got packet len=%d pad=%d\r\n", len, pad));
427 for (i = 0; i < packetlen; i++)
428 debug((" %02x", (unsigned char)pktin.data[i]));
435 if (scmac && !scmac->verify(pktin.data, len+4, incoming_sequence))
436 fatalbox("Incorrect MAC received on packet");
437 incoming_sequence++; /* whether or not we MACed */
440 pktin.type = pktin.data[5];
442 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
443 goto next_packet; /* FIXME: print DEBUG message */
448 static void ssh_gotdata(unsigned char *data, int datalen)
450 while (datalen > 0) {
451 if ( s_rdpkt(&data, &datalen) == 0 ) {
452 ssh_protocol(NULL, 0, 1);
453 if (ssh_state == SSH_STATE_CLOSED) {
461 static void s_wrpkt_start(int type, int len) {
464 len += 5; /* type and CRC */
468 pktout.length = len-5;
469 if (pktout.maxlen < biglen) {
470 pktout.maxlen = biglen;
472 /* Allocate enough buffer space for extra block
473 * for MS CryptEncrypt() */
474 pktout.data = (pktout.data == NULL ? malloc(biglen+12) :
475 realloc(pktout.data, biglen+12));
477 pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
478 realloc(pktout.data, biglen+4));
481 fatalbox("Out of memory");
485 pktout.body = pktout.data+4+pad+1;
488 static void s_wrpkt(void) {
489 int pad, len, biglen, i;
492 len = pktout.length + 5; /* type and CRC */
496 pktout.body[-1] = pktout.type;
497 for (i=0; i<pad; i++)
498 pktout.data[i+4] = random_byte();
499 crc = crc32(pktout.data+4, biglen-4);
500 PUT_32BIT(pktout.data+biglen, crc);
501 PUT_32BIT(pktout.data, len);
504 cipher->encrypt(pktout.data+4, biglen);
506 s_write(pktout.data, biglen+4);
510 * Construct a packet with the specified contents and
511 * send it to the server.
513 static void send_packet(int pkttype, ...)
516 unsigned char *p, *argp, argchar;
517 unsigned long argint;
518 int pktlen, argtype, arglen;
523 va_start(args, pkttype);
524 while ((argtype = va_arg(args, int)) != PKT_END) {
527 (void) va_arg(args, int);
531 (void) va_arg(args, char);
535 (void) va_arg(args, unsigned char *);
536 arglen = va_arg(args, int);
540 argp = va_arg(args, unsigned char *);
541 arglen = strlen(argp);
542 pktlen += 4 + arglen;
545 bn = va_arg(args, Bignum);
547 while ( i > 0 && (bn[i/16+1] >> (i%16)) == 0 )
549 pktlen += 2 + (i+7)/8;
557 s_wrpkt_start(pkttype, pktlen);
560 va_start(args, pkttype);
561 while ((argtype = va_arg(args, int)) != PKT_END) {
564 argint = va_arg(args, int);
565 PUT_32BIT(p, argint);
569 argchar = va_arg(args, unsigned char);
574 argp = va_arg(args, unsigned char *);
575 arglen = va_arg(args, int);
576 memcpy(p, argp, arglen);
580 argp = va_arg(args, unsigned char *);
581 arglen = strlen(argp);
582 PUT_32BIT(p, arglen);
583 memcpy(p + 4, argp, arglen);
587 bn = va_arg(args, Bignum);
589 while ( i > 0 && (bn[i/16+1] >> (i%16)) == 0 )
591 *p++ = (i >> 8) & 0xFF;
596 *p++ = bn[i/2+1] >> 8;
598 *p++ = bn[i/2+1] & 0xFF;
610 * Connect to specified host and port.
611 * Returns an error message, or NULL on success.
612 * Also places the canonical host name into `realhost'.
614 static char *connect_to_host(char *host, int port, char **realhost)
624 savedhost = malloc(1+strlen(host));
626 fatalbox("Out of memory");
627 strcpy(savedhost, host);
630 port = 22; /* default ssh port */
642 if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
643 if ( (h = gethostbyname(host)) == NULL)
644 switch (WSAGetLastError()) {
645 case WSAENETDOWN: return "Network is down";
646 case WSAHOST_NOT_FOUND: case WSANO_DATA:
647 return "Host does not exist";
648 case WSATRY_AGAIN: return "Host not found";
649 default: return "gethostbyname: unknown error";
651 memcpy (&a, h->h_addr, sizeof(a));
652 *realhost = h->h_name;
663 s = socket(AF_INET, SOCK_STREAM, 0);
664 if (s == INVALID_SOCKET)
665 switch (WSAGetLastError()) {
666 case WSAENETDOWN: return "Network is down";
667 case WSAEAFNOSUPPORT: return "TCP/IP support not present";
668 default: return "socket(): unknown error";
672 * Bind to local address.
674 addr.sin_family = AF_INET;
675 addr.sin_addr.s_addr = htonl(INADDR_ANY);
676 addr.sin_port = htons(0);
677 if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
678 switch (WSAGetLastError()) {
679 case WSAENETDOWN: return "Network is down";
680 default: return "bind(): unknown error";
684 * Connect to remote address.
686 addr.sin_addr.s_addr = htonl(a);
687 addr.sin_port = htons((short)port);
688 if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
689 switch (WSAGetLastError()) {
690 case WSAENETDOWN: return "Network is down";
691 case WSAECONNREFUSED: return "Connection refused";
692 case WSAENETUNREACH: return "Network is unreachable";
693 case WSAEHOSTUNREACH: return "No route to host";
694 default: return "connect(): unknown error";
698 send(s, "connect ", 8, 0);
699 send(s, FWhost, strlen(FWhost), 0);
702 sprintf(buf, " %d\n", FWport);
703 send (s, buf, strlen(buf), 0);
710 static int ssh_versioncmp(char *a, char *b) {
712 unsigned long av, bv;
714 av = strtoul(a, &ae, 10);
715 bv = strtoul(b, &be, 10);
716 if (av != bv) return (av < bv ? -1 : +1);
717 if (*ae == '.') ae++;
718 if (*be == '.') be++;
719 av = strtoul(ae, &ae, 10);
720 bv = strtoul(be, &be, 10);
721 if (av != bv) return (av < bv ? -1 : +1);
727 * Utility routine for putting an SSH-protocol `string' into a SHA
731 void sha_string(SHA_State *s, void *str, int len) {
732 unsigned char lenblk[4];
733 PUT_32BIT(lenblk, len);
734 SHA_Bytes(s, lenblk, 4);
735 SHA_Bytes(s, str, len);
739 * SSH2 packet construction functions.
741 void ssh2_pkt_adddata(void *data, int len) {
742 pktout.length += len;
743 if (pktout.maxlen < pktout.length) {
744 pktout.maxlen = pktout.length + 256;
745 pktout.data = (pktout.data == NULL ? malloc(pktout.maxlen+APIEXTRA) :
746 realloc(pktout.data, pktout.maxlen+APIEXTRA));
748 fatalbox("Out of memory");
750 memcpy(pktout.data+pktout.length-len, data, len);
752 void ssh2_pkt_addbyte(unsigned char byte) {
753 ssh2_pkt_adddata(&byte, 1);
755 void ssh2_pkt_init(int pkt_type) {
757 ssh2_pkt_addbyte((unsigned char)pkt_type);
759 void ssh2_pkt_addbool(unsigned char value) {
760 ssh2_pkt_adddata(&value, 1);
762 void ssh2_pkt_adduint32(unsigned long value) {
765 ssh2_pkt_adddata(x, 4);
767 void ssh2_pkt_addstring_start(void) {
768 ssh2_pkt_adduint32(0);
769 pktout.savedpos = pktout.length;
771 void ssh2_pkt_addstring_str(char *data) {
772 ssh2_pkt_adddata(data, strlen(data));
773 PUT_32BIT(pktout.data + pktout.savedpos - 4,
774 pktout.length - pktout.savedpos);
776 void ssh2_pkt_addstring_data(char *data, int len) {
777 ssh2_pkt_adddata(data, len);
778 PUT_32BIT(pktout.data + pktout.savedpos - 4,
779 pktout.length - pktout.savedpos);
781 void ssh2_pkt_addstring(char *data) {
782 ssh2_pkt_addstring_start();
783 ssh2_pkt_addstring_str(data);
785 char *ssh2_mpint_fmt(Bignum b, int *len) {
788 p = malloc(n * 2 + 1);
790 fatalbox("out of memory");
792 for (i = 0; i < n; i++) {
793 p[i*2+1] = (b[n-i] >> 8) & 0xFF;
794 p[i*2+2] = (b[n-i] ) & 0xFF;
797 while (p[i] == 0 && (p[i+1] & 0x80) == 0)
799 memmove(p, p+i, n*2+1-i);
803 void ssh2_pkt_addmp(Bignum b) {
806 p = ssh2_mpint_fmt(b, &len);
807 ssh2_pkt_addstring_start();
808 ssh2_pkt_addstring_data(p, len);
811 void ssh2_pkt_send(void) {
812 int cipherblk, maclen, padding, i;
813 static unsigned long outgoing_sequence = 0;
816 * Add padding. At least four bytes, and must also bring total
817 * length (minus MAC) up to a multiple of the block size.
819 cipherblk = cipher ? cipher->blksize : 8; /* block size */
820 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
822 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
823 pktout.data[4] = padding;
824 for (i = 0; i < padding; i++)
825 pktout.data[pktout.length + i] = random_byte();
826 PUT_32BIT(pktout.data, pktout.length + padding - 4);
828 csmac->generate(pktout.data, pktout.length + padding,
830 outgoing_sequence++; /* whether or not we MACed */
833 debug(("Sending packet len=%d\r\n", pktout.length+padding));
834 for (i = 0; i < pktout.length+padding; i++)
835 debug((" %02x", (unsigned char)pktout.data[i]));
840 cscipher->encrypt(pktout.data, pktout.length + padding);
841 maclen = csmac ? csmac->len : 0;
843 s_write(pktout.data, pktout.length + padding + maclen);
847 void bndebug(char *string, Bignum b) {
850 p = ssh2_mpint_fmt(b, &len);
851 debug(("%s", string));
852 for (i = 0; i < len; i++)
853 debug((" %02x", p[i]));
859 void sha_mpint(SHA_State *s, Bignum b) {
862 p = ssh2_mpint_fmt(b, &len);
863 sha_string(s, p, len);
868 * SSH2 packet decode functions.
870 unsigned long ssh2_pkt_getuint32(void) {
872 if (pktin.length - pktin.savedpos < 4)
873 return 0; /* arrgh, no way to decline (FIXME?) */
874 value = GET_32BIT(pktin.data+pktin.savedpos);
878 void ssh2_pkt_getstring(char **p, int *length) {
880 if (pktin.length - pktin.savedpos < 4)
882 *length = GET_32BIT(pktin.data+pktin.savedpos);
884 if (pktin.length - pktin.savedpos < *length)
886 *p = pktin.data+pktin.savedpos;
887 pktin.savedpos += *length;
889 Bignum ssh2_pkt_getmp(void) {
894 ssh2_pkt_getstring(&p, &length);
898 fatalbox("internal error: Can't handle negative mpints");
899 b = newbn((length+1)/2);
900 for (i = 0; i < length; i++) {
903 b[j/2+1] |= ((unsigned char)p[i]) << 8;
905 b[j/2+1] |= ((unsigned char)p[i]);
910 static int do_ssh_init(void) {
914 char vlog[sizeof(vstring)+20];
919 while (s_read(&c, 1) == 1) {
920 if (c == 'S' && i < 2) i++;
921 else if (c == 'S' && i == 2) i = 2;
922 else if (c == 'H' && i == 2) break;
926 if (s_read(&c,1) != 1 || c != 'S') return 0;
927 if (s_read(&c,1) != 1 || c != 'S') return 0;
928 if (s_read(&c,1) != 1 || c != 'H') return 0;
930 strcpy(vstring, "SSH-");
932 if (s_read(&c,1) != 1 || c != '-') return 0;
935 if (s_read(&c,1) != 1)
937 if (vsp < vstring+sizeof(vstring)-1)
943 } else if (i < sizeof(version)-1)
951 sprintf(vlog, "Server version: %s", vstring);
952 vlog[strcspn(vlog, "\r\n")] = '\0';
956 * Server version "1.99" means we can choose whether we use v1
957 * or v2 protocol. Choice is based on cfg.sshprot.
959 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
961 * This is a v2 server. Begin v2 protocol.
963 char *verstring = "SSH-2.0-PuTTY";
966 * Hash our version string and their version string.
968 sha_string(&exhash, verstring, strlen(verstring));
969 sha_string(&exhash, vstring, strcspn(vstring, "\r\n"));
970 sprintf(vstring, "%s\n", verstring);
971 sprintf(vlog, "We claim version: %s", verstring);
973 logevent("Using SSH protocol version 2");
974 s_write(vstring, strlen(vstring));
975 ssh_protocol = ssh2_protocol;
977 s_rdpkt = ssh2_rdpkt;
980 * This is a v1 server. Begin v1 protocol.
982 sprintf(vstring, "SSH-%s-PuTTY\n",
983 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
984 sprintf(vlog, "We claim version: %s", vstring);
985 vlog[strcspn(vlog, "\r\n")] = '\0';
987 logevent("Using SSH protocol version 1");
988 s_write(vstring, strlen(vstring));
989 ssh_protocol = ssh1_protocol;
991 s_rdpkt = ssh1_rdpkt;
998 * Handle the key exchange and user authentication phases.
1000 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1003 unsigned char *rsabuf, *keystr1, *keystr2;
1004 unsigned char cookie[8];
1005 struct RSAKey servkey, hostkey;
1006 struct MD5Context md5c;
1007 static unsigned long supported_ciphers_mask, supported_auths_mask;
1008 static int tried_publickey;
1009 static unsigned char session_id[16];
1014 if (!ispkt) crWaitUntil(ispkt);
1016 if (pktin.type != SSH1_SMSG_PUBLIC_KEY)
1017 fatalbox("Public key packet not received");
1019 logevent("Received public keys");
1021 memcpy(cookie, pktin.body, 8);
1023 i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1024 j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1027 * Hash the host key and print the hash in the log box. Just as
1028 * a last resort in case the registry's host key checking is
1029 * compromised, we'll allow the user some ability to verify
1033 MD5Update(&md5c, keystr2, hostkey.bytes);
1034 MD5Final(session_id, &md5c);
1038 logevent("Host key MD5 is:");
1039 strcpy(logmsg, " ");
1040 for (i = 0; i < 16; i++)
1041 sprintf(logmsg+strlen(logmsg), "%02x", session_id[i]);
1045 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1046 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1049 MD5Update(&md5c, keystr2, hostkey.bytes);
1050 MD5Update(&md5c, keystr1, servkey.bytes);
1051 MD5Update(&md5c, pktin.body, 8);
1052 MD5Final(session_id, &md5c);
1054 for (i=0; i<32; i++)
1055 session_key[i] = random_byte();
1057 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1059 rsabuf = malloc(len);
1061 fatalbox("Out of memory");
1064 * Verify the host key.
1068 * First format the key into a string.
1070 int len = rsastr_len(&hostkey);
1071 char *keystr = malloc(len);
1073 fatalbox("Out of memory");
1074 rsastr_fmt(keystr, &hostkey);
1075 verify_ssh_host_key(savedhost, keystr);
1079 for (i=0; i<32; i++) {
1080 rsabuf[i] = session_key[i];
1082 rsabuf[i] ^= session_id[i];
1085 if (hostkey.bytes > servkey.bytes) {
1086 rsaencrypt(rsabuf, 32, &servkey);
1087 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1089 rsaencrypt(rsabuf, 32, &hostkey);
1090 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1093 logevent("Encrypted session key");
1095 cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
1096 cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES :
1098 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1099 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1100 cipher_type = SSH_CIPHER_3DES;
1102 switch (cipher_type) {
1103 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1104 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1105 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1108 send_packet(SSH1_CMSG_SESSION_KEY,
1109 PKT_CHAR, cipher_type,
1110 PKT_DATA, cookie, 8,
1111 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1112 PKT_DATA, rsabuf, len,
1116 logevent("Trying to enable encryption...");
1120 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
1121 cipher_type == SSH_CIPHER_DES ? &ssh_des :
1123 cipher->sesskey(session_key);
1127 if (pktin.type != SSH1_SMSG_SUCCESS)
1128 fatalbox("Encryption not successfully enabled");
1130 logevent("Successfully started encryption");
1134 static char username[100];
1137 if (!(flags & FLAG_CONNECTION) && !*cfg.username) {
1138 c_write("login as: ", 10);
1140 crWaitUntil(!ispkt);
1141 while (inlen--) switch (c = *in++) {
1148 c_write("\b \b", 3);
1154 c_write("\b \b", 3);
1163 if (((c >= ' ' && c <= '~') ||
1164 ((unsigned char)c >= 160)) && pos < 40) {
1165 username[pos++] = c;
1172 username[strcspn(username, "\n\r")] = '\0';
1175 strncpy(username, cfg.username, 99);
1176 username[99] = '\0';
1177 if (flags & FLAG_VERBOSE) {
1178 sprintf(stuff, "Sent username \"%s\".\r\n", username);
1179 c_write(stuff, strlen(stuff));
1183 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1185 char userlog[20+sizeof(username)];
1186 sprintf(userlog, "Sent username \"%s\"", username);
1193 tried_publickey = 0;
1195 while (pktin.type == SSH1_SMSG_FAILURE) {
1196 static char password[100];
1199 static int pwpkt_type;
1201 * Show password prompt, having first obtained it via a TIS
1202 * exchange if we're doing TIS authentication.
1204 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1205 if (*cfg.keyfile && !tried_publickey)
1206 pwpkt_type = SSH1_CMSG_AUTH_RSA;
1208 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD && !FLAG_WINDOWED) {
1210 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
1211 if (!ssh_get_password(prompt, password, sizeof(password))) {
1213 * get_password failed to get a password (for
1214 * example because one was supplied on the command
1215 * line which has already failed to work).
1218 logevent("No more passwords to try");
1219 ssh_state = SSH_STATE_CLOSED;
1224 if (pktin.type == SSH1_SMSG_FAILURE &&
1226 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1227 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1228 logevent("Requested TIS authentication");
1229 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1231 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1232 logevent("TIS authentication declined");
1233 c_write("TIS authentication refused.\r\n", 29);
1235 int challengelen = ((pktin.body[0] << 24) |
1236 (pktin.body[1] << 16) |
1237 (pktin.body[2] << 8) |
1239 logevent("Received TIS challenge");
1240 c_write(pktin.body+4, challengelen);
1243 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD)
1244 c_write("password: ", 10);
1245 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1246 if (flags & FLAG_VERBOSE)
1247 c_write("Trying public key authentication.\r\n", 35);
1248 if (!rsakey_encrypted(cfg.keyfile)) {
1249 if (flags & FLAG_VERBOSE)
1250 c_write("No passphrase required.\r\n", 25);
1253 c_write("passphrase: ", 12);
1258 crWaitUntil(!ispkt);
1259 while (inlen--) switch (c = *in++) {
1276 if (((c >= ' ' && c <= '~') ||
1277 ((unsigned char)c >= 160)) && pos < sizeof(password))
1278 password[pos++] = c;
1287 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1289 * Try public key authentication with the specified
1292 static struct RSAKey pubkey;
1293 static Bignum challenge, response;
1295 static unsigned char buffer[32];
1297 tried_publickey = 1;
1298 i = loadrsakey(cfg.keyfile, &pubkey, password);
1300 c_write("Couldn't load public key from ", 30);
1301 c_write(cfg.keyfile, strlen(cfg.keyfile));
1302 c_write(".\r\n", 3);
1303 continue; /* go and try password */
1306 c_write("Wrong passphrase.\r\n", 19);
1307 tried_publickey = 0;
1308 continue; /* try again */
1312 * Send a public key attempt.
1314 send_packet(SSH1_CMSG_AUTH_RSA,
1315 PKT_BIGNUM, pubkey.modulus, PKT_END);
1318 if (pktin.type == SSH1_SMSG_FAILURE) {
1319 if (flags & FLAG_VERBOSE)
1320 c_write("Server refused our public key.\r\n", 32);
1321 continue; /* go and try password */
1323 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE)
1324 fatalbox("Bizarre response to offer of public key");
1325 ssh1_read_bignum(pktin.body, &challenge);
1326 response = rsadecrypt(challenge, &pubkey);
1327 freebn(pubkey.private_exponent); /* burn the evidence */
1329 for (i = 0; i < 32; i += 2) {
1330 buffer[i] = response[16-i/2] >> 8;
1331 buffer[i+1] = response[16-i/2] & 0xFF;
1335 MD5Update(&md5c, buffer, 32);
1336 MD5Update(&md5c, session_id, 16);
1337 MD5Final(buffer, &md5c);
1339 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1340 PKT_DATA, buffer, 16, PKT_END);
1343 if (pktin.type == SSH1_SMSG_FAILURE) {
1344 if (flags & FLAG_VERBOSE)
1345 c_write("Failed to authenticate with our public key.\r\n",
1347 continue; /* go and try password */
1348 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1349 fatalbox("Bizarre response to RSA authentication response");
1352 break; /* we're through! */
1354 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1356 logevent("Sent password");
1357 memset(password, 0, strlen(password));
1359 if (pktin.type == SSH1_SMSG_FAILURE) {
1360 if (flags & FLAG_VERBOSE)
1361 c_write("Access denied\r\n", 15);
1362 logevent("Authentication refused");
1363 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1364 logevent("Received disconnect request");
1365 ssh_state = SSH_STATE_CLOSED;
1367 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1368 fatalbox("Strange packet received, type %d", pktin.type);
1372 logevent("Authentication successful");
1377 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1382 while (!do_ssh1_login(in, inlen, ispkt)) {
1385 if (ssh_state == SSH_STATE_CLOSED)
1389 send_packet(SSH1_CMSG_REQUEST_PTY,
1390 PKT_STR, cfg.termtype,
1391 PKT_INT, rows, PKT_INT, cols,
1392 PKT_INT, 0, PKT_INT, 0,
1395 ssh_state = SSH_STATE_INTERMED;
1396 do { crReturnV; } while (!ispkt);
1397 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1398 fatalbox("Protocol confusion");
1399 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1400 c_write("Server refused to allocate pty\r\n", 32);
1402 logevent("Allocated pty");
1405 if (*cfg.remote_cmd)
1406 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1408 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1409 logevent("Started session");
1411 ssh_state = SSH_STATE_SESSION;
1419 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1420 pktin.type == SSH1_SMSG_STDERR_DATA) {
1421 long len = GET_32BIT(pktin.body);
1422 c_write(pktin.body+4, len);
1423 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1424 ssh_state = SSH_STATE_CLOSED;
1425 logevent("Received disconnect request");
1426 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
1427 /* may be from EXEC_SHELL on some servers */
1428 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1429 /* may be from EXEC_SHELL on some servers
1430 * if no pty is available or in other odd cases. Ignore */
1431 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1432 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
1434 fatalbox("Strange packet received: type %d", pktin.type);
1437 send_packet(SSH1_CMSG_STDIN_DATA,
1438 PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
1446 * Utility routine for decoding comma-separated strings in KEXINIT.
1448 int in_commasep_string(char *needle, char *haystack, int haylen) {
1449 int needlen = strlen(needle);
1452 * Is it at the start of the string?
1454 if (haylen >= needlen && /* haystack is long enough */
1455 !memcmp(needle, haystack, needlen) && /* initial match */
1456 (haylen == needlen || haystack[needlen] == ',')
1457 /* either , or EOS follows */
1461 * If not, search for the next comma and resume after that.
1462 * If no comma found, terminate.
1464 while (haylen > 0 && *haystack != ',')
1465 haylen--, haystack++;
1468 haylen--, haystack++; /* skip over comma itself */
1473 * SSH2 key creation method.
1475 void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1477 /* First 20 bytes. */
1480 SHA_Bytes(&s, H, 20);
1481 SHA_Bytes(&s, &chr, 1);
1482 SHA_Bytes(&s, H, 20);
1483 SHA_Final(&s, keyspace);
1484 /* Next 20 bytes. */
1487 SHA_Bytes(&s, H, 20);
1488 SHA_Bytes(&s, keyspace, 20);
1489 SHA_Final(&s, keyspace+20);
1493 * Handle the SSH2 transport layer.
1495 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
1499 static Bignum e, f, K;
1500 static struct ssh_cipher *cscipher_tobe = NULL;
1501 static struct ssh_cipher *sccipher_tobe = NULL;
1502 static struct ssh_mac *csmac_tobe = NULL;
1503 static struct ssh_mac *scmac_tobe = NULL;
1504 static struct ssh_compress *cscomp_tobe = NULL;
1505 static struct ssh_compress *sccomp_tobe = NULL;
1506 static char *hostkeydata, *sigdata, *keystr;
1507 static int hostkeylen, siglen;
1508 static unsigned char exchange_hash[20];
1509 static unsigned char keyspace[40];
1516 * Construct and send our key exchange packet.
1518 ssh2_pkt_init(SSH2_MSG_KEXINIT);
1519 for (i = 0; i < 16; i++)
1520 ssh2_pkt_addbyte((unsigned char)random_byte());
1521 /* List key exchange algorithms. */
1522 ssh2_pkt_addstring_start();
1523 for (i = 0; i < lenof(kex_algs); i++) {
1524 ssh2_pkt_addstring_str(kex_algs[i]->name);
1525 if (i < lenof(kex_algs)-1)
1526 ssh2_pkt_addstring_str(",");
1528 /* List server host key algorithms. */
1529 ssh2_pkt_addstring_start();
1530 for (i = 0; i < lenof(hostkey_algs); i++) {
1531 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1532 if (i < lenof(hostkey_algs)-1)
1533 ssh2_pkt_addstring_str(",");
1535 /* List client->server encryption algorithms. */
1536 ssh2_pkt_addstring_start();
1537 for (i = 0; i < lenof(ciphers); i++) {
1538 ssh2_pkt_addstring_str(ciphers[i]->name);
1539 if (i < lenof(ciphers)-1)
1540 ssh2_pkt_addstring_str(",");
1542 /* List server->client encryption algorithms. */
1543 ssh2_pkt_addstring_start();
1544 for (i = 0; i < lenof(ciphers); i++) {
1545 ssh2_pkt_addstring_str(ciphers[i]->name);
1546 if (i < lenof(ciphers)-1)
1547 ssh2_pkt_addstring_str(",");
1549 /* List client->server MAC algorithms. */
1550 ssh2_pkt_addstring_start();
1551 for (i = 0; i < lenof(macs); i++) {
1552 ssh2_pkt_addstring_str(macs[i]->name);
1553 if (i < lenof(macs)-1)
1554 ssh2_pkt_addstring_str(",");
1556 /* List server->client MAC algorithms. */
1557 ssh2_pkt_addstring_start();
1558 for (i = 0; i < lenof(macs); i++) {
1559 ssh2_pkt_addstring_str(macs[i]->name);
1560 if (i < lenof(macs)-1)
1561 ssh2_pkt_addstring_str(",");
1563 /* List client->server compression algorithms. */
1564 ssh2_pkt_addstring_start();
1565 for (i = 0; i < lenof(compressions); i++) {
1566 ssh2_pkt_addstring_str(compressions[i]->name);
1567 if (i < lenof(compressions)-1)
1568 ssh2_pkt_addstring_str(",");
1570 /* List server->client compression algorithms. */
1571 ssh2_pkt_addstring_start();
1572 for (i = 0; i < lenof(compressions); i++) {
1573 ssh2_pkt_addstring_str(compressions[i]->name);
1574 if (i < lenof(compressions)-1)
1575 ssh2_pkt_addstring_str(",");
1577 /* List client->server languages. Empty list. */
1578 ssh2_pkt_addstring_start();
1579 /* List server->client languages. Empty list. */
1580 ssh2_pkt_addstring_start();
1581 /* First KEX packet does _not_ follow, because we're not that brave. */
1582 ssh2_pkt_addbool(FALSE);
1584 ssh2_pkt_adduint32(0);
1585 sha_string(&exhash, pktout.data+5, pktout.length-5);
1588 if (!ispkt) crWaitUntil(ispkt);
1589 sha_string(&exhash, pktin.data+5, pktin.length-5);
1592 * Now examine the other side's KEXINIT to see what we're up
1595 if (pktin.type != SSH2_MSG_KEXINIT) {
1596 fatalbox("expected key exchange packet from server");
1598 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1599 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1600 pktin.savedpos += 16; /* skip garbage cookie */
1601 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
1602 for (i = 0; i < lenof(kex_algs); i++) {
1603 if (in_commasep_string(kex_algs[i]->name, str, len)) {
1608 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
1609 for (i = 0; i < lenof(hostkey_algs); i++) {
1610 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1611 hostkey = hostkey_algs[i];
1615 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
1616 for (i = 0; i < lenof(ciphers); i++) {
1617 if (in_commasep_string(ciphers[i]->name, str, len)) {
1618 cscipher_tobe = ciphers[i];
1622 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
1623 for (i = 0; i < lenof(ciphers); i++) {
1624 if (in_commasep_string(ciphers[i]->name, str, len)) {
1625 sccipher_tobe = ciphers[i];
1629 ssh2_pkt_getstring(&str, &len); /* client->server mac */
1630 for (i = 0; i < lenof(macs); i++) {
1631 if (in_commasep_string(macs[i]->name, str, len)) {
1632 csmac_tobe = macs[i];
1636 ssh2_pkt_getstring(&str, &len); /* server->client mac */
1637 for (i = 0; i < lenof(macs); i++) {
1638 if (in_commasep_string(macs[i]->name, str, len)) {
1639 scmac_tobe = macs[i];
1643 ssh2_pkt_getstring(&str, &len); /* client->server compression */
1644 for (i = 0; i < lenof(compressions); i++) {
1645 if (in_commasep_string(compressions[i]->name, str, len)) {
1646 cscomp_tobe = compressions[i];
1650 ssh2_pkt_getstring(&str, &len); /* server->client compression */
1651 for (i = 0; i < lenof(compressions); i++) {
1652 if (in_commasep_string(compressions[i]->name, str, len)) {
1653 sccomp_tobe = compressions[i];
1659 * Currently we only support Diffie-Hellman and DSS, so let's
1660 * bomb out if those aren't selected.
1662 if (kex != &ssh_diffiehellman || hostkey != &ssh_dss)
1663 fatalbox("internal fault: chaos in SSH 2 transport layer");
1666 * Now we begin the fun. Generate and send e for Diffie-Hellman.
1669 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
1674 if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
1675 fatalbox("expected key exchange packet from server");
1677 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
1678 f = ssh2_pkt_getmp();
1679 ssh2_pkt_getstring(&sigdata, &siglen);
1683 sha_string(&exhash, hostkeydata, hostkeylen);
1684 sha_mpint(&exhash, e);
1685 sha_mpint(&exhash, f);
1686 sha_mpint(&exhash, K);
1687 SHA_Final(&exhash, exchange_hash);
1690 debug(("Exchange hash is:\r\n"));
1691 for (i = 0; i < 20; i++)
1692 debug((" %02x", exchange_hash[i]));
1696 hostkey->setkey(hostkeydata, hostkeylen);
1697 if (!hostkey->verifysig(sigdata, siglen, exchange_hash, 20))
1698 fatalbox("Server failed host key check");
1701 * Expect SSH2_MSG_NEWKEYS from server.
1704 if (pktin.type != SSH2_MSG_NEWKEYS)
1705 fatalbox("expected new-keys packet from server");
1708 * Authenticate remote host: verify host key. (We've already
1709 * checked the signature of the exchange hash.)
1711 keystr = hostkey->fmtkey();
1712 verify_ssh_host_key(savedhost, keystr);
1716 * Send SSH2_MSG_NEWKEYS.
1718 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
1722 * Create and initialise session keys.
1724 cscipher = cscipher_tobe;
1725 sccipher = sccipher_tobe;
1728 cscomp = cscomp_tobe;
1729 sccomp = sccomp_tobe;
1731 * Set IVs after keys.
1733 ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
1734 ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
1735 ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
1736 ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
1737 ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
1738 ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
1741 * Now we're encrypting. Begin returning 1 to the protocol main
1742 * function so that other things can run on top of the
1743 * transport. If we ever see a KEXINIT, we must go back to the
1748 } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
1749 goto begin_key_exchange;
1755 * SSH2: remote identifier for the main session channel.
1757 static unsigned long ssh_remote_channel;
1760 * Handle the SSH2 userauth and connection layers.
1762 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
1764 static unsigned long remote_winsize;
1765 static unsigned long remote_maxpkt;
1770 * Request userauth protocol, and await a response to it.
1772 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
1773 ssh2_pkt_addstring("ssh-userauth");
1775 crWaitUntilV(ispkt);
1776 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT)
1777 fatalbox("Server refused user authentication protocol");
1780 * FIXME: currently we support only password authentication.
1781 * (This places us technically in violation of the SSH2 spec.
1782 * We must fix this.)
1786 * Get a username and a password.
1788 static char username[100];
1789 static char password[100];
1793 if ((flags & FLAG_CONNECTION) && !*cfg.username) {
1794 c_write("login as: ", 10);
1796 crWaitUntilV(!ispkt);
1797 while (inlen--) switch (c = *in++) {
1804 c_write("\b \b", 3);
1810 c_write("\b \b", 3);
1819 if (((c >= ' ' && c <= '~') ||
1820 ((unsigned char)c >= 160)) && pos < 40) {
1821 username[pos++] = c;
1828 username[strcspn(username, "\n\r")] = '\0';
1831 strncpy(username, cfg.username, 99);
1832 username[99] = '\0';
1833 if (flags & FLAG_VERBOSE) {
1834 sprintf(stuff, "Using username \"%s\".\r\n", username);
1835 c_write(stuff, strlen(stuff));
1839 if (!(flags & FLAG_WINDOWED)) {
1841 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
1842 if (!ssh_get_password(prompt, password, sizeof(password))) {
1844 * get_password failed to get a password (for
1845 * example because one was supplied on the command
1846 * line which has already failed to work).
1849 logevent("No more passwords to try");
1850 ssh_state = SSH_STATE_CLOSED;
1854 c_write("password: ", 10);
1858 crWaitUntilV(!ispkt);
1859 while (inlen--) switch (c = *in++) {
1876 if (((c >= ' ' && c <= '~') ||
1877 ((unsigned char)c >= 160)) && pos < 40)
1878 password[pos++] = c;
1885 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
1886 ssh2_pkt_addstring(username);
1887 ssh2_pkt_addstring("ssh-connection"); /* service requested */
1888 ssh2_pkt_addstring("password");
1889 ssh2_pkt_addbool(FALSE);
1890 ssh2_pkt_addstring(password);
1893 crWaitUntilV(ispkt);
1894 if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
1895 c_write("Access denied\r\n", 15);
1896 logevent("Authentication refused");
1902 * Now we're authenticated for the connection protocol. The
1903 * connection protocol will automatically have started at this
1904 * point; there's no need to send SERVICE_REQUEST.
1908 * So now create a channel with a session in it.
1910 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
1911 ssh2_pkt_addstring("session");
1912 ssh2_pkt_adduint32(100); /* as good as any */
1913 ssh2_pkt_adduint32(0xFFFFFFFFUL); /* very big window which we ignore */
1914 ssh2_pkt_adduint32(0xFFFFFFFFUL); /* very big max pkt size */
1916 crWaitUntilV(ispkt);
1917 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
1918 fatalbox("Server refused to open a session");
1919 /* FIXME: error data comes back in FAILURE packet */
1921 if (ssh2_pkt_getuint32() != 100) {
1922 fatalbox("Server's channel confirmation cited wrong channel");
1924 ssh_remote_channel = ssh2_pkt_getuint32();
1925 remote_winsize = ssh2_pkt_getuint32();
1926 remote_maxpkt = ssh2_pkt_getuint32();
1927 logevent("Opened channel for session");
1930 * Now allocate a pty for the session.
1932 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
1933 ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
1934 ssh2_pkt_addstring("pty-req");
1935 ssh2_pkt_addbool(1); /* want reply */
1936 ssh2_pkt_addstring(cfg.termtype);
1937 ssh2_pkt_adduint32(cols);
1938 ssh2_pkt_adduint32(rows);
1939 ssh2_pkt_adduint32(0); /* pixel width */
1940 ssh2_pkt_adduint32(0); /* pixel height */
1941 ssh2_pkt_addstring_start();
1942 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
1945 do { /* FIXME: pay attention to these */
1946 crWaitUntilV(ispkt);
1947 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1949 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
1950 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
1951 fatalbox("Server got confused by pty request");
1953 c_write("Server refused to allocate pty\r\n", 32);
1955 logevent("Allocated pty");
1961 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
1962 ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
1963 ssh2_pkt_addstring("shell");
1964 ssh2_pkt_addbool(1); /* want reply */
1966 do { /* FIXME: pay attention to these */
1967 crWaitUntilV(ispkt);
1968 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1969 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
1970 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
1971 fatalbox("Server got confused by shell request");
1973 fatalbox("Server refused to start a shell");
1975 logevent("Started a shell");
1985 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
1986 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1989 if (ssh2_pkt_getuint32() != 100)
1990 continue; /* wrong channel */
1991 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
1992 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
1993 continue; /* extended but not stderr */
1994 ssh2_pkt_getstring(&data, &length);
1996 c_write(data, length);
1997 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
1998 ssh_state = SSH_STATE_CLOSED;
1999 logevent("Received disconnect request");
2000 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2001 continue; /* exit status et al; ignore (FIXME?) */
2002 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2003 continue; /* ignore for now (FIXME!) */
2005 fatalbox("Strange packet received: type %d", pktin.type);
2008 /* FIXME: for now, ignore window size */
2009 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2010 ssh2_pkt_adduint32(ssh_remote_channel);
2011 ssh2_pkt_addstring_start();
2012 ssh2_pkt_addstring_data(in, inlen);
2021 * Handle the top-level SSH2 protocol.
2023 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2025 if (do_ssh2_transport(in, inlen, ispkt) == 0)
2027 do_ssh2_authconn(in, inlen, ispkt);
2031 * Called to set up the connection. Will arrange for WM_NETEVENT
2032 * messages to be passed to the specified window, whose window
2033 * procedure should then call telnet_msg().
2035 * Returns an error message, or NULL on success.
2037 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
2041 if(crypto_startup() == 0)
2042 return "Microsoft high encryption pack not installed!";
2045 p = connect_to_host(host, port, realhost);
2050 return "Protocol initialisation error";
2052 if (hwnd && WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
2053 switch (WSAGetLastError()) {
2054 case WSAENETDOWN: return "Network is down";
2055 default: return "WSAAsyncSelect(): unknown error";
2062 * Process a WM_NETEVENT message. Will return 0 if the connection
2063 * has closed, or <0 for a socket error.
2065 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
2070 * Because reading less than the whole of the available pending
2071 * data can generate an FD_READ event, we need to allow for the
2072 * possibility that FD_READ may arrive with FD_CLOSE already in
2073 * the queue; so it's possible that we can get here even with s
2074 * invalid. If so, we return 1 and don't worry about it.
2076 if (s == INVALID_SOCKET)
2079 if (WSAGETSELECTERROR(lParam) != 0)
2080 return -WSAGETSELECTERROR(lParam);
2082 switch (WSAGETSELECTEVENT(lParam)) {
2085 ret = recv(s, buf, sizeof(buf), 0);
2086 if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
2088 if (ret < 0) /* any _other_ error */
2089 return -10000-WSAGetLastError();
2094 ssh_gotdata (buf, ret);
2095 if (ssh_state == SSH_STATE_CLOSED) {
2102 return 1; /* shouldn't happen, but WTF */
2106 * Called to send data down the Telnet connection.
2108 static void ssh_send (char *buf, int len) {
2109 if (s == INVALID_SOCKET)
2112 ssh_protocol(buf, len, 0);
2116 * Called to set the size of the window from Telnet's POV.
2118 static void ssh_size(void) {
2119 switch (ssh_state) {
2120 case SSH_STATE_BEFORE_SIZE:
2121 case SSH_STATE_CLOSED:
2122 break; /* do nothing */
2123 case SSH_STATE_INTERMED:
2124 size_needed = TRUE; /* buffer for later */
2126 case SSH_STATE_SESSION:
2128 send_packet(SSH1_CMSG_WINDOW_SIZE,
2129 PKT_INT, rows, PKT_INT, cols,
2130 PKT_INT, 0, PKT_INT, 0, PKT_END);
2136 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2137 * can send an EOF and collect resulting output (e.g. `plink
2140 static void ssh_special (Telnet_Special code) {
2141 if (code == TS_EOF) {
2142 if (ssh_version = 1) {
2143 send_packet(SSH1_CMSG_EOF, PKT_END);
2145 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
2146 ssh2_pkt_adduint32(ssh_remote_channel);
2156 * Read and decrypt one incoming SSH packet.
2157 * (only used by pSCP)
2159 static void get_packet(void)
2161 unsigned char buf[4096], *p;
2168 while ((to_read = s_rdpkt(&p, &len)) > 0) {
2169 if (to_read > sizeof(buf)) to_read = sizeof(buf);
2170 len = s_read(buf, to_read);
2171 if (len != to_read) {
2183 * Receive a block of data over the SSH link. Block until
2184 * all data is available. Return nr of bytes read (0 if lost connection).
2185 * (only used by pSCP)
2187 int ssh_scp_recv(unsigned char *buf, int len)
2189 static int pending_input_len = 0;
2190 static unsigned char *pending_input_ptr;
2193 if (pending_input_len >= to_read) {
2194 memcpy(buf, pending_input_ptr, to_read);
2195 pending_input_ptr += to_read;
2196 pending_input_len -= to_read;
2200 if (pending_input_len > 0) {
2201 memcpy(buf, pending_input_ptr, pending_input_len);
2202 buf += pending_input_len;
2203 to_read -= pending_input_len;
2204 pending_input_len = 0;
2207 if (s == INVALID_SOCKET)
2209 while (to_read > 0) {
2211 if (s == INVALID_SOCKET)
2213 if (pktin.type == SSH1_SMSG_STDOUT_DATA) {
2214 int plen = GET_32BIT(pktin.body);
2215 if (plen <= to_read) {
2216 memcpy(buf, pktin.body + 4, plen);
2220 memcpy(buf, pktin.body + 4, to_read);
2221 pending_input_len = plen - to_read;
2222 pending_input_ptr = pktin.body + 4 + to_read;
2225 } else if (pktin.type == SSH1_SMSG_STDERR_DATA) {
2226 int plen = GET_32BIT(pktin.body);
2227 fwrite(pktin.body + 4, plen, 1, stderr);
2228 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2229 logevent("Received disconnect request");
2230 } else if (pktin.type == SSH1_SMSG_SUCCESS ||
2231 pktin.type == SSH1_SMSG_FAILURE) {
2233 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2235 sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
2237 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2238 logevent("Closing connection");
2242 fatalbox("Strange packet received: type %d", pktin.type);
2250 * Send a block of data over the SSH link.
2251 * Block until all data is sent.
2252 * (only used by pSCP)
2254 void ssh_scp_send(unsigned char *buf, int len)
2256 if (s == INVALID_SOCKET)
2258 send_packet(SSH1_CMSG_STDIN_DATA,
2259 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2263 * Send an EOF notification to the server.
2264 * (only used by pSCP)
2266 void ssh_scp_send_eof(void)
2268 if (s == INVALID_SOCKET)
2270 send_packet(SSH1_CMSG_EOF, PKT_END);
2274 * Set up the connection, login on the remote host and
2275 * start execution of a command.
2276 * Returns an error message, or NULL on success.
2277 * (only used by pSCP)
2279 char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
2284 if (crypto_startup() == 0)
2285 return "Microsoft high encryption pack not installed!";
2288 p = connect_to_host(host, port, realhost);
2295 return "Protocol initialisation error";
2297 /* Exchange keys and login */
2300 if (s == INVALID_SOCKET)
2301 return "Connection closed by remote host";
2302 } while (!do_ssh1_login(NULL, 0, 1));
2304 if (ssh_state == SSH_STATE_CLOSED) {
2307 return "Session initialisation error";
2310 /* Execute command */
2311 sprintf(buf, "Sending command: %.100s", cmd);
2313 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
2318 static SOCKET ssh_socket(void) { return s; }
2320 static int ssh_sendok(void) { return ssh_send_ok; }
2322 Backend ssh_backend = {