18 #define logevent(s) { logevent(s); \
19 if (IS_SCP && (scp_flags & SCP_VERBOSE) != 0) \
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;
164 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
166 static char *savedhost;
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);
183 fatalbox("Lost connection while sending");
190 static int s_read (char *buf, int len) {
193 int i = recv (s, buf, len, 0);
197 len -= i, buf += i, ret += i;
204 static void c_write (char *buf, int len) {
206 if (len > 0 && buf[len-1] == '\n') len--;
207 if (len > 0 && buf[len-1] == '\r') len--;
208 if (len > 0) { fwrite(buf, len, 1, stderr); fputc('\n', stderr); }
224 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
225 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
227 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
228 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
229 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
230 static void ssh_size(void);
232 static int (*s_rdpkt)(unsigned char **data, int *datalen);
235 * Collect incoming data in the incoming packet buffer.
236 * Decipher and verify the packet when it is completely read.
237 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
238 * Update the *data and *datalen variables.
239 * Return the additional nr of bytes needed, or 0 when
240 * a complete packet is available.
242 static int ssh1_rdpkt(unsigned char **data, int *datalen)
244 static long len, pad, biglen, to_read;
245 static unsigned long realcrc, gotcrc;
246 static unsigned char *p;
256 for (i = len = 0; i < 4; i++) {
257 while ((*datalen) == 0)
259 len = (len << 8) + **data;
260 (*data)++, (*datalen)--;
264 if (len == 0x52656d6f) { /* "Remo"te server has closed ... */
265 len = 0x300; /* big enough to carry to end */
271 pktin.length = len - 5;
273 if (pktin.maxlen < biglen) {
274 pktin.maxlen = biglen;
275 pktin.data = (pktin.data == NULL ? malloc(biglen+APIEXTRA) :
276 realloc(pktin.data, biglen+APIEXTRA));
278 fatalbox("Out of memory");
283 while (to_read > 0) {
286 while ((*datalen) == 0)
288 if (chunk > (*datalen))
290 memcpy(p, *data, chunk);
298 cipher->decrypt(pktin.data, biglen);
300 pktin.type = pktin.data[pad];
301 pktin.body = pktin.data + pad + 1;
303 realcrc = crc32(pktin.data, biglen-4);
304 gotcrc = GET_32BIT(pktin.data+biglen-4);
305 if (gotcrc != realcrc) {
306 fatalbox("Incorrect CRC received on packet");
309 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
310 pktin.type == SSH1_SMSG_STDERR_DATA ||
311 pktin.type == SSH1_MSG_DEBUG ||
312 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE) {
313 long strlen = GET_32BIT(pktin.body);
314 if (strlen + 4 != pktin.length)
315 fatalbox("Received data packet with bogus string length");
318 if (pktin.type == SSH1_MSG_DEBUG) {
319 /* log debug message */
321 int strlen = GET_32BIT(pktin.body);
322 strcpy(buf, "Remote: ");
323 if (strlen > 70) strlen = 70;
324 memcpy(buf+8, pktin.body+4, strlen);
325 buf[8+strlen] = '\0';
328 } else if (pktin.type == SSH1_MSG_IGNORE) {
336 static int ssh2_rdpkt(unsigned char **data, int *datalen)
338 static long len, pad, payload, packetlen, maclen;
340 static int cipherblk;
341 static unsigned long incoming_sequence = 0;
351 cipherblk = cipher->blksize;
357 if (pktin.maxlen < cipherblk) {
358 pktin.maxlen = cipherblk;
359 pktin.data = (pktin.data == NULL ? malloc(cipherblk+APIEXTRA) :
360 realloc(pktin.data, cipherblk+APIEXTRA));
362 fatalbox("Out of memory");
366 * Acquire and decrypt the first block of the packet. This will
367 * contain the length and padding details.
369 for (i = len = 0; i < cipherblk; i++) {
370 while ((*datalen) == 0)
371 crReturn(cipherblk-i);
372 pktin.data[i] = *(*data)++;
376 if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
381 sccipher->decrypt(pktin.data, cipherblk);
384 * Now get the length and padding figures.
386 len = GET_32BIT(pktin.data);
390 * This enables us to deduce the payload length.
392 payload = len - pad - 1;
394 pktin.length = payload + 5;
397 * So now we can work out the total packet length.
400 maclen = scmac ? scmac->len : 0;
403 * Adjust memory allocation if packet is too big.
405 if (pktin.maxlen < packetlen) {
406 pktin.maxlen = packetlen;
407 pktin.data = (pktin.data == NULL ? malloc(packetlen+APIEXTRA) :
408 realloc(pktin.data, packetlen+APIEXTRA));
410 fatalbox("Out of memory");
414 * Read and decrypt the remainder of the packet.
416 for (i = cipherblk; i < packetlen + maclen; i++) {
417 while ((*datalen) == 0)
418 crReturn(packetlen + maclen - i);
419 pktin.data[i] = *(*data)++;
422 /* Decrypt everything _except_ the MAC. */
424 sccipher->decrypt(pktin.data + cipherblk, packetlen - cipherblk);
427 debug(("Got packet len=%d pad=%d\r\n", len, pad));
428 for (i = 0; i < packetlen; i++)
429 debug((" %02x", (unsigned char)pktin.data[i]));
436 if (scmac && !scmac->verify(pktin.data, len+4, incoming_sequence))
437 fatalbox("Incorrect MAC received on packet");
438 incoming_sequence++; /* whether or not we MACed */
441 pktin.type = pktin.data[5];
443 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
444 goto next_packet; /* FIXME: print DEBUG message */
449 static void ssh_gotdata(unsigned char *data, int datalen)
451 while (datalen > 0) {
452 if ( s_rdpkt(&data, &datalen) == 0 ) {
453 ssh_protocol(NULL, 0, 1);
454 if (ssh_state == SSH_STATE_CLOSED) {
462 static void s_wrpkt_start(int type, int len) {
465 len += 5; /* type and CRC */
469 pktout.length = len-5;
470 if (pktout.maxlen < biglen) {
471 pktout.maxlen = biglen;
473 /* Allocate enough buffer space for extra block
474 * for MS CryptEncrypt() */
475 pktout.data = (pktout.data == NULL ? malloc(biglen+12) :
476 realloc(pktout.data, biglen+12));
478 pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
479 realloc(pktout.data, biglen+4));
482 fatalbox("Out of memory");
486 pktout.body = pktout.data+4+pad+1;
489 static void s_wrpkt(void) {
490 int pad, len, biglen, i;
493 len = pktout.length + 5; /* type and CRC */
497 pktout.body[-1] = pktout.type;
498 for (i=0; i<pad; i++)
499 pktout.data[i+4] = random_byte();
500 crc = crc32(pktout.data+4, biglen-4);
501 PUT_32BIT(pktout.data+biglen, crc);
502 PUT_32BIT(pktout.data, len);
505 cipher->encrypt(pktout.data+4, biglen);
507 s_write(pktout.data, biglen+4);
511 * Construct a packet with the specified contents and
512 * send it to the server.
514 static void send_packet(int pkttype, ...)
517 unsigned char *p, *argp, argchar;
518 unsigned long argint;
519 int pktlen, argtype, arglen;
524 va_start(args, pkttype);
525 while ((argtype = va_arg(args, int)) != PKT_END) {
528 (void) va_arg(args, int);
532 (void) va_arg(args, char);
536 (void) va_arg(args, unsigned char *);
537 arglen = va_arg(args, int);
541 argp = va_arg(args, unsigned char *);
542 arglen = strlen(argp);
543 pktlen += 4 + arglen;
546 bn = va_arg(args, Bignum);
548 while ( i > 0 && (bn[i/16+1] >> (i%16)) == 0 )
550 pktlen += 2 + (i+7)/8;
558 s_wrpkt_start(pkttype, pktlen);
561 va_start(args, pkttype);
562 while ((argtype = va_arg(args, int)) != PKT_END) {
565 argint = va_arg(args, int);
566 PUT_32BIT(p, argint);
570 argchar = va_arg(args, unsigned char);
575 argp = va_arg(args, unsigned char *);
576 arglen = va_arg(args, int);
577 memcpy(p, argp, arglen);
581 argp = va_arg(args, unsigned char *);
582 arglen = strlen(argp);
583 PUT_32BIT(p, arglen);
584 memcpy(p + 4, argp, arglen);
588 bn = va_arg(args, Bignum);
590 while ( i > 0 && (bn[i/16+1] >> (i%16)) == 0 )
592 *p++ = (i >> 8) & 0xFF;
597 *p++ = bn[i/2+1] >> 8;
599 *p++ = bn[i/2+1] & 0xFF;
611 * Connect to specified host and port.
612 * Returns an error message, or NULL on success.
613 * Also places the canonical host name into `realhost'.
615 static char *connect_to_host(char *host, int port, char **realhost)
625 savedhost = malloc(1+strlen(host));
627 fatalbox("Out of memory");
628 strcpy(savedhost, host);
631 port = 22; /* default ssh port */
643 if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
644 if ( (h = gethostbyname(host)) == NULL)
645 switch (WSAGetLastError()) {
646 case WSAENETDOWN: return "Network is down";
647 case WSAHOST_NOT_FOUND: case WSANO_DATA:
648 return "Host does not exist";
649 case WSATRY_AGAIN: return "Host not found";
650 default: return "gethostbyname: unknown error";
652 memcpy (&a, h->h_addr, sizeof(a));
653 *realhost = h->h_name;
664 s = socket(AF_INET, SOCK_STREAM, 0);
665 if (s == INVALID_SOCKET)
666 switch (WSAGetLastError()) {
667 case WSAENETDOWN: return "Network is down";
668 case WSAEAFNOSUPPORT: return "TCP/IP support not present";
669 default: return "socket(): unknown error";
673 * Bind to local address.
675 addr.sin_family = AF_INET;
676 addr.sin_addr.s_addr = htonl(INADDR_ANY);
677 addr.sin_port = htons(0);
678 if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
679 switch (WSAGetLastError()) {
680 case WSAENETDOWN: return "Network is down";
681 default: return "bind(): unknown error";
685 * Connect to remote address.
687 addr.sin_addr.s_addr = htonl(a);
688 addr.sin_port = htons((short)port);
689 if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
690 switch (WSAGetLastError()) {
691 case WSAENETDOWN: return "Network is down";
692 case WSAECONNREFUSED: return "Connection refused";
693 case WSAENETUNREACH: return "Network is unreachable";
694 case WSAEHOSTUNREACH: return "No route to host";
695 default: return "connect(): unknown error";
699 send(s, "connect ", 8, 0);
700 send(s, FWhost, strlen(FWhost), 0);
703 sprintf(buf, " %d\n", FWport);
704 send (s, buf, strlen(buf), 0);
711 static int ssh_versioncmp(char *a, char *b) {
713 unsigned long av, bv;
715 av = strtoul(a, &ae, 10);
716 bv = strtoul(b, &be, 10);
717 if (av != bv) return (av < bv ? -1 : +1);
718 if (*ae == '.') ae++;
719 if (*be == '.') be++;
720 av = strtoul(ae, &ae, 10);
721 bv = strtoul(be, &be, 10);
722 if (av != bv) return (av < bv ? -1 : +1);
728 * Utility routine for putting an SSH-protocol `string' into a SHA
732 void sha_string(SHA_State *s, void *str, int len) {
733 unsigned char lenblk[4];
735 PUT_32BIT(lenblk, len);
736 if (!fp) fp = fopen("h:\\statham\\windows\\putty\\data","wb");
737 fwrite(lenblk, 4, 1, fp);
738 SHA_Bytes(s, lenblk, 4);
739 fwrite(str, len, 1, fp);
741 SHA_Bytes(s, str, len);
745 * SSH2 packet construction functions.
747 void ssh2_pkt_adddata(void *data, int len) {
748 pktout.length += len;
749 if (pktout.maxlen < pktout.length) {
750 pktout.maxlen = pktout.length + 256;
751 pktout.data = (pktout.data == NULL ? malloc(pktout.maxlen+APIEXTRA) :
752 realloc(pktout.data, pktout.maxlen+APIEXTRA));
754 fatalbox("Out of memory");
756 memcpy(pktout.data+pktout.length-len, data, len);
758 void ssh2_pkt_addbyte(unsigned char byte) {
759 ssh2_pkt_adddata(&byte, 1);
761 void ssh2_pkt_init(int pkt_type) {
763 ssh2_pkt_addbyte((unsigned char)pkt_type);
765 void ssh2_pkt_addbool(unsigned char value) {
766 ssh2_pkt_adddata(&value, 1);
768 void ssh2_pkt_adduint32(unsigned long value) {
771 ssh2_pkt_adddata(x, 4);
773 void ssh2_pkt_addstring_start(void) {
774 ssh2_pkt_adduint32(0);
775 pktout.savedpos = pktout.length;
777 void ssh2_pkt_addstring_str(char *data) {
778 ssh2_pkt_adddata(data, strlen(data));
779 PUT_32BIT(pktout.data + pktout.savedpos - 4,
780 pktout.length - pktout.savedpos);
782 void ssh2_pkt_addstring_data(char *data, int len) {
783 ssh2_pkt_adddata(data, len);
784 PUT_32BIT(pktout.data + pktout.savedpos - 4,
785 pktout.length - pktout.savedpos);
787 void ssh2_pkt_addstring(char *data) {
788 ssh2_pkt_addstring_start();
789 ssh2_pkt_addstring_str(data);
791 char *ssh2_mpint_fmt(Bignum b, int *len) {
794 p = malloc(n * 2 + 1);
796 fatalbox("out of memory");
798 for (i = 0; i < n; i++) {
799 p[i*2+1] = (b[n-i] >> 8) & 0xFF;
800 p[i*2+2] = (b[n-i] ) & 0xFF;
803 while (p[i] == 0 && (p[i+1] & 0x80) == 0)
805 memmove(p, p+i, n*2+1-i);
809 void ssh2_pkt_addmp(Bignum b) {
812 p = ssh2_mpint_fmt(b, &len);
813 ssh2_pkt_addstring_start();
814 ssh2_pkt_addstring_data(p, len);
817 void ssh2_pkt_send(void) {
818 int cipherblk, maclen, padding, i;
819 static unsigned long outgoing_sequence = 0;
822 * Add padding. At least four bytes, and must also bring total
823 * length (minus MAC) up to a multiple of the block size.
825 cipherblk = cipher ? cipher->blksize : 8; /* block size */
826 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
828 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
829 pktout.data[4] = padding;
830 for (i = 0; i < padding; i++)
831 pktout.data[pktout.length + i] = random_byte();
832 PUT_32BIT(pktout.data, pktout.length + padding - 4);
834 csmac->generate(pktout.data, pktout.length + padding,
836 outgoing_sequence++; /* whether or not we MACed */
839 debug(("Sending packet len=%d\r\n", pktout.length+padding));
840 for (i = 0; i < pktout.length+padding; i++)
841 debug((" %02x", (unsigned char)pktout.data[i]));
846 cscipher->encrypt(pktout.data, pktout.length + padding);
847 maclen = csmac ? csmac->len : 0;
849 s_write(pktout.data, pktout.length + padding + maclen);
853 void bndebug(char *string, Bignum b) {
856 p = ssh2_mpint_fmt(b, &len);
857 debug(("%s", string));
858 for (i = 0; i < len; i++)
859 debug((" %02x", p[i]));
865 void sha_mpint(SHA_State *s, Bignum b) {
868 p = ssh2_mpint_fmt(b, &len);
869 sha_string(s, p, len);
874 * SSH2 packet decode functions.
876 unsigned long ssh2_pkt_getuint32(void) {
878 if (pktin.length - pktin.savedpos < 4)
879 return 0; /* arrgh, no way to decline (FIXME?) */
880 value = GET_32BIT(pktin.data+pktin.savedpos);
884 void ssh2_pkt_getstring(char **p, int *length) {
886 if (pktin.length - pktin.savedpos < 4)
888 *length = GET_32BIT(pktin.data+pktin.savedpos);
890 if (pktin.length - pktin.savedpos < *length)
892 *p = pktin.data+pktin.savedpos;
893 pktin.savedpos += *length;
895 Bignum ssh2_pkt_getmp(void) {
900 ssh2_pkt_getstring(&p, &length);
904 fatalbox("internal error: Can't handle negative mpints");
905 b = newbn((length+1)/2);
906 for (i = 0; i < length; i++) {
909 b[j/2+1] |= ((unsigned char)p[i]) << 8;
911 b[j/2+1] |= ((unsigned char)p[i]);
916 static int do_ssh_init(void) {
920 char vlog[sizeof(vstring)+20];
925 while (s_read(&c, 1) == 1) {
926 if (c == 'S' && i < 2) i++;
927 else if (c == 'S' && i == 2) i = 2;
928 else if (c == 'H' && i == 2) break;
932 if (s_read(&c,1) != 1 || c != 'S') return 0;
933 if (s_read(&c,1) != 1 || c != 'S') return 0;
934 if (s_read(&c,1) != 1 || c != 'H') return 0;
936 strcpy(vstring, "SSH-");
938 if (s_read(&c,1) != 1 || c != '-') return 0;
941 if (s_read(&c,1) != 1)
943 if (vsp < vstring+sizeof(vstring)-1)
949 } else if (i < sizeof(version)-1)
957 sprintf(vlog, "Server version: %s", vstring);
958 vlog[strcspn(vlog, "\r\n")] = '\0';
961 if (ssh_versioncmp(version, "2.0" /* FIXME: "1.99" */ ) >= 0) {
963 * This is a v2 server. Begin v2 protocol.
965 char *verstring = "SSH-2.0-PuTTY";
968 * Hash our version string and their version string.
970 sha_string(&exhash, verstring, strlen(verstring));
971 sha_string(&exhash, vstring, strcspn(vstring, "\r\n"));
972 sprintf(vstring, "%s\n", verstring);
973 sprintf(vlog, "We claim version: %s", verstring);
975 logevent("Using SSH protocol version 2");
976 s_write(vstring, strlen(vstring));
977 ssh_protocol = ssh2_protocol;
978 s_rdpkt = ssh2_rdpkt;
981 * This is a v1 server. Begin v1 protocol.
983 sprintf(vstring, "SSH-%s-PuTTY\n",
984 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
985 sprintf(vlog, "We claim version: %s", vstring);
986 vlog[strcspn(vlog, "\r\n")] = '\0';
988 logevent("Using SSH protocol version 1");
989 s_write(vstring, strlen(vstring));
990 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 (!IS_SCP && !*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';
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 && IS_SCP) {
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 c_write("Trying public key authentication.\r\n", 35);
1246 if (!rsakey_encrypted(cfg.keyfile)) {
1247 c_write("No passphrase required.\r\n", 25);
1250 c_write("passphrase: ", 12);
1255 crWaitUntil(!ispkt);
1256 while (inlen--) switch (c = *in++) {
1273 if (((c >= ' ' && c <= '~') ||
1274 ((unsigned char)c >= 160)) && pos < sizeof(password))
1275 password[pos++] = c;
1284 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1286 * Try public key authentication with the specified
1289 static struct RSAKey pubkey;
1290 static Bignum challenge, response;
1292 static unsigned char buffer[32];
1294 tried_publickey = 1;
1295 i = loadrsakey(cfg.keyfile, &pubkey, password);
1297 c_write("Couldn't load public key from ", 30);
1298 c_write(cfg.keyfile, strlen(cfg.keyfile));
1299 c_write(".\r\n", 3);
1300 continue; /* go and try password */
1303 c_write("Wrong passphrase.\r\n", 19);
1304 tried_publickey = 0;
1305 continue; /* try again */
1309 * Send a public key attempt.
1311 send_packet(SSH1_CMSG_AUTH_RSA,
1312 PKT_BIGNUM, pubkey.modulus, PKT_END);
1315 if (pktin.type == SSH1_SMSG_FAILURE) {
1316 c_write("Server refused our public key.\r\n", 32);
1317 continue; /* go and try password */
1319 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE)
1320 fatalbox("Bizarre response to offer of public key");
1321 ssh1_read_bignum(pktin.body, &challenge);
1322 response = rsadecrypt(challenge, &pubkey);
1323 freebn(pubkey.private_exponent); /* burn the evidence */
1325 for (i = 0; i < 32; i += 2) {
1326 buffer[i] = response[16-i/2] >> 8;
1327 buffer[i+1] = response[16-i/2] & 0xFF;
1331 MD5Update(&md5c, buffer, 32);
1332 MD5Update(&md5c, session_id, 16);
1333 MD5Final(buffer, &md5c);
1335 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1336 PKT_DATA, buffer, 16, PKT_END);
1339 if (pktin.type == SSH1_SMSG_FAILURE) {
1340 c_write("Failed to authenticate with our public key.\r\n", 45);
1341 continue; /* go and try password */
1342 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1343 fatalbox("Bizarre response to RSA authentication response");
1346 break; /* we're through! */
1348 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1350 logevent("Sent password");
1351 memset(password, 0, strlen(password));
1353 if (pktin.type == SSH1_SMSG_FAILURE) {
1354 c_write("Access denied\r\n", 15);
1355 logevent("Authentication refused");
1356 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1357 logevent("Received disconnect request");
1358 ssh_state = SSH_STATE_CLOSED;
1360 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1361 fatalbox("Strange packet received, type %d", pktin.type);
1365 logevent("Authentication successful");
1370 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1375 while (!do_ssh1_login(in, inlen, ispkt)) {
1378 if (ssh_state == SSH_STATE_CLOSED)
1382 send_packet(SSH1_CMSG_REQUEST_PTY,
1383 PKT_STR, cfg.termtype,
1384 PKT_INT, rows, PKT_INT, cols,
1385 PKT_INT, 0, PKT_INT, 0,
1388 ssh_state = SSH_STATE_INTERMED;
1389 do { crReturnV; } while (!ispkt);
1390 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1391 fatalbox("Protocol confusion");
1392 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1393 c_write("Server refused to allocate pty\r\n", 32);
1395 logevent("Allocated pty");
1398 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1399 logevent("Started session");
1401 ssh_state = SSH_STATE_SESSION;
1408 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1409 pktin.type == SSH1_SMSG_STDERR_DATA) {
1410 long len = GET_32BIT(pktin.body);
1411 c_write(pktin.body+4, len);
1412 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1413 ssh_state = SSH_STATE_CLOSED;
1414 logevent("Received disconnect request");
1415 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
1416 /* may be from EXEC_SHELL on some servers */
1417 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1418 /* may be from EXEC_SHELL on some servers
1419 * if no pty is available or in other odd cases. Ignore */
1420 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1421 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
1423 fatalbox("Strange packet received: type %d", pktin.type);
1426 send_packet(SSH1_CMSG_STDIN_DATA,
1427 PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
1435 * Utility routine for decoding comma-separated strings in KEXINIT.
1437 int in_commasep_string(char *needle, char *haystack, int haylen) {
1438 int needlen = strlen(needle);
1441 * Is it at the start of the string?
1443 if (haylen >= needlen && /* haystack is long enough */
1444 !memcmp(needle, haystack, needlen) && /* initial match */
1445 (haylen == needlen || haystack[needlen] == ',')
1446 /* either , or EOS follows */
1450 * If not, search for the next comma and resume after that.
1451 * If no comma found, terminate.
1453 while (haylen > 0 && *haystack != ',')
1454 haylen--, haystack++;
1457 haylen--, haystack++; /* skip over comma itself */
1462 * SSH2 key creation method.
1464 void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1466 /* First 20 bytes. */
1469 SHA_Bytes(&s, H, 20);
1470 SHA_Bytes(&s, &chr, 1);
1471 SHA_Bytes(&s, H, 20);
1472 SHA_Final(&s, keyspace);
1473 /* Next 20 bytes. */
1476 SHA_Bytes(&s, H, 20);
1477 SHA_Bytes(&s, keyspace, 20);
1478 SHA_Final(&s, keyspace+20);
1482 * Handle the SSH2 transport layer.
1484 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
1488 static Bignum e, f, K;
1489 static struct ssh_cipher *cscipher_tobe = NULL;
1490 static struct ssh_cipher *sccipher_tobe = NULL;
1491 static struct ssh_mac *csmac_tobe = NULL;
1492 static struct ssh_mac *scmac_tobe = NULL;
1493 static struct ssh_compress *cscomp_tobe = NULL;
1494 static struct ssh_compress *sccomp_tobe = NULL;
1495 static char *hostkeydata, *sigdata, *keystr;
1496 static int hostkeylen, siglen;
1497 static unsigned char exchange_hash[20];
1498 static unsigned char keyspace[40];
1505 * Construct and send our key exchange packet.
1507 ssh2_pkt_init(SSH2_MSG_KEXINIT);
1508 for (i = 0; i < 16; i++)
1509 ssh2_pkt_addbyte((unsigned char)random_byte());
1510 /* List key exchange algorithms. */
1511 ssh2_pkt_addstring_start();
1512 for (i = 0; i < lenof(kex_algs); i++) {
1513 ssh2_pkt_addstring_str(kex_algs[i]->name);
1514 if (i < lenof(kex_algs)-1)
1515 ssh2_pkt_addstring_str(",");
1517 /* List server host key algorithms. */
1518 ssh2_pkt_addstring_start();
1519 for (i = 0; i < lenof(hostkey_algs); i++) {
1520 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1521 if (i < lenof(hostkey_algs)-1)
1522 ssh2_pkt_addstring_str(",");
1524 /* List client->server encryption algorithms. */
1525 ssh2_pkt_addstring_start();
1526 for (i = 0; i < lenof(ciphers); i++) {
1527 ssh2_pkt_addstring_str(ciphers[i]->name);
1528 if (i < lenof(ciphers)-1)
1529 ssh2_pkt_addstring_str(",");
1531 /* List server->client encryption algorithms. */
1532 ssh2_pkt_addstring_start();
1533 for (i = 0; i < lenof(ciphers); i++) {
1534 ssh2_pkt_addstring_str(ciphers[i]->name);
1535 if (i < lenof(ciphers)-1)
1536 ssh2_pkt_addstring_str(",");
1538 /* List client->server MAC algorithms. */
1539 ssh2_pkt_addstring_start();
1540 for (i = 0; i < lenof(macs); i++) {
1541 ssh2_pkt_addstring_str(macs[i]->name);
1542 if (i < lenof(macs)-1)
1543 ssh2_pkt_addstring_str(",");
1545 /* List server->client MAC algorithms. */
1546 ssh2_pkt_addstring_start();
1547 for (i = 0; i < lenof(macs); i++) {
1548 ssh2_pkt_addstring_str(macs[i]->name);
1549 if (i < lenof(macs)-1)
1550 ssh2_pkt_addstring_str(",");
1552 /* List client->server compression algorithms. */
1553 ssh2_pkt_addstring_start();
1554 for (i = 0; i < lenof(compressions); i++) {
1555 ssh2_pkt_addstring_str(compressions[i]->name);
1556 if (i < lenof(compressions)-1)
1557 ssh2_pkt_addstring_str(",");
1559 /* List server->client compression algorithms. */
1560 ssh2_pkt_addstring_start();
1561 for (i = 0; i < lenof(compressions); i++) {
1562 ssh2_pkt_addstring_str(compressions[i]->name);
1563 if (i < lenof(compressions)-1)
1564 ssh2_pkt_addstring_str(",");
1566 /* List client->server languages. Empty list. */
1567 ssh2_pkt_addstring_start();
1568 /* List server->client languages. Empty list. */
1569 ssh2_pkt_addstring_start();
1570 /* First KEX packet does _not_ follow, because we're not that brave. */
1571 ssh2_pkt_addbool(FALSE);
1573 ssh2_pkt_adduint32(0);
1574 sha_string(&exhash, pktout.data+5, pktout.length-5);
1577 if (!ispkt) crWaitUntil(ispkt);
1578 sha_string(&exhash, pktin.data+5, pktin.length-5);
1581 * Now examine the other side's KEXINIT to see what we're up
1584 if (pktin.type != SSH2_MSG_KEXINIT) {
1585 fatalbox("expected key exchange packet from server");
1587 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1588 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1589 pktin.savedpos += 16; /* skip garbage cookie */
1590 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
1591 for (i = 0; i < lenof(kex_algs); i++) {
1592 if (in_commasep_string(kex_algs[i]->name, str, len)) {
1597 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
1598 for (i = 0; i < lenof(hostkey_algs); i++) {
1599 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1600 hostkey = hostkey_algs[i];
1604 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
1605 for (i = 0; i < lenof(ciphers); i++) {
1606 if (in_commasep_string(ciphers[i]->name, str, len)) {
1607 cscipher_tobe = ciphers[i];
1611 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
1612 for (i = 0; i < lenof(ciphers); i++) {
1613 if (in_commasep_string(ciphers[i]->name, str, len)) {
1614 sccipher_tobe = ciphers[i];
1618 ssh2_pkt_getstring(&str, &len); /* client->server mac */
1619 for (i = 0; i < lenof(macs); i++) {
1620 if (in_commasep_string(macs[i]->name, str, len)) {
1621 csmac_tobe = macs[i];
1625 ssh2_pkt_getstring(&str, &len); /* server->client mac */
1626 for (i = 0; i < lenof(macs); i++) {
1627 if (in_commasep_string(macs[i]->name, str, len)) {
1628 scmac_tobe = macs[i];
1632 ssh2_pkt_getstring(&str, &len); /* client->server compression */
1633 for (i = 0; i < lenof(compressions); i++) {
1634 if (in_commasep_string(compressions[i]->name, str, len)) {
1635 cscomp_tobe = compressions[i];
1639 ssh2_pkt_getstring(&str, &len); /* server->client compression */
1640 for (i = 0; i < lenof(compressions); i++) {
1641 if (in_commasep_string(compressions[i]->name, str, len)) {
1642 sccomp_tobe = compressions[i];
1648 * Currently we only support Diffie-Hellman and DSS, so let's
1649 * bomb out if those aren't selected.
1651 if (kex != &ssh_diffiehellman || hostkey != &ssh_dss)
1652 fatalbox("internal fault: chaos in SSH 2 transport layer");
1655 * Now we begin the fun. Generate and send e for Diffie-Hellman.
1658 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
1663 if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
1664 fatalbox("expected key exchange packet from server");
1666 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
1667 f = ssh2_pkt_getmp();
1668 ssh2_pkt_getstring(&sigdata, &siglen);
1672 sha_string(&exhash, hostkeydata, hostkeylen);
1673 sha_mpint(&exhash, e);
1674 sha_mpint(&exhash, f);
1675 sha_mpint(&exhash, K);
1676 SHA_Final(&exhash, exchange_hash);
1679 debug(("Exchange hash is:\r\n"));
1680 for (i = 0; i < 20; i++)
1681 debug((" %02x", exchange_hash[i]));
1685 hostkey->setkey(hostkeydata, hostkeylen);
1686 if (!hostkey->verifysig(sigdata, siglen, exchange_hash, 20))
1687 fatalbox("Server failed host key check");
1690 * Expect SSH2_MSG_NEWKEYS from server.
1693 if (pktin.type != SSH2_MSG_NEWKEYS)
1694 fatalbox("expected new-keys packet from server");
1697 * Authenticate remote host: verify host key. (We've already
1698 * checked the signature of the exchange hash.)
1700 keystr = hostkey->fmtkey();
1701 verify_ssh_host_key(savedhost, keystr);
1705 * Send SSH2_MSG_NEWKEYS.
1707 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
1711 * Create and initialise session keys.
1713 cscipher = cscipher_tobe;
1714 sccipher = sccipher_tobe;
1717 cscomp = cscomp_tobe;
1718 sccomp = sccomp_tobe;
1720 * Set IVs after keys.
1722 ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
1723 ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
1724 ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
1725 ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
1726 ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
1727 ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
1730 * Now we're encrypting. Begin returning 1 to the protocol main
1731 * function so that other things can run on top of the
1732 * transport. If we ever see a KEXINIT, we must go back to the
1737 } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
1738 goto begin_key_exchange;
1744 * Handle the SSH2 userauth and connection layers.
1746 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
1748 static unsigned long their_channel;
1749 static unsigned long remote_winsize;
1750 static unsigned long remote_maxpkt;
1755 * Request userauth protocol, and await a response to it.
1757 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
1758 ssh2_pkt_addstring("ssh-userauth");
1760 crWaitUntilV(ispkt);
1761 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT)
1762 fatalbox("Server refused user authentication protocol");
1765 * FIXME: currently we support only password authentication.
1766 * (This places us technically in violation of the SSH2 spec.
1767 * We must fix this.)
1771 * Get a username and a password.
1773 static char username[100];
1774 static char password[100];
1778 if (!IS_SCP && !*cfg.username) {
1779 c_write("login as: ", 10);
1781 crWaitUntilV(!ispkt);
1782 while (inlen--) switch (c = *in++) {
1789 c_write("\b \b", 3);
1795 c_write("\b \b", 3);
1804 if (((c >= ' ' && c <= '~') ||
1805 ((unsigned char)c >= 160)) && pos < 40) {
1806 username[pos++] = c;
1813 username[strcspn(username, "\n\r")] = '\0';
1816 strncpy(username, cfg.username, 99);
1817 username[99] = '\0';
1819 sprintf(stuff, "Using username \"%s\".\r\n", username);
1820 c_write(stuff, strlen(stuff));
1826 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
1827 if (!ssh_get_password(prompt, password, sizeof(password))) {
1829 * get_password failed to get a password (for
1830 * example because one was supplied on the command
1831 * line which has already failed to work).
1834 logevent("No more passwords to try");
1835 ssh_state = SSH_STATE_CLOSED;
1839 c_write("password: ", 10);
1843 crWaitUntilV(!ispkt);
1844 while (inlen--) switch (c = *in++) {
1861 if (((c >= ' ' && c <= '~') ||
1862 ((unsigned char)c >= 160)) && pos < 40)
1863 password[pos++] = c;
1870 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
1871 ssh2_pkt_addstring(username);
1872 ssh2_pkt_addstring("ssh-connection"); /* service requested */
1873 ssh2_pkt_addstring("password");
1874 ssh2_pkt_addbool(FALSE);
1875 ssh2_pkt_addstring(password);
1878 crWaitUntilV(ispkt);
1879 if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
1880 c_write("Access denied\r\n", 15);
1881 logevent("Authentication refused");
1887 * Now we're authenticated for the connection protocol. The
1888 * connection protocol will automatically have started at this
1889 * point; there's no need to send SERVICE_REQUEST.
1893 * So now create a channel with a session in it.
1895 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
1896 ssh2_pkt_addstring("session");
1897 ssh2_pkt_adduint32(100); /* as good as any */
1898 ssh2_pkt_adduint32(0xFFFFFFFFUL); /* very big window which we ignore */
1899 ssh2_pkt_adduint32(0xFFFFFFFFUL); /* very big max pkt size */
1901 crWaitUntilV(ispkt);
1902 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
1903 fatalbox("Server refused to open a session");
1904 /* FIXME: error data comes back in FAILURE packet */
1906 if (ssh2_pkt_getuint32() != 100) {
1907 fatalbox("Server's channel confirmation cited wrong channel");
1909 their_channel = ssh2_pkt_getuint32();
1910 remote_winsize = ssh2_pkt_getuint32();
1911 remote_maxpkt = ssh2_pkt_getuint32();
1912 logevent("Opened channel for session");
1915 * Now allocate a pty for the session.
1917 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
1918 ssh2_pkt_adduint32(their_channel); /* recipient channel */
1919 ssh2_pkt_addstring("pty-req");
1920 ssh2_pkt_addbool(1); /* want reply */
1921 ssh2_pkt_addstring(cfg.termtype);
1922 ssh2_pkt_adduint32(cols);
1923 ssh2_pkt_adduint32(rows);
1924 ssh2_pkt_adduint32(0); /* pixel width */
1925 ssh2_pkt_adduint32(0); /* pixel height */
1926 ssh2_pkt_addstring_start();
1927 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
1930 do { /* FIXME: pay attention to these */
1931 crWaitUntilV(ispkt);
1932 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1934 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
1935 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
1936 fatalbox("Server got confused by pty request");
1938 c_write("Server refused to allocate pty\r\n", 32);
1940 logevent("Allocated pty");
1946 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
1947 ssh2_pkt_adduint32(their_channel); /* recipient channel */
1948 ssh2_pkt_addstring("shell");
1949 ssh2_pkt_addbool(1); /* want reply */
1951 do { /* FIXME: pay attention to these */
1952 crWaitUntilV(ispkt);
1953 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1954 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
1955 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
1956 fatalbox("Server got confused by shell request");
1958 fatalbox("Server refused to start a shell");
1960 logevent("Started a shell");
1969 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
1970 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1973 if (ssh2_pkt_getuint32() != 100)
1974 continue; /* wrong channel */
1975 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
1976 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
1977 continue; /* extended but not stderr */
1978 ssh2_pkt_getstring(&data, &length);
1980 c_write(data, length);
1981 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
1982 ssh_state = SSH_STATE_CLOSED;
1983 logevent("Received disconnect request");
1984 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
1985 continue; /* exit status et al; ignore (FIXME?) */
1986 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
1987 continue; /* ignore for now (FIXME!) */
1989 fatalbox("Strange packet received: type %d", pktin.type);
1992 /* FIXME: for now, ignore window size */
1993 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
1994 ssh2_pkt_adduint32(their_channel);
1995 ssh2_pkt_addstring_start();
1996 ssh2_pkt_addstring_data(in, inlen);
2005 * Handle the top-level SSH2 protocol.
2007 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2009 if (do_ssh2_transport(in, inlen, ispkt) == 0)
2011 do_ssh2_authconn(in, inlen, ispkt);
2015 * Called to set up the connection. Will arrange for WM_NETEVENT
2016 * messages to be passed to the specified window, whose window
2017 * procedure should then call telnet_msg().
2019 * Returns an error message, or NULL on success.
2021 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
2025 if(crypto_startup() == 0)
2026 return "Microsoft high encryption pack not installed!";
2029 p = connect_to_host(host, port, realhost);
2034 return "Protocol initialisation error";
2036 if (WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
2037 switch (WSAGetLastError()) {
2038 case WSAENETDOWN: return "Network is down";
2039 default: return "WSAAsyncSelect(): unknown error";
2046 * Process a WM_NETEVENT message. Will return 0 if the connection
2047 * has closed, or <0 for a socket error.
2049 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
2054 * Because reading less than the whole of the available pending
2055 * data can generate an FD_READ event, we need to allow for the
2056 * possibility that FD_READ may arrive with FD_CLOSE already in
2057 * the queue; so it's possible that we can get here even with s
2058 * invalid. If so, we return 1 and don't worry about it.
2060 if (s == INVALID_SOCKET)
2063 if (WSAGETSELECTERROR(lParam) != 0)
2064 return -WSAGETSELECTERROR(lParam);
2066 switch (WSAGETSELECTEVENT(lParam)) {
2069 ret = recv(s, buf, sizeof(buf), 0);
2070 if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
2072 if (ret < 0) /* any _other_ error */
2073 return -10000-WSAGetLastError();
2078 ssh_gotdata (buf, ret);
2079 if (ssh_state == SSH_STATE_CLOSED) {
2086 return 1; /* shouldn't happen, but WTF */
2090 * Called to send data down the Telnet connection.
2092 static void ssh_send (char *buf, int len) {
2093 if (s == INVALID_SOCKET)
2096 ssh_protocol(buf, len, 0);
2100 * Called to set the size of the window from Telnet's POV.
2102 static void ssh_size(void) {
2103 switch (ssh_state) {
2104 case SSH_STATE_BEFORE_SIZE:
2105 case SSH_STATE_CLOSED:
2106 break; /* do nothing */
2107 case SSH_STATE_INTERMED:
2108 size_needed = TRUE; /* buffer for later */
2110 case SSH_STATE_SESSION:
2112 send_packet(SSH1_CMSG_WINDOW_SIZE,
2113 PKT_INT, rows, PKT_INT, cols,
2114 PKT_INT, 0, PKT_INT, 0, PKT_END);
2120 * (Send Telnet special codes)
2122 static void ssh_special (Telnet_Special code) {
2128 * Read and decrypt one incoming SSH packet.
2129 * (only used by pSCP)
2131 static void get_packet(void)
2133 unsigned char buf[4096], *p;
2142 while ((to_read = s_rdpkt(&p, &len)) > 0) {
2143 if (to_read > sizeof(buf)) to_read = sizeof(buf);
2144 len = s_read(buf, to_read);
2145 if (len != to_read) {
2157 * Receive a block of data over the SSH link. Block until
2158 * all data is available. Return nr of bytes read (0 if lost connection).
2159 * (only used by pSCP)
2161 int ssh_scp_recv(unsigned char *buf, int len)
2163 static int pending_input_len = 0;
2164 static unsigned char *pending_input_ptr;
2169 if (pending_input_len >= to_read) {
2170 memcpy(buf, pending_input_ptr, to_read);
2171 pending_input_ptr += to_read;
2172 pending_input_len -= to_read;
2176 if (pending_input_len > 0) {
2177 memcpy(buf, pending_input_ptr, pending_input_len);
2178 buf += pending_input_len;
2179 to_read -= pending_input_len;
2180 pending_input_len = 0;
2183 if (s == INVALID_SOCKET)
2185 while (to_read > 0) {
2187 if (s == INVALID_SOCKET)
2189 if (pktin.type == SSH1_SMSG_STDOUT_DATA) {
2190 int plen = GET_32BIT(pktin.body);
2191 if (plen <= to_read) {
2192 memcpy(buf, pktin.body + 4, plen);
2196 memcpy(buf, pktin.body + 4, to_read);
2197 pending_input_len = plen - to_read;
2198 pending_input_ptr = pktin.body + 4 + to_read;
2201 } else if (pktin.type == SSH1_SMSG_STDERR_DATA) {
2202 int plen = GET_32BIT(pktin.body);
2203 fwrite(pktin.body + 4, plen, 1, stderr);
2204 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2205 logevent("Received disconnect request");
2206 } else if (pktin.type == SSH1_SMSG_SUCCESS ||
2207 pktin.type == SSH1_SMSG_FAILURE) {
2209 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2211 sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
2213 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2214 logevent("Closing connection");
2218 fatalbox("Strange packet received: type %d", pktin.type);
2226 * Send a block of data over the SSH link.
2227 * Block until all data is sent.
2228 * (only used by pSCP)
2230 void ssh_scp_send(unsigned char *buf, int len)
2233 if (s == INVALID_SOCKET)
2235 send_packet(SSH1_CMSG_STDIN_DATA,
2236 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2240 * Send an EOF notification to the server.
2241 * (only used by pSCP)
2243 void ssh_scp_send_eof(void)
2246 if (s == INVALID_SOCKET)
2248 send_packet(SSH1_CMSG_EOF, PKT_END);
2252 * Set up the connection, login on the remote host and
2253 * start execution of a command.
2254 * Returns an error message, or NULL on success.
2255 * (only used by pSCP)
2257 char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
2264 if (crypto_startup() == 0)
2265 return "Microsoft high encryption pack not installed!";
2268 p = connect_to_host(host, port, realhost);
2275 return "Protocol initialisation error";
2277 /* Exchange keys and login */
2280 if (s == INVALID_SOCKET)
2281 return "Connection closed by remote host";
2282 } while (!do_ssh1_login(NULL, 0, 1));
2284 if (ssh_state == SSH_STATE_CLOSED) {
2287 return "Session initialisation error";
2290 /* Execute command */
2291 sprintf(buf, "Sending command: %.100s", cmd);
2293 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
2299 Backend ssh_backend = {