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;
168 SSH_STATE_BEFORE_SIZE,
172 } ssh_state = SSH_STATE_BEFORE_SIZE;
174 static int size_needed = FALSE;
176 static void s_write (char *buf, int len) {
178 int i = send (s, buf, len, 0);
181 fatalbox("Lost connection while sending");
187 static int s_read (char *buf, int len) {
190 int i = recv (s, buf, len, 0);
193 len -= i, buf += i, ret += i;
200 static void c_write (char *buf, int len) {
201 if (!(flags & FLAG_CONNECTION)) {
203 for (i = 0; i < len; i++)
205 fputc(buf[i], stderr);
221 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
222 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
224 static int ssh_version;
225 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
226 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
227 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
228 static void ssh_size(void);
230 static int (*s_rdpkt)(unsigned char **data, int *datalen);
233 * Collect incoming data in the incoming packet buffer.
234 * Decipher and verify the packet when it is completely read.
235 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
236 * Update the *data and *datalen variables.
237 * Return the additional nr of bytes needed, or 0 when
238 * a complete packet is available.
240 static int ssh1_rdpkt(unsigned char **data, int *datalen)
242 static long len, pad, biglen, to_read;
243 static unsigned long realcrc, gotcrc;
244 static unsigned char *p;
254 for (i = len = 0; i < 4; i++) {
255 while ((*datalen) == 0)
257 len = (len << 8) + **data;
258 (*data)++, (*datalen)--;
262 if (len == 0x52656d6f) { /* "Remo"te server has closed ... */
263 len = 0x300; /* big enough to carry to end */
269 pktin.length = len - 5;
271 if (pktin.maxlen < biglen) {
272 pktin.maxlen = biglen;
273 pktin.data = (pktin.data == NULL ? malloc(biglen+APIEXTRA) :
274 realloc(pktin.data, biglen+APIEXTRA));
276 fatalbox("Out of memory");
281 while (to_read > 0) {
284 while ((*datalen) == 0)
286 if (chunk > (*datalen))
288 memcpy(p, *data, chunk);
296 cipher->decrypt(pktin.data, biglen);
298 pktin.type = pktin.data[pad];
299 pktin.body = pktin.data + pad + 1;
301 realcrc = crc32(pktin.data, biglen-4);
302 gotcrc = GET_32BIT(pktin.data+biglen-4);
303 if (gotcrc != realcrc) {
304 fatalbox("Incorrect CRC received on packet");
307 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
308 pktin.type == SSH1_SMSG_STDERR_DATA ||
309 pktin.type == SSH1_MSG_DEBUG ||
310 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE) {
311 long strlen = GET_32BIT(pktin.body);
312 if (strlen + 4 != pktin.length)
313 fatalbox("Received data packet with bogus string length");
316 if (pktin.type == SSH1_MSG_DEBUG) {
317 /* log debug message */
319 int strlen = GET_32BIT(pktin.body);
320 strcpy(buf, "Remote: ");
321 if (strlen > 70) strlen = 70;
322 memcpy(buf+8, pktin.body+4, strlen);
323 buf[8+strlen] = '\0';
326 } else if (pktin.type == SSH1_MSG_IGNORE) {
334 static int ssh2_rdpkt(unsigned char **data, int *datalen)
336 static long len, pad, payload, packetlen, maclen;
338 static int cipherblk;
339 static unsigned long incoming_sequence = 0;
349 cipherblk = cipher->blksize;
355 if (pktin.maxlen < cipherblk) {
356 pktin.maxlen = cipherblk;
357 pktin.data = (pktin.data == NULL ? malloc(cipherblk+APIEXTRA) :
358 realloc(pktin.data, cipherblk+APIEXTRA));
360 fatalbox("Out of memory");
364 * Acquire and decrypt the first block of the packet. This will
365 * contain the length and padding details.
367 for (i = len = 0; i < cipherblk; i++) {
368 while ((*datalen) == 0)
369 crReturn(cipherblk-i);
370 pktin.data[i] = *(*data)++;
374 if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
379 sccipher->decrypt(pktin.data, cipherblk);
382 * Now get the length and padding figures.
384 len = GET_32BIT(pktin.data);
388 * This enables us to deduce the payload length.
390 payload = len - pad - 1;
392 pktin.length = payload + 5;
395 * So now we can work out the total packet length.
398 maclen = scmac ? scmac->len : 0;
401 * Adjust memory allocation if packet is too big.
403 if (pktin.maxlen < packetlen) {
404 pktin.maxlen = packetlen;
405 pktin.data = (pktin.data == NULL ? malloc(packetlen+APIEXTRA) :
406 realloc(pktin.data, packetlen+APIEXTRA));
408 fatalbox("Out of memory");
412 * Read and decrypt the remainder of the packet.
414 for (i = cipherblk; i < packetlen + maclen; i++) {
415 while ((*datalen) == 0)
416 crReturn(packetlen + maclen - i);
417 pktin.data[i] = *(*data)++;
420 /* Decrypt everything _except_ the MAC. */
422 sccipher->decrypt(pktin.data + cipherblk, packetlen - cipherblk);
425 debug(("Got packet len=%d pad=%d\r\n", len, pad));
426 for (i = 0; i < packetlen; i++)
427 debug((" %02x", (unsigned char)pktin.data[i]));
434 if (scmac && !scmac->verify(pktin.data, len+4, incoming_sequence))
435 fatalbox("Incorrect MAC received on packet");
436 incoming_sequence++; /* whether or not we MACed */
439 pktin.type = pktin.data[5];
441 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
442 goto next_packet; /* FIXME: print DEBUG message */
447 static void ssh_gotdata(unsigned char *data, int datalen)
449 while (datalen > 0) {
450 if ( s_rdpkt(&data, &datalen) == 0 ) {
451 ssh_protocol(NULL, 0, 1);
452 if (ssh_state == SSH_STATE_CLOSED) {
460 static void s_wrpkt_start(int type, int len) {
463 len += 5; /* type and CRC */
467 pktout.length = len-5;
468 if (pktout.maxlen < biglen) {
469 pktout.maxlen = biglen;
471 /* Allocate enough buffer space for extra block
472 * for MS CryptEncrypt() */
473 pktout.data = (pktout.data == NULL ? malloc(biglen+12) :
474 realloc(pktout.data, biglen+12));
476 pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
477 realloc(pktout.data, biglen+4));
480 fatalbox("Out of memory");
484 pktout.body = pktout.data+4+pad+1;
487 static void s_wrpkt(void) {
488 int pad, len, biglen, i;
491 len = pktout.length + 5; /* type and CRC */
495 pktout.body[-1] = pktout.type;
496 for (i=0; i<pad; i++)
497 pktout.data[i+4] = random_byte();
498 crc = crc32(pktout.data+4, biglen-4);
499 PUT_32BIT(pktout.data+biglen, crc);
500 PUT_32BIT(pktout.data, len);
503 cipher->encrypt(pktout.data+4, biglen);
505 s_write(pktout.data, biglen+4);
509 * Construct a packet with the specified contents and
510 * send it to the server.
512 static void send_packet(int pkttype, ...)
515 unsigned char *p, *argp, argchar;
516 unsigned long argint;
517 int pktlen, argtype, arglen;
522 va_start(args, pkttype);
523 while ((argtype = va_arg(args, int)) != PKT_END) {
526 (void) va_arg(args, int);
530 (void) va_arg(args, char);
534 (void) va_arg(args, unsigned char *);
535 arglen = va_arg(args, int);
539 argp = va_arg(args, unsigned char *);
540 arglen = strlen(argp);
541 pktlen += 4 + arglen;
544 bn = va_arg(args, Bignum);
546 while ( i > 0 && (bn[i/16+1] >> (i%16)) == 0 )
548 pktlen += 2 + (i+7)/8;
556 s_wrpkt_start(pkttype, pktlen);
559 va_start(args, pkttype);
560 while ((argtype = va_arg(args, int)) != PKT_END) {
563 argint = va_arg(args, int);
564 PUT_32BIT(p, argint);
568 argchar = va_arg(args, unsigned char);
573 argp = va_arg(args, unsigned char *);
574 arglen = va_arg(args, int);
575 memcpy(p, argp, arglen);
579 argp = va_arg(args, unsigned char *);
580 arglen = strlen(argp);
581 PUT_32BIT(p, arglen);
582 memcpy(p + 4, argp, arglen);
586 bn = va_arg(args, Bignum);
588 while ( i > 0 && (bn[i/16+1] >> (i%16)) == 0 )
590 *p++ = (i >> 8) & 0xFF;
595 *p++ = bn[i/2+1] >> 8;
597 *p++ = bn[i/2+1] & 0xFF;
609 * Connect to specified host and port.
610 * Returns an error message, or NULL on success.
611 * Also places the canonical host name into `realhost'.
613 static char *connect_to_host(char *host, int port, char **realhost)
623 savedhost = malloc(1+strlen(host));
625 fatalbox("Out of memory");
626 strcpy(savedhost, host);
629 port = 22; /* default ssh port */
641 if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
642 if ( (h = gethostbyname(host)) == NULL)
643 switch (WSAGetLastError()) {
644 case WSAENETDOWN: return "Network is down";
645 case WSAHOST_NOT_FOUND: case WSANO_DATA:
646 return "Host does not exist";
647 case WSATRY_AGAIN: return "Host not found";
648 default: return "gethostbyname: unknown error";
650 memcpy (&a, h->h_addr, sizeof(a));
651 *realhost = h->h_name;
662 s = socket(AF_INET, SOCK_STREAM, 0);
663 if (s == INVALID_SOCKET)
664 switch (WSAGetLastError()) {
665 case WSAENETDOWN: return "Network is down";
666 case WSAEAFNOSUPPORT: return "TCP/IP support not present";
667 default: return "socket(): unknown error";
671 * Bind to local address.
673 addr.sin_family = AF_INET;
674 addr.sin_addr.s_addr = htonl(INADDR_ANY);
675 addr.sin_port = htons(0);
676 if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
677 switch (WSAGetLastError()) {
678 case WSAENETDOWN: return "Network is down";
679 default: return "bind(): unknown error";
683 * Connect to remote address.
685 addr.sin_addr.s_addr = htonl(a);
686 addr.sin_port = htons((short)port);
687 if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
688 switch (WSAGetLastError()) {
689 case WSAENETDOWN: return "Network is down";
690 case WSAECONNREFUSED: return "Connection refused";
691 case WSAENETUNREACH: return "Network is unreachable";
692 case WSAEHOSTUNREACH: return "No route to host";
693 default: return "connect(): unknown error";
697 send(s, "connect ", 8, 0);
698 send(s, FWhost, strlen(FWhost), 0);
701 sprintf(buf, " %d\n", FWport);
702 send (s, buf, strlen(buf), 0);
709 static int ssh_versioncmp(char *a, char *b) {
711 unsigned long av, bv;
713 av = strtoul(a, &ae, 10);
714 bv = strtoul(b, &be, 10);
715 if (av != bv) return (av < bv ? -1 : +1);
716 if (*ae == '.') ae++;
717 if (*be == '.') be++;
718 av = strtoul(ae, &ae, 10);
719 bv = strtoul(be, &be, 10);
720 if (av != bv) return (av < bv ? -1 : +1);
726 * Utility routine for putting an SSH-protocol `string' into a SHA
730 void sha_string(SHA_State *s, void *str, int len) {
731 unsigned char lenblk[4];
733 PUT_32BIT(lenblk, len);
734 if (!fp) fp = fopen("h:\\statham\\windows\\putty\\data","wb");
735 fwrite(lenblk, 4, 1, fp);
736 SHA_Bytes(s, lenblk, 4);
737 fwrite(str, len, 1, fp);
739 SHA_Bytes(s, str, len);
743 * SSH2 packet construction functions.
745 void ssh2_pkt_adddata(void *data, int len) {
746 pktout.length += len;
747 if (pktout.maxlen < pktout.length) {
748 pktout.maxlen = pktout.length + 256;
749 pktout.data = (pktout.data == NULL ? malloc(pktout.maxlen+APIEXTRA) :
750 realloc(pktout.data, pktout.maxlen+APIEXTRA));
752 fatalbox("Out of memory");
754 memcpy(pktout.data+pktout.length-len, data, len);
756 void ssh2_pkt_addbyte(unsigned char byte) {
757 ssh2_pkt_adddata(&byte, 1);
759 void ssh2_pkt_init(int pkt_type) {
761 ssh2_pkt_addbyte((unsigned char)pkt_type);
763 void ssh2_pkt_addbool(unsigned char value) {
764 ssh2_pkt_adddata(&value, 1);
766 void ssh2_pkt_adduint32(unsigned long value) {
769 ssh2_pkt_adddata(x, 4);
771 void ssh2_pkt_addstring_start(void) {
772 ssh2_pkt_adduint32(0);
773 pktout.savedpos = pktout.length;
775 void ssh2_pkt_addstring_str(char *data) {
776 ssh2_pkt_adddata(data, strlen(data));
777 PUT_32BIT(pktout.data + pktout.savedpos - 4,
778 pktout.length - pktout.savedpos);
780 void ssh2_pkt_addstring_data(char *data, int len) {
781 ssh2_pkt_adddata(data, len);
782 PUT_32BIT(pktout.data + pktout.savedpos - 4,
783 pktout.length - pktout.savedpos);
785 void ssh2_pkt_addstring(char *data) {
786 ssh2_pkt_addstring_start();
787 ssh2_pkt_addstring_str(data);
789 char *ssh2_mpint_fmt(Bignum b, int *len) {
792 p = malloc(n * 2 + 1);
794 fatalbox("out of memory");
796 for (i = 0; i < n; i++) {
797 p[i*2+1] = (b[n-i] >> 8) & 0xFF;
798 p[i*2+2] = (b[n-i] ) & 0xFF;
801 while (p[i] == 0 && (p[i+1] & 0x80) == 0)
803 memmove(p, p+i, n*2+1-i);
807 void ssh2_pkt_addmp(Bignum b) {
810 p = ssh2_mpint_fmt(b, &len);
811 ssh2_pkt_addstring_start();
812 ssh2_pkt_addstring_data(p, len);
815 void ssh2_pkt_send(void) {
816 int cipherblk, maclen, padding, i;
817 static unsigned long outgoing_sequence = 0;
820 * Add padding. At least four bytes, and must also bring total
821 * length (minus MAC) up to a multiple of the block size.
823 cipherblk = cipher ? cipher->blksize : 8; /* block size */
824 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
826 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
827 pktout.data[4] = padding;
828 for (i = 0; i < padding; i++)
829 pktout.data[pktout.length + i] = random_byte();
830 PUT_32BIT(pktout.data, pktout.length + padding - 4);
832 csmac->generate(pktout.data, pktout.length + padding,
834 outgoing_sequence++; /* whether or not we MACed */
837 debug(("Sending packet len=%d\r\n", pktout.length+padding));
838 for (i = 0; i < pktout.length+padding; i++)
839 debug((" %02x", (unsigned char)pktout.data[i]));
844 cscipher->encrypt(pktout.data, pktout.length + padding);
845 maclen = csmac ? csmac->len : 0;
847 s_write(pktout.data, pktout.length + padding + maclen);
851 void bndebug(char *string, Bignum b) {
854 p = ssh2_mpint_fmt(b, &len);
855 debug(("%s", string));
856 for (i = 0; i < len; i++)
857 debug((" %02x", p[i]));
863 void sha_mpint(SHA_State *s, Bignum b) {
866 p = ssh2_mpint_fmt(b, &len);
867 sha_string(s, p, len);
872 * SSH2 packet decode functions.
874 unsigned long ssh2_pkt_getuint32(void) {
876 if (pktin.length - pktin.savedpos < 4)
877 return 0; /* arrgh, no way to decline (FIXME?) */
878 value = GET_32BIT(pktin.data+pktin.savedpos);
882 void ssh2_pkt_getstring(char **p, int *length) {
884 if (pktin.length - pktin.savedpos < 4)
886 *length = GET_32BIT(pktin.data+pktin.savedpos);
888 if (pktin.length - pktin.savedpos < *length)
890 *p = pktin.data+pktin.savedpos;
891 pktin.savedpos += *length;
893 Bignum ssh2_pkt_getmp(void) {
898 ssh2_pkt_getstring(&p, &length);
902 fatalbox("internal error: Can't handle negative mpints");
903 b = newbn((length+1)/2);
904 for (i = 0; i < length; i++) {
907 b[j/2+1] |= ((unsigned char)p[i]) << 8;
909 b[j/2+1] |= ((unsigned char)p[i]);
914 static int do_ssh_init(void) {
918 char vlog[sizeof(vstring)+20];
923 while (s_read(&c, 1) == 1) {
924 if (c == 'S' && i < 2) i++;
925 else if (c == 'S' && i == 2) i = 2;
926 else if (c == 'H' && i == 2) break;
930 if (s_read(&c,1) != 1 || c != 'S') return 0;
931 if (s_read(&c,1) != 1 || c != 'S') return 0;
932 if (s_read(&c,1) != 1 || c != 'H') return 0;
934 strcpy(vstring, "SSH-");
936 if (s_read(&c,1) != 1 || c != '-') return 0;
939 if (s_read(&c,1) != 1)
941 if (vsp < vstring+sizeof(vstring)-1)
947 } else if (i < sizeof(version)-1)
955 sprintf(vlog, "Server version: %s", vstring);
956 vlog[strcspn(vlog, "\r\n")] = '\0';
959 if (ssh_versioncmp(version, "2.0" /* FIXME: "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;
997 * Handle the key exchange and user authentication phases.
999 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1002 unsigned char *rsabuf, *keystr1, *keystr2;
1003 unsigned char cookie[8];
1004 struct RSAKey servkey, hostkey;
1005 struct MD5Context md5c;
1006 static unsigned long supported_ciphers_mask, supported_auths_mask;
1007 static int tried_publickey;
1008 static unsigned char session_id[16];
1013 if (!ispkt) crWaitUntil(ispkt);
1015 if (pktin.type != SSH1_SMSG_PUBLIC_KEY)
1016 fatalbox("Public key packet not received");
1018 logevent("Received public keys");
1020 memcpy(cookie, pktin.body, 8);
1022 i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1023 j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1026 * Hash the host key and print the hash in the log box. Just as
1027 * a last resort in case the registry's host key checking is
1028 * compromised, we'll allow the user some ability to verify
1032 MD5Update(&md5c, keystr2, hostkey.bytes);
1033 MD5Final(session_id, &md5c);
1037 logevent("Host key MD5 is:");
1038 strcpy(logmsg, " ");
1039 for (i = 0; i < 16; i++)
1040 sprintf(logmsg+strlen(logmsg), "%02x", session_id[i]);
1044 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1045 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1048 MD5Update(&md5c, keystr2, hostkey.bytes);
1049 MD5Update(&md5c, keystr1, servkey.bytes);
1050 MD5Update(&md5c, pktin.body, 8);
1051 MD5Final(session_id, &md5c);
1053 for (i=0; i<32; i++)
1054 session_key[i] = random_byte();
1056 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1058 rsabuf = malloc(len);
1060 fatalbox("Out of memory");
1063 * Verify the host key.
1067 * First format the key into a string.
1069 int len = rsastr_len(&hostkey);
1070 char *keystr = malloc(len);
1072 fatalbox("Out of memory");
1073 rsastr_fmt(keystr, &hostkey);
1074 verify_ssh_host_key(savedhost, keystr);
1078 for (i=0; i<32; i++) {
1079 rsabuf[i] = session_key[i];
1081 rsabuf[i] ^= session_id[i];
1084 if (hostkey.bytes > servkey.bytes) {
1085 rsaencrypt(rsabuf, 32, &servkey);
1086 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1088 rsaencrypt(rsabuf, 32, &hostkey);
1089 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1092 logevent("Encrypted session key");
1094 cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
1095 cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES :
1097 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1098 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1099 cipher_type = SSH_CIPHER_3DES;
1101 switch (cipher_type) {
1102 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1103 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1104 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1107 send_packet(SSH1_CMSG_SESSION_KEY,
1108 PKT_CHAR, cipher_type,
1109 PKT_DATA, cookie, 8,
1110 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1111 PKT_DATA, rsabuf, len,
1115 logevent("Trying to enable encryption...");
1119 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
1120 cipher_type == SSH_CIPHER_DES ? &ssh_des :
1122 cipher->sesskey(session_key);
1126 if (pktin.type != SSH1_SMSG_SUCCESS)
1127 fatalbox("Encryption not successfully enabled");
1129 logevent("Successfully started encryption");
1133 static char username[100];
1136 if (!(flags & FLAG_CONNECTION) && !*cfg.username) {
1137 c_write("login as: ", 10);
1139 crWaitUntil(!ispkt);
1140 while (inlen--) switch (c = *in++) {
1147 c_write("\b \b", 3);
1153 c_write("\b \b", 3);
1162 if (((c >= ' ' && c <= '~') ||
1163 ((unsigned char)c >= 160)) && pos < 40) {
1164 username[pos++] = c;
1171 username[strcspn(username, "\n\r")] = '\0';
1174 strncpy(username, cfg.username, 99);
1175 username[99] = '\0';
1176 if (flags & FLAG_VERBOSE) {
1177 sprintf(stuff, "Sent username \"%s\".\r\n", username);
1178 c_write(stuff, strlen(stuff));
1182 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1184 char userlog[20+sizeof(username)];
1185 sprintf(userlog, "Sent username \"%s\"", username);
1192 tried_publickey = 0;
1194 while (pktin.type == SSH1_SMSG_FAILURE) {
1195 static char password[100];
1198 static int pwpkt_type;
1200 * Show password prompt, having first obtained it via a TIS
1201 * exchange if we're doing TIS authentication.
1203 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1204 if (*cfg.keyfile && !tried_publickey)
1205 pwpkt_type = SSH1_CMSG_AUTH_RSA;
1207 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD && !FLAG_WINDOWED) {
1209 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
1210 if (!ssh_get_password(prompt, password, sizeof(password))) {
1212 * get_password failed to get a password (for
1213 * example because one was supplied on the command
1214 * line which has already failed to work).
1217 logevent("No more passwords to try");
1218 ssh_state = SSH_STATE_CLOSED;
1223 if (pktin.type == SSH1_SMSG_FAILURE &&
1225 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1226 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1227 logevent("Requested TIS authentication");
1228 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1230 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1231 logevent("TIS authentication declined");
1232 c_write("TIS authentication refused.\r\n", 29);
1234 int challengelen = ((pktin.body[0] << 24) |
1235 (pktin.body[1] << 16) |
1236 (pktin.body[2] << 8) |
1238 logevent("Received TIS challenge");
1239 c_write(pktin.body+4, challengelen);
1242 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD)
1243 c_write("password: ", 10);
1244 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1245 if (flags & FLAG_VERBOSE)
1246 c_write("Trying public key authentication.\r\n", 35);
1247 if (!rsakey_encrypted(cfg.keyfile)) {
1248 if (flags & FLAG_VERBOSE)
1249 c_write("No passphrase required.\r\n", 25);
1252 c_write("passphrase: ", 12);
1257 crWaitUntil(!ispkt);
1258 while (inlen--) switch (c = *in++) {
1275 if (((c >= ' ' && c <= '~') ||
1276 ((unsigned char)c >= 160)) && pos < sizeof(password))
1277 password[pos++] = c;
1286 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1288 * Try public key authentication with the specified
1291 static struct RSAKey pubkey;
1292 static Bignum challenge, response;
1294 static unsigned char buffer[32];
1296 tried_publickey = 1;
1297 i = loadrsakey(cfg.keyfile, &pubkey, password);
1299 c_write("Couldn't load public key from ", 30);
1300 c_write(cfg.keyfile, strlen(cfg.keyfile));
1301 c_write(".\r\n", 3);
1302 continue; /* go and try password */
1305 c_write("Wrong passphrase.\r\n", 19);
1306 tried_publickey = 0;
1307 continue; /* try again */
1311 * Send a public key attempt.
1313 send_packet(SSH1_CMSG_AUTH_RSA,
1314 PKT_BIGNUM, pubkey.modulus, PKT_END);
1317 if (pktin.type == SSH1_SMSG_FAILURE) {
1318 if (flags & FLAG_VERBOSE)
1319 c_write("Server refused our public key.\r\n", 32);
1320 continue; /* go and try password */
1322 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE)
1323 fatalbox("Bizarre response to offer of public key");
1324 ssh1_read_bignum(pktin.body, &challenge);
1325 response = rsadecrypt(challenge, &pubkey);
1326 freebn(pubkey.private_exponent); /* burn the evidence */
1328 for (i = 0; i < 32; i += 2) {
1329 buffer[i] = response[16-i/2] >> 8;
1330 buffer[i+1] = response[16-i/2] & 0xFF;
1334 MD5Update(&md5c, buffer, 32);
1335 MD5Update(&md5c, session_id, 16);
1336 MD5Final(buffer, &md5c);
1338 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1339 PKT_DATA, buffer, 16, PKT_END);
1342 if (pktin.type == SSH1_SMSG_FAILURE) {
1343 if (flags & FLAG_VERBOSE)
1344 c_write("Failed to authenticate with our public key.\r\n",
1346 continue; /* go and try password */
1347 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1348 fatalbox("Bizarre response to RSA authentication response");
1351 break; /* we're through! */
1353 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1355 logevent("Sent password");
1356 memset(password, 0, strlen(password));
1358 if (pktin.type == SSH1_SMSG_FAILURE) {
1359 if (flags & FLAG_VERBOSE)
1360 c_write("Access denied\r\n", 15);
1361 logevent("Authentication refused");
1362 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1363 logevent("Received disconnect request");
1364 ssh_state = SSH_STATE_CLOSED;
1366 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1367 fatalbox("Strange packet received, type %d", pktin.type);
1371 logevent("Authentication successful");
1376 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1381 while (!do_ssh1_login(in, inlen, ispkt)) {
1384 if (ssh_state == SSH_STATE_CLOSED)
1388 send_packet(SSH1_CMSG_REQUEST_PTY,
1389 PKT_STR, cfg.termtype,
1390 PKT_INT, rows, PKT_INT, cols,
1391 PKT_INT, 0, PKT_INT, 0,
1394 ssh_state = SSH_STATE_INTERMED;
1395 do { crReturnV; } while (!ispkt);
1396 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1397 fatalbox("Protocol confusion");
1398 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1399 c_write("Server refused to allocate pty\r\n", 32);
1401 logevent("Allocated pty");
1404 if (*cfg.remote_cmd)
1405 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1407 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1408 logevent("Started session");
1410 ssh_state = SSH_STATE_SESSION;
1417 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1418 pktin.type == SSH1_SMSG_STDERR_DATA) {
1419 long len = GET_32BIT(pktin.body);
1420 c_write(pktin.body+4, len);
1421 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1422 ssh_state = SSH_STATE_CLOSED;
1423 logevent("Received disconnect request");
1424 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
1425 /* may be from EXEC_SHELL on some servers */
1426 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1427 /* may be from EXEC_SHELL on some servers
1428 * if no pty is available or in other odd cases. Ignore */
1429 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1430 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
1432 fatalbox("Strange packet received: type %d", pktin.type);
1435 send_packet(SSH1_CMSG_STDIN_DATA,
1436 PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
1444 * Utility routine for decoding comma-separated strings in KEXINIT.
1446 int in_commasep_string(char *needle, char *haystack, int haylen) {
1447 int needlen = strlen(needle);
1450 * Is it at the start of the string?
1452 if (haylen >= needlen && /* haystack is long enough */
1453 !memcmp(needle, haystack, needlen) && /* initial match */
1454 (haylen == needlen || haystack[needlen] == ',')
1455 /* either , or EOS follows */
1459 * If not, search for the next comma and resume after that.
1460 * If no comma found, terminate.
1462 while (haylen > 0 && *haystack != ',')
1463 haylen--, haystack++;
1466 haylen--, haystack++; /* skip over comma itself */
1471 * SSH2 key creation method.
1473 void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1475 /* First 20 bytes. */
1478 SHA_Bytes(&s, H, 20);
1479 SHA_Bytes(&s, &chr, 1);
1480 SHA_Bytes(&s, H, 20);
1481 SHA_Final(&s, keyspace);
1482 /* Next 20 bytes. */
1485 SHA_Bytes(&s, H, 20);
1486 SHA_Bytes(&s, keyspace, 20);
1487 SHA_Final(&s, keyspace+20);
1491 * Handle the SSH2 transport layer.
1493 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
1497 static Bignum e, f, K;
1498 static struct ssh_cipher *cscipher_tobe = NULL;
1499 static struct ssh_cipher *sccipher_tobe = NULL;
1500 static struct ssh_mac *csmac_tobe = NULL;
1501 static struct ssh_mac *scmac_tobe = NULL;
1502 static struct ssh_compress *cscomp_tobe = NULL;
1503 static struct ssh_compress *sccomp_tobe = NULL;
1504 static char *hostkeydata, *sigdata, *keystr;
1505 static int hostkeylen, siglen;
1506 static unsigned char exchange_hash[20];
1507 static unsigned char keyspace[40];
1514 * Construct and send our key exchange packet.
1516 ssh2_pkt_init(SSH2_MSG_KEXINIT);
1517 for (i = 0; i < 16; i++)
1518 ssh2_pkt_addbyte((unsigned char)random_byte());
1519 /* List key exchange algorithms. */
1520 ssh2_pkt_addstring_start();
1521 for (i = 0; i < lenof(kex_algs); i++) {
1522 ssh2_pkt_addstring_str(kex_algs[i]->name);
1523 if (i < lenof(kex_algs)-1)
1524 ssh2_pkt_addstring_str(",");
1526 /* List server host key algorithms. */
1527 ssh2_pkt_addstring_start();
1528 for (i = 0; i < lenof(hostkey_algs); i++) {
1529 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1530 if (i < lenof(hostkey_algs)-1)
1531 ssh2_pkt_addstring_str(",");
1533 /* List client->server encryption algorithms. */
1534 ssh2_pkt_addstring_start();
1535 for (i = 0; i < lenof(ciphers); i++) {
1536 ssh2_pkt_addstring_str(ciphers[i]->name);
1537 if (i < lenof(ciphers)-1)
1538 ssh2_pkt_addstring_str(",");
1540 /* List server->client encryption algorithms. */
1541 ssh2_pkt_addstring_start();
1542 for (i = 0; i < lenof(ciphers); i++) {
1543 ssh2_pkt_addstring_str(ciphers[i]->name);
1544 if (i < lenof(ciphers)-1)
1545 ssh2_pkt_addstring_str(",");
1547 /* List client->server MAC algorithms. */
1548 ssh2_pkt_addstring_start();
1549 for (i = 0; i < lenof(macs); i++) {
1550 ssh2_pkt_addstring_str(macs[i]->name);
1551 if (i < lenof(macs)-1)
1552 ssh2_pkt_addstring_str(",");
1554 /* List server->client MAC algorithms. */
1555 ssh2_pkt_addstring_start();
1556 for (i = 0; i < lenof(macs); i++) {
1557 ssh2_pkt_addstring_str(macs[i]->name);
1558 if (i < lenof(macs)-1)
1559 ssh2_pkt_addstring_str(",");
1561 /* List client->server compression algorithms. */
1562 ssh2_pkt_addstring_start();
1563 for (i = 0; i < lenof(compressions); i++) {
1564 ssh2_pkt_addstring_str(compressions[i]->name);
1565 if (i < lenof(compressions)-1)
1566 ssh2_pkt_addstring_str(",");
1568 /* List server->client compression algorithms. */
1569 ssh2_pkt_addstring_start();
1570 for (i = 0; i < lenof(compressions); i++) {
1571 ssh2_pkt_addstring_str(compressions[i]->name);
1572 if (i < lenof(compressions)-1)
1573 ssh2_pkt_addstring_str(",");
1575 /* List client->server languages. Empty list. */
1576 ssh2_pkt_addstring_start();
1577 /* List server->client languages. Empty list. */
1578 ssh2_pkt_addstring_start();
1579 /* First KEX packet does _not_ follow, because we're not that brave. */
1580 ssh2_pkt_addbool(FALSE);
1582 ssh2_pkt_adduint32(0);
1583 sha_string(&exhash, pktout.data+5, pktout.length-5);
1586 if (!ispkt) crWaitUntil(ispkt);
1587 sha_string(&exhash, pktin.data+5, pktin.length-5);
1590 * Now examine the other side's KEXINIT to see what we're up
1593 if (pktin.type != SSH2_MSG_KEXINIT) {
1594 fatalbox("expected key exchange packet from server");
1596 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1597 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1598 pktin.savedpos += 16; /* skip garbage cookie */
1599 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
1600 for (i = 0; i < lenof(kex_algs); i++) {
1601 if (in_commasep_string(kex_algs[i]->name, str, len)) {
1606 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
1607 for (i = 0; i < lenof(hostkey_algs); i++) {
1608 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1609 hostkey = hostkey_algs[i];
1613 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
1614 for (i = 0; i < lenof(ciphers); i++) {
1615 if (in_commasep_string(ciphers[i]->name, str, len)) {
1616 cscipher_tobe = ciphers[i];
1620 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
1621 for (i = 0; i < lenof(ciphers); i++) {
1622 if (in_commasep_string(ciphers[i]->name, str, len)) {
1623 sccipher_tobe = ciphers[i];
1627 ssh2_pkt_getstring(&str, &len); /* client->server mac */
1628 for (i = 0; i < lenof(macs); i++) {
1629 if (in_commasep_string(macs[i]->name, str, len)) {
1630 csmac_tobe = macs[i];
1634 ssh2_pkt_getstring(&str, &len); /* server->client mac */
1635 for (i = 0; i < lenof(macs); i++) {
1636 if (in_commasep_string(macs[i]->name, str, len)) {
1637 scmac_tobe = macs[i];
1641 ssh2_pkt_getstring(&str, &len); /* client->server compression */
1642 for (i = 0; i < lenof(compressions); i++) {
1643 if (in_commasep_string(compressions[i]->name, str, len)) {
1644 cscomp_tobe = compressions[i];
1648 ssh2_pkt_getstring(&str, &len); /* server->client compression */
1649 for (i = 0; i < lenof(compressions); i++) {
1650 if (in_commasep_string(compressions[i]->name, str, len)) {
1651 sccomp_tobe = compressions[i];
1657 * Currently we only support Diffie-Hellman and DSS, so let's
1658 * bomb out if those aren't selected.
1660 if (kex != &ssh_diffiehellman || hostkey != &ssh_dss)
1661 fatalbox("internal fault: chaos in SSH 2 transport layer");
1664 * Now we begin the fun. Generate and send e for Diffie-Hellman.
1667 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
1672 if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
1673 fatalbox("expected key exchange packet from server");
1675 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
1676 f = ssh2_pkt_getmp();
1677 ssh2_pkt_getstring(&sigdata, &siglen);
1681 sha_string(&exhash, hostkeydata, hostkeylen);
1682 sha_mpint(&exhash, e);
1683 sha_mpint(&exhash, f);
1684 sha_mpint(&exhash, K);
1685 SHA_Final(&exhash, exchange_hash);
1688 debug(("Exchange hash is:\r\n"));
1689 for (i = 0; i < 20; i++)
1690 debug((" %02x", exchange_hash[i]));
1694 hostkey->setkey(hostkeydata, hostkeylen);
1695 if (!hostkey->verifysig(sigdata, siglen, exchange_hash, 20))
1696 fatalbox("Server failed host key check");
1699 * Expect SSH2_MSG_NEWKEYS from server.
1702 if (pktin.type != SSH2_MSG_NEWKEYS)
1703 fatalbox("expected new-keys packet from server");
1706 * Authenticate remote host: verify host key. (We've already
1707 * checked the signature of the exchange hash.)
1709 keystr = hostkey->fmtkey();
1710 verify_ssh_host_key(savedhost, keystr);
1714 * Send SSH2_MSG_NEWKEYS.
1716 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
1720 * Create and initialise session keys.
1722 cscipher = cscipher_tobe;
1723 sccipher = sccipher_tobe;
1726 cscomp = cscomp_tobe;
1727 sccomp = sccomp_tobe;
1729 * Set IVs after keys.
1731 ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
1732 ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
1733 ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
1734 ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
1735 ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
1736 ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
1739 * Now we're encrypting. Begin returning 1 to the protocol main
1740 * function so that other things can run on top of the
1741 * transport. If we ever see a KEXINIT, we must go back to the
1746 } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
1747 goto begin_key_exchange;
1753 * SSH2: remote identifier for the main session channel.
1755 static unsigned long ssh_remote_channel;
1758 * Handle the SSH2 userauth and connection layers.
1760 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
1762 static unsigned long remote_winsize;
1763 static unsigned long remote_maxpkt;
1768 * Request userauth protocol, and await a response to it.
1770 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
1771 ssh2_pkt_addstring("ssh-userauth");
1773 crWaitUntilV(ispkt);
1774 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT)
1775 fatalbox("Server refused user authentication protocol");
1778 * FIXME: currently we support only password authentication.
1779 * (This places us technically in violation of the SSH2 spec.
1780 * We must fix this.)
1784 * Get a username and a password.
1786 static char username[100];
1787 static char password[100];
1791 if ((flags & FLAG_CONNECTION) && !*cfg.username) {
1792 c_write("login as: ", 10);
1794 crWaitUntilV(!ispkt);
1795 while (inlen--) switch (c = *in++) {
1802 c_write("\b \b", 3);
1808 c_write("\b \b", 3);
1817 if (((c >= ' ' && c <= '~') ||
1818 ((unsigned char)c >= 160)) && pos < 40) {
1819 username[pos++] = c;
1826 username[strcspn(username, "\n\r")] = '\0';
1829 strncpy(username, cfg.username, 99);
1830 username[99] = '\0';
1831 if (flags & FLAG_VERBOSE) {
1832 sprintf(stuff, "Using username \"%s\".\r\n", username);
1833 c_write(stuff, strlen(stuff));
1837 if (!(flags & FLAG_WINDOWED)) {
1839 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
1840 if (!ssh_get_password(prompt, password, sizeof(password))) {
1842 * get_password failed to get a password (for
1843 * example because one was supplied on the command
1844 * line which has already failed to work).
1847 logevent("No more passwords to try");
1848 ssh_state = SSH_STATE_CLOSED;
1852 c_write("password: ", 10);
1856 crWaitUntilV(!ispkt);
1857 while (inlen--) switch (c = *in++) {
1874 if (((c >= ' ' && c <= '~') ||
1875 ((unsigned char)c >= 160)) && pos < 40)
1876 password[pos++] = c;
1883 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
1884 ssh2_pkt_addstring(username);
1885 ssh2_pkt_addstring("ssh-connection"); /* service requested */
1886 ssh2_pkt_addstring("password");
1887 ssh2_pkt_addbool(FALSE);
1888 ssh2_pkt_addstring(password);
1891 crWaitUntilV(ispkt);
1892 if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
1893 c_write("Access denied\r\n", 15);
1894 logevent("Authentication refused");
1900 * Now we're authenticated for the connection protocol. The
1901 * connection protocol will automatically have started at this
1902 * point; there's no need to send SERVICE_REQUEST.
1906 * So now create a channel with a session in it.
1908 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
1909 ssh2_pkt_addstring("session");
1910 ssh2_pkt_adduint32(100); /* as good as any */
1911 ssh2_pkt_adduint32(0xFFFFFFFFUL); /* very big window which we ignore */
1912 ssh2_pkt_adduint32(0xFFFFFFFFUL); /* very big max pkt size */
1914 crWaitUntilV(ispkt);
1915 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
1916 fatalbox("Server refused to open a session");
1917 /* FIXME: error data comes back in FAILURE packet */
1919 if (ssh2_pkt_getuint32() != 100) {
1920 fatalbox("Server's channel confirmation cited wrong channel");
1922 ssh_remote_channel = ssh2_pkt_getuint32();
1923 remote_winsize = ssh2_pkt_getuint32();
1924 remote_maxpkt = ssh2_pkt_getuint32();
1925 logevent("Opened channel for session");
1928 * Now allocate a pty for the session.
1930 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
1931 ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
1932 ssh2_pkt_addstring("pty-req");
1933 ssh2_pkt_addbool(1); /* want reply */
1934 ssh2_pkt_addstring(cfg.termtype);
1935 ssh2_pkt_adduint32(cols);
1936 ssh2_pkt_adduint32(rows);
1937 ssh2_pkt_adduint32(0); /* pixel width */
1938 ssh2_pkt_adduint32(0); /* pixel height */
1939 ssh2_pkt_addstring_start();
1940 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
1943 do { /* FIXME: pay attention to these */
1944 crWaitUntilV(ispkt);
1945 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1947 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
1948 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
1949 fatalbox("Server got confused by pty request");
1951 c_write("Server refused to allocate pty\r\n", 32);
1953 logevent("Allocated pty");
1959 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
1960 ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
1961 ssh2_pkt_addstring("shell");
1962 ssh2_pkt_addbool(1); /* want reply */
1964 do { /* FIXME: pay attention to these */
1965 crWaitUntilV(ispkt);
1966 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1967 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
1968 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
1969 fatalbox("Server got confused by shell request");
1971 fatalbox("Server refused to start a shell");
1973 logevent("Started a shell");
1982 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
1983 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1986 if (ssh2_pkt_getuint32() != 100)
1987 continue; /* wrong channel */
1988 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
1989 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
1990 continue; /* extended but not stderr */
1991 ssh2_pkt_getstring(&data, &length);
1993 c_write(data, length);
1994 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
1995 ssh_state = SSH_STATE_CLOSED;
1996 logevent("Received disconnect request");
1997 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
1998 continue; /* exit status et al; ignore (FIXME?) */
1999 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2000 continue; /* ignore for now (FIXME!) */
2002 fatalbox("Strange packet received: type %d", pktin.type);
2005 /* FIXME: for now, ignore window size */
2006 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2007 ssh2_pkt_adduint32(ssh_remote_channel);
2008 ssh2_pkt_addstring_start();
2009 ssh2_pkt_addstring_data(in, inlen);
2018 * Handle the top-level SSH2 protocol.
2020 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2022 if (do_ssh2_transport(in, inlen, ispkt) == 0)
2024 do_ssh2_authconn(in, inlen, ispkt);
2028 * Called to set up the connection. Will arrange for WM_NETEVENT
2029 * messages to be passed to the specified window, whose window
2030 * procedure should then call telnet_msg().
2032 * Returns an error message, or NULL on success.
2034 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
2038 if(crypto_startup() == 0)
2039 return "Microsoft high encryption pack not installed!";
2042 p = connect_to_host(host, port, realhost);
2047 return "Protocol initialisation error";
2049 if (hwnd && WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
2050 switch (WSAGetLastError()) {
2051 case WSAENETDOWN: return "Network is down";
2052 default: return "WSAAsyncSelect(): unknown error";
2059 * Process a WM_NETEVENT message. Will return 0 if the connection
2060 * has closed, or <0 for a socket error.
2062 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
2067 * Because reading less than the whole of the available pending
2068 * data can generate an FD_READ event, we need to allow for the
2069 * possibility that FD_READ may arrive with FD_CLOSE already in
2070 * the queue; so it's possible that we can get here even with s
2071 * invalid. If so, we return 1 and don't worry about it.
2073 if (s == INVALID_SOCKET)
2076 if (WSAGETSELECTERROR(lParam) != 0)
2077 return -WSAGETSELECTERROR(lParam);
2079 switch (WSAGETSELECTEVENT(lParam)) {
2082 ret = recv(s, buf, sizeof(buf), 0);
2083 if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
2085 if (ret < 0) /* any _other_ error */
2086 return -10000-WSAGetLastError();
2091 ssh_gotdata (buf, ret);
2092 if (ssh_state == SSH_STATE_CLOSED) {
2099 return 1; /* shouldn't happen, but WTF */
2103 * Called to send data down the Telnet connection.
2105 static void ssh_send (char *buf, int len) {
2106 if (s == INVALID_SOCKET)
2109 ssh_protocol(buf, len, 0);
2113 * Called to set the size of the window from Telnet's POV.
2115 static void ssh_size(void) {
2116 switch (ssh_state) {
2117 case SSH_STATE_BEFORE_SIZE:
2118 case SSH_STATE_CLOSED:
2119 break; /* do nothing */
2120 case SSH_STATE_INTERMED:
2121 size_needed = TRUE; /* buffer for later */
2123 case SSH_STATE_SESSION:
2125 send_packet(SSH1_CMSG_WINDOW_SIZE,
2126 PKT_INT, rows, PKT_INT, cols,
2127 PKT_INT, 0, PKT_INT, 0, PKT_END);
2133 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2134 * can send an EOF and collect resulting output (e.g. `plink
2137 static void ssh_special (Telnet_Special code) {
2138 if (code == TS_EOF) {
2139 if (ssh_version = 1) {
2140 send_packet(SSH1_CMSG_EOF, PKT_END);
2142 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
2143 ssh2_pkt_adduint32(ssh_remote_channel);
2153 * Read and decrypt one incoming SSH packet.
2154 * (only used by pSCP)
2156 static void get_packet(void)
2158 unsigned char buf[4096], *p;
2165 while ((to_read = s_rdpkt(&p, &len)) > 0) {
2166 if (to_read > sizeof(buf)) to_read = sizeof(buf);
2167 len = s_read(buf, to_read);
2168 if (len != to_read) {
2180 * Receive a block of data over the SSH link. Block until
2181 * all data is available. Return nr of bytes read (0 if lost connection).
2182 * (only used by pSCP)
2184 int ssh_scp_recv(unsigned char *buf, int len)
2186 static int pending_input_len = 0;
2187 static unsigned char *pending_input_ptr;
2190 if (pending_input_len >= to_read) {
2191 memcpy(buf, pending_input_ptr, to_read);
2192 pending_input_ptr += to_read;
2193 pending_input_len -= to_read;
2197 if (pending_input_len > 0) {
2198 memcpy(buf, pending_input_ptr, pending_input_len);
2199 buf += pending_input_len;
2200 to_read -= pending_input_len;
2201 pending_input_len = 0;
2204 if (s == INVALID_SOCKET)
2206 while (to_read > 0) {
2208 if (s == INVALID_SOCKET)
2210 if (pktin.type == SSH1_SMSG_STDOUT_DATA) {
2211 int plen = GET_32BIT(pktin.body);
2212 if (plen <= to_read) {
2213 memcpy(buf, pktin.body + 4, plen);
2217 memcpy(buf, pktin.body + 4, to_read);
2218 pending_input_len = plen - to_read;
2219 pending_input_ptr = pktin.body + 4 + to_read;
2222 } else if (pktin.type == SSH1_SMSG_STDERR_DATA) {
2223 int plen = GET_32BIT(pktin.body);
2224 fwrite(pktin.body + 4, plen, 1, stderr);
2225 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2226 logevent("Received disconnect request");
2227 } else if (pktin.type == SSH1_SMSG_SUCCESS ||
2228 pktin.type == SSH1_SMSG_FAILURE) {
2230 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2232 sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
2234 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2235 logevent("Closing connection");
2239 fatalbox("Strange packet received: type %d", pktin.type);
2247 * Send a block of data over the SSH link.
2248 * Block until all data is sent.
2249 * (only used by pSCP)
2251 void ssh_scp_send(unsigned char *buf, int len)
2253 if (s == INVALID_SOCKET)
2255 send_packet(SSH1_CMSG_STDIN_DATA,
2256 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2260 * Send an EOF notification to the server.
2261 * (only used by pSCP)
2263 void ssh_scp_send_eof(void)
2265 if (s == INVALID_SOCKET)
2267 send_packet(SSH1_CMSG_EOF, PKT_END);
2271 * Set up the connection, login on the remote host and
2272 * start execution of a command.
2273 * Returns an error message, or NULL on success.
2274 * (only used by pSCP)
2276 char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
2281 if (crypto_startup() == 0)
2282 return "Microsoft high encryption pack not installed!";
2285 p = connect_to_host(host, port, realhost);
2292 return "Protocol initialisation error";
2294 /* Exchange keys and login */
2297 if (s == INVALID_SOCKET)
2298 return "Connection closed by remote host";
2299 } while (!do_ssh1_login(NULL, 0, 1));
2301 if (ssh_state == SSH_STATE_CLOSED) {
2304 return "Session initialisation error";
2307 /* Execute command */
2308 sprintf(buf, "Sending command: %.100s", cmd);
2310 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
2315 SOCKET ssh_socket(void) { return s; }
2317 Backend ssh_backend = {