]> asedeno.scripts.mit.edu Git - PuTTY_svn.git/blob - ssh.c
8a483f8bd8215f5a99b5b36d8a07f358df4c8109
[PuTTY_svn.git] / ssh.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4 #include <assert.h>
5 #include <winsock.h>
6
7 #include "putty.h"
8 #include "ssh.h"
9 #include "scp.h"
10
11 #ifndef FALSE
12 #define FALSE 0
13 #endif
14 #ifndef TRUE
15 #define TRUE 1
16 #endif
17
18 #define logevent(s) { logevent(s); \
19                       if (IS_SCP && (scp_flags & SCP_VERBOSE) != 0) \
20                       fprintf(stderr, "%s\n", s); }
21
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_PASSWORD 9
27 #define SSH1_CMSG_REQUEST_PTY   10
28 #define SSH1_CMSG_WINDOW_SIZE   11
29 #define SSH1_CMSG_EXEC_SHELL    12
30 #define SSH1_CMSG_EXEC_CMD      13
31 #define SSH1_SMSG_SUCCESS       14
32 #define SSH1_SMSG_FAILURE       15
33 #define SSH1_CMSG_STDIN_DATA    16
34 #define SSH1_SMSG_STDOUT_DATA   17
35 #define SSH1_SMSG_STDERR_DATA   18
36 #define SSH1_CMSG_EOF           19
37 #define SSH1_SMSG_EXIT_STATUS   20
38 #define SSH1_CMSG_EXIT_CONFIRMATION     33
39 #define SSH1_MSG_IGNORE         32
40 #define SSH1_MSG_DEBUG          36
41 #define SSH1_CMSG_AUTH_TIS      39
42 #define SSH1_SMSG_AUTH_TIS_CHALLENGE    40
43 #define SSH1_CMSG_AUTH_TIS_RESPONSE     41
44
45 #define SSH1_AUTH_TIS           5
46
47 #define SSH2_MSG_DISCONNECT             1
48 #define SSH2_MSG_IGNORE                 2
49 #define SSH2_MSG_UNIMPLEMENTED          3
50 #define SSH2_MSG_DEBUG                  4
51 #define SSH2_MSG_SERVICE_REQUEST        5
52 #define SSH2_MSG_SERVICE_ACCEPT         6
53 #define SSH2_MSG_KEXINIT                20
54 #define SSH2_MSG_NEWKEYS                21
55 #define SSH2_MSG_KEXDH_INIT             30
56 #define SSH2_MSG_KEXDH_REPLY            31
57
58 #define GET_32BIT(cp) \
59     (((unsigned long)(unsigned char)(cp)[0] << 24) | \
60     ((unsigned long)(unsigned char)(cp)[1] << 16) | \
61     ((unsigned long)(unsigned char)(cp)[2] << 8) | \
62     ((unsigned long)(unsigned char)(cp)[3]))
63
64 #define PUT_32BIT(cp, value) { \
65     (cp)[0] = (unsigned char)((value) >> 24); \
66     (cp)[1] = (unsigned char)((value) >> 16); \
67     (cp)[2] = (unsigned char)((value) >> 8); \
68     (cp)[3] = (unsigned char)(value); }
69
70 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR };
71
72 /* Coroutine mechanics for the sillier bits of the code */
73 #define crBegin1        static int crLine = 0;
74 #define crBegin2        switch(crLine) { case 0:;
75 #define crBegin         crBegin1; crBegin2;
76 #define crFinish(z)     } crLine = 0; return (z)
77 #define crFinishV       } crLine = 0; return
78 #define crReturn(z)     \
79         do {\
80             crLine=__LINE__; return (z); case __LINE__:;\
81         } while (0)
82 #define crReturnV       \
83         do {\
84             crLine=__LINE__; return; case __LINE__:;\
85         } while (0)
86 #define crStop(z)       do{ crLine = 0; return (z); }while(0)
87 #define crStopV         do{ crLine = 0; return; }while(0)
88 #define crWaitUntil(c)  do { crReturn(0); } while (!(c))
89
90 extern struct ssh_cipher ssh_3des;
91 extern struct ssh_cipher ssh_des;
92 extern struct ssh_cipher ssh_blowfish;
93
94 /* for ssh 2; we miss out single-DES because it isn't supported */
95 struct ssh_cipher *ciphers[] = { &ssh_3des, &ssh_blowfish };
96
97 extern struct ssh_kex ssh_diffiehellman;
98 struct ssh_kex *kex_algs[] = { &ssh_diffiehellman };
99
100 extern struct ssh_hostkey ssh_dss;
101 struct ssh_hostkey *hostkey_algs[] = { &ssh_dss };
102
103 extern struct ssh_mac ssh_sha1;
104
105 SHA_State exhash;
106
107 static void nullmac_key(unsigned char *key) { }
108 static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
109 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
110 struct ssh_mac ssh_mac_none = {
111     nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
112 };
113 struct ssh_mac *macs[] = { &ssh_sha1, &ssh_mac_none };
114
115 struct ssh_compress ssh_comp_none = {
116     "none"
117 };
118 struct ssh_compress *compressions[] = { &ssh_comp_none };
119
120 static SOCKET s = INVALID_SOCKET;
121
122 static unsigned char session_key[32];
123 static struct ssh_cipher *cipher = NULL;
124 static struct ssh_cipher *cscipher = NULL;
125 static struct ssh_cipher *sccipher = NULL;
126 static struct ssh_mac *csmac = NULL;
127 static struct ssh_mac *scmac = NULL;
128 static struct ssh_compress *cscomp = NULL;
129 static struct ssh_compress *sccomp = NULL;
130 static struct ssh_kex *kex = NULL;
131 static struct ssh_hostkey *hostkey = NULL;
132 int scp_flags = 0;
133 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
134
135 static char *savedhost;
136
137 static enum {
138     SSH_STATE_BEFORE_SIZE,
139     SSH_STATE_INTERMED,
140     SSH_STATE_SESSION,
141     SSH_STATE_CLOSED
142 } ssh_state = SSH_STATE_BEFORE_SIZE;
143
144 static int size_needed = FALSE;
145
146 static void s_write (char *buf, int len) {
147     while (len > 0) {
148         int i = send (s, buf, len, 0);
149         if (IS_SCP) {
150             noise_ultralight(i);
151             if (i <= 0)
152                 fatalbox("Lost connection while sending");
153         }
154         if (i > 0)
155             len -= i, buf += i;
156     }
157 }
158
159 static int s_read (char *buf, int len) {
160     int ret = 0;
161     while (len > 0) {
162         int i = recv (s, buf, len, 0);
163         if (IS_SCP)
164             noise_ultralight(i);
165         if (i > 0)
166             len -= i, buf += i, ret += i;
167         else
168             return i;
169     }
170     return ret;
171 }
172
173 static void c_write (char *buf, int len) {
174     if (IS_SCP) {
175         if (len > 0 && buf[len-1] == '\n') len--;
176         if (len > 0 && buf[len-1] == '\r') len--;
177         if (len > 0) { fwrite(buf, len, 1, stderr); fputc('\n', stderr); }
178         return;
179     }
180     while (len--) 
181         c_write1(*buf++);
182 }
183
184 struct Packet {
185     long length;
186     int type;
187     unsigned char *data;
188     unsigned char *body;
189     long savedpos;
190     long maxlen;
191 };
192
193 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
194 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
195
196 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
197 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
198 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
199 static void ssh_size(void);
200
201 static int (*s_rdpkt)(unsigned char **data, int *datalen);
202
203 /*
204  * Collect incoming data in the incoming packet buffer.
205  * Decipher and verify the packet when it is completely read.
206  * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
207  * Update the *data and *datalen variables.
208  * Return the additional nr of bytes needed, or 0 when
209  * a complete packet is available.
210  */
211 static int ssh1_rdpkt(unsigned char **data, int *datalen)
212 {
213     static long len, pad, biglen, to_read;
214     static unsigned long realcrc, gotcrc;
215     static unsigned char *p;
216     static int i;
217
218     crBegin;
219
220 next_packet:
221
222     pktin.type = 0;
223     pktin.length = 0;
224
225     for (i = len = 0; i < 4; i++) {
226         while ((*datalen) == 0)
227             crReturn(4-i);
228         len = (len << 8) + **data;
229         (*data)++, (*datalen)--;
230     }
231
232 #ifdef FWHACK
233     if (len == 0x52656d6f) {       /* "Remo"te server has closed ... */
234         len = 0x300;               /* big enough to carry to end */
235     }
236 #endif
237
238     pad = 8 - (len % 8);
239     biglen = len + pad;
240     pktin.length = len - 5;
241
242     if (pktin.maxlen < biglen) {
243         pktin.maxlen = biglen;
244         pktin.data = (pktin.data == NULL ? malloc(biglen+APIEXTRA) :
245                       realloc(pktin.data, biglen+APIEXTRA));
246         if (!pktin.data)
247             fatalbox("Out of memory");
248     }
249
250     to_read = biglen;
251     p = pktin.data;
252     while (to_read > 0) {
253         static int chunk;
254         chunk = to_read;
255         while ((*datalen) == 0)
256             crReturn(to_read);
257         if (chunk > (*datalen))
258             chunk = (*datalen);
259         memcpy(p, *data, chunk);
260         *data += chunk;
261         *datalen -= chunk;
262         p += chunk;
263         to_read -= chunk;
264     }
265
266     if (cipher)
267         cipher->decrypt(pktin.data, biglen);
268
269     pktin.type = pktin.data[pad];
270     pktin.body = pktin.data + pad + 1;
271
272     realcrc = crc32(pktin.data, biglen-4);
273     gotcrc = GET_32BIT(pktin.data+biglen-4);
274     if (gotcrc != realcrc) {
275         fatalbox("Incorrect CRC received on packet");
276     }
277
278     if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
279         pktin.type == SSH1_SMSG_STDERR_DATA ||
280         pktin.type == SSH1_MSG_DEBUG ||
281         pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE) {
282         long strlen = GET_32BIT(pktin.body);
283         if (strlen + 4 != pktin.length)
284             fatalbox("Received data packet with bogus string length");
285     }
286
287     if (pktin.type == SSH1_MSG_DEBUG) {
288         /* log debug message */
289         char buf[80];
290         int strlen = GET_32BIT(pktin.body);
291         strcpy(buf, "Remote: ");
292         if (strlen > 70) strlen = 70;
293         memcpy(buf+8, pktin.body+4, strlen);
294         buf[8+strlen] = '\0';
295         logevent(buf);
296         goto next_packet;
297     } else if (pktin.type == SSH1_MSG_IGNORE) {
298         /* do nothing */
299         goto next_packet;
300     }
301
302     crFinish(0);
303 }
304
305 static int ssh2_rdpkt(unsigned char **data, int *datalen)
306 {
307     static long len, pad, payload, packetlen, maclen;
308     static int i;
309     static int cipherblk;
310     static unsigned long incoming_sequence = 0;
311
312     crBegin;
313
314 next_packet:
315
316     pktin.type = 0;
317     pktin.length = 0;
318
319     if (cipher)
320         cipherblk = cipher->blksize;
321     else
322         cipherblk = 8;
323     if (cipherblk < 8)
324         cipherblk = 8;
325
326     if (pktin.maxlen < cipherblk) {
327         pktin.maxlen = cipherblk;
328         pktin.data = (pktin.data == NULL ? malloc(cipherblk+APIEXTRA) :
329                       realloc(pktin.data, cipherblk+APIEXTRA));
330         if (!pktin.data)
331             fatalbox("Out of memory");
332     }
333
334     /*
335      * Acquire and decrypt the first block of the packet. This will
336      * contain the length and padding details.
337      */
338      for (i = len = 0; i < cipherblk; i++) {
339         while ((*datalen) == 0)
340             crReturn(cipherblk-i);
341         pktin.data[i] = *(*data)++;
342         (*datalen)--;
343     }
344 #ifdef FWHACK
345     if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
346         /* FIXME */
347     }
348 #endif
349     debug(("Got initblk:"));
350     for (i = 0; i < cipherblk; i++)
351         debug(("  %02x", (unsigned char)pktin.data[i]));
352     debug(("\r\n"));
353     if (sccipher)
354         sccipher->decrypt(pktin.data, cipherblk);
355     debug(("Decrypted initblk:"));
356     for (i = 0; i < cipherblk; i++)
357         debug(("  %02x", (unsigned char)pktin.data[i]));
358     debug(("\r\n"));
359
360     /*
361      * Now get the length and padding figures.
362      */
363     len = GET_32BIT(pktin.data);
364     pad = pktin.data[4];
365
366     /*
367      * This enables us to deduce the payload length.
368      */
369     payload = len - pad - 1;
370
371     pktin.length = payload + 5;
372
373     /*
374      * So now we can work out the total packet length.
375      */
376     packetlen = len + 4;
377     maclen = scmac ? scmac->len : 0;
378
379     /*
380      * Adjust memory allocation if packet is too big.
381      */
382     if (pktin.maxlen < packetlen) {
383         pktin.maxlen = packetlen;
384         pktin.data = (pktin.data == NULL ? malloc(packetlen+APIEXTRA) :
385                       realloc(pktin.data, packetlen+APIEXTRA));
386         if (!pktin.data)
387             fatalbox("Out of memory");
388     }
389
390     /*
391      * Read and decrypt the remainder of the packet.
392      */
393     for (i = cipherblk; i < packetlen + maclen; i++) {
394         while ((*datalen) == 0)
395             crReturn(packetlen + maclen - i);
396         pktin.data[i] = *(*data)++;
397         (*datalen)--;
398     }
399     /* Decrypt everything _except_ the MAC. */
400     if (sccipher)
401         sccipher->decrypt(pktin.data + cipherblk, packetlen - cipherblk);
402
403     debug(("Got packet len=%d pad=%d\r\n", len, pad));
404     for (i = 0; i < packetlen; i++)
405         debug(("  %02x", (unsigned char)pktin.data[i]));
406     debug(("\r\n"));
407
408     /*
409      * Check the MAC.
410      */
411     if (scmac && !scmac->verify(pktin.data, incoming_sequence++, len+4))
412         fatalbox("Incorrect MAC received on packet");
413
414     pktin.savedpos = 6;
415     pktin.type = pktin.data[5];
416
417     /*
418      * FIXME: handle IGNORE and DEBUG messages.
419      */
420
421     crFinish(0);
422 }
423
424 static void ssh_gotdata(unsigned char *data, int datalen)
425 {
426     while (datalen > 0) {
427         if ( s_rdpkt(&data, &datalen) == 0 ) {
428             ssh_protocol(NULL, 0, 1);
429             if (ssh_state == SSH_STATE_CLOSED) {
430                 return;
431             }
432         }
433     }
434 }
435
436
437 static void s_wrpkt_start(int type, int len) {
438     int pad, biglen;
439
440     len += 5;                          /* type and CRC */
441     pad = 8 - (len%8);
442     biglen = len + pad;
443
444     pktout.length = len-5;
445     if (pktout.maxlen < biglen) {
446         pktout.maxlen = biglen;
447 #ifdef MSCRYPTOAPI
448         /* Allocate enough buffer space for extra block
449          * for MS CryptEncrypt() */
450         pktout.data = (pktout.data == NULL ? malloc(biglen+12) :
451                        realloc(pktout.data, biglen+12));
452 #else
453         pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
454                        realloc(pktout.data, biglen+4));
455 #endif
456         if (!pktout.data)
457             fatalbox("Out of memory");
458     }
459
460     pktout.type = type;
461     pktout.body = pktout.data+4+pad+1;
462 }
463
464 static void s_wrpkt(void) {
465     int pad, len, biglen, i;
466     unsigned long crc;
467
468     len = pktout.length + 5;           /* type and CRC */
469     pad = 8 - (len%8);
470     biglen = len + pad;
471
472     pktout.body[-1] = pktout.type;
473     for (i=0; i<pad; i++)
474         pktout.data[i+4] = random_byte();
475     crc = crc32(pktout.data+4, biglen-4);
476     PUT_32BIT(pktout.data+biglen, crc);
477     PUT_32BIT(pktout.data, len);
478
479     if (cipher)
480         cipher->encrypt(pktout.data+4, biglen);
481
482     s_write(pktout.data, biglen+4);
483 }
484
485 /*
486  * Construct a packet with the specified contents and
487  * send it to the server.
488  */
489 static void send_packet(int pkttype, ...)
490 {
491     va_list args;
492     unsigned char *p, *argp, argchar;
493     unsigned long argint;
494     int pktlen, argtype, arglen;
495
496     pktlen = 0;
497     va_start(args, pkttype);
498     while ((argtype = va_arg(args, int)) != PKT_END) {
499         switch (argtype) {
500           case PKT_INT:
501             (void) va_arg(args, int);
502             pktlen += 4;
503             break;
504           case PKT_CHAR:
505             (void) va_arg(args, char);
506             pktlen++;
507             break;
508           case PKT_DATA:
509             (void) va_arg(args, unsigned char *);
510             arglen = va_arg(args, int);
511             pktlen += arglen;
512             break;
513           case PKT_STR:
514             argp = va_arg(args, unsigned char *);
515             arglen = strlen(argp);
516             pktlen += 4 + arglen;
517             break;
518           default:
519             assert(0);
520         }
521     }
522     va_end(args);
523
524     s_wrpkt_start(pkttype, pktlen);
525     p = pktout.body;
526
527     va_start(args, pkttype);
528     while ((argtype = va_arg(args, int)) != PKT_END) {
529         switch (argtype) {
530           case PKT_INT:
531             argint = va_arg(args, int);
532             PUT_32BIT(p, argint);
533             p += 4;
534             break;
535           case PKT_CHAR:
536             argchar = va_arg(args, unsigned char);
537             *p = argchar;
538             p++;
539             break;
540           case PKT_DATA:
541             argp = va_arg(args, unsigned char *);
542             arglen = va_arg(args, int);
543             memcpy(p, argp, arglen);
544             p += arglen;
545             break;
546           case PKT_STR:
547             argp = va_arg(args, unsigned char *);
548             arglen = strlen(argp);
549             PUT_32BIT(p, arglen);
550             memcpy(p + 4, argp, arglen);
551             p += 4 + arglen;
552             break;
553         }
554     }
555     va_end(args);
556
557     s_wrpkt();
558 }
559
560
561 /*
562  * Connect to specified host and port.
563  * Returns an error message, or NULL on success.
564  * Also places the canonical host name into `realhost'.
565  */
566 static char *connect_to_host(char *host, int port, char **realhost)
567 {
568     SOCKADDR_IN addr;
569     struct hostent *h;
570     unsigned long a;
571 #ifdef FWHACK
572     char *FWhost;
573     int FWport;
574 #endif
575
576     savedhost = malloc(1+strlen(host));
577     if (!savedhost)
578         fatalbox("Out of memory");
579     strcpy(savedhost, host);
580
581     if (port < 0)
582         port = 22;                     /* default ssh port */
583
584 #ifdef FWHACK
585     FWhost = host;
586     FWport = port;
587     host = FWSTR;
588     port = 23;
589 #endif
590
591     /*
592      * Try to find host.
593      */
594     if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
595         if ( (h = gethostbyname(host)) == NULL)
596             switch (WSAGetLastError()) {
597               case WSAENETDOWN: return "Network is down";
598               case WSAHOST_NOT_FOUND: case WSANO_DATA:
599                 return "Host does not exist";
600               case WSATRY_AGAIN: return "Host not found";
601               default: return "gethostbyname: unknown error";
602             }
603         memcpy (&a, h->h_addr, sizeof(a));
604         *realhost = h->h_name;
605     } else
606         *realhost = host;
607 #ifdef FWHACK
608     *realhost = FWhost;
609 #endif
610     a = ntohl(a);
611
612     /*
613      * Open socket.
614      */
615     s = socket(AF_INET, SOCK_STREAM, 0);
616     if (s == INVALID_SOCKET)
617         switch (WSAGetLastError()) {
618           case WSAENETDOWN: return "Network is down";
619           case WSAEAFNOSUPPORT: return "TCP/IP support not present";
620           default: return "socket(): unknown error";
621         }
622
623     /*
624      * Bind to local address.
625      */
626     addr.sin_family = AF_INET;
627     addr.sin_addr.s_addr = htonl(INADDR_ANY);
628     addr.sin_port = htons(0);
629     if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
630         switch (WSAGetLastError()) {
631           case WSAENETDOWN: return "Network is down";
632           default: return "bind(): unknown error";
633         }
634
635     /*
636      * Connect to remote address.
637      */
638     addr.sin_addr.s_addr = htonl(a);
639     addr.sin_port = htons((short)port);
640     if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
641         switch (WSAGetLastError()) {
642           case WSAENETDOWN: return "Network is down";
643           case WSAECONNREFUSED: return "Connection refused";
644           case WSAENETUNREACH: return "Network is unreachable";
645           case WSAEHOSTUNREACH: return "No route to host";
646           default: return "connect(): unknown error";
647         }
648
649 #ifdef FWHACK
650     send(s, "connect ", 8, 0);
651     send(s, FWhost, strlen(FWhost), 0);
652     {
653         char buf[20];
654         sprintf(buf, " %d\n", FWport);
655         send (s, buf, strlen(buf), 0);
656     }
657 #endif
658
659     return NULL;
660 }
661
662 static int ssh_versioncmp(char *a, char *b) {
663     char *ae, *be;
664     unsigned long av, bv;
665
666     av = strtoul(a, &ae, 10);
667     bv = strtoul(b, &be, 10);
668     if (av != bv) return (av < bv ? -1 : +1);
669     if (*ae == '.') ae++;
670     if (*be == '.') be++;
671     av = strtoul(ae, &ae, 10);
672     bv = strtoul(be, &be, 10);
673     if (av != bv) return (av < bv ? -1 : +1);
674     return 0;
675 }
676
677
678 /*
679  * Utility routine for putting an SSH-protocol `string' into a SHA
680  * state.
681  */
682 #include <stdio.h>
683 void sha_string(SHA_State *s, void *str, int len) {
684     unsigned char lenblk[4];
685 static FILE *fp;
686     PUT_32BIT(lenblk, len);
687 if (!fp) fp = fopen("h:\\statham\\windows\\putty\\data","wb");
688 fwrite(lenblk, 4, 1, fp);
689     SHA_Bytes(s, lenblk, 4);
690 fwrite(str, len, 1, fp);
691 fflush(fp);
692     SHA_Bytes(s, str, len);
693 }
694
695 static int do_ssh_init(void) {
696     char c, *vsp;
697     char version[10];
698     char vstring[80];
699     char vlog[sizeof(vstring)+20];
700     int i;
701
702 #ifdef FWHACK
703     i = 0;
704     while (s_read(&c, 1) == 1) {
705         if (c == 'S' && i < 2) i++;
706         else if (c == 'S' && i == 2) i = 2;
707         else if (c == 'H' && i == 2) break;
708         else i = 0;
709     }
710 #else
711     if (s_read(&c,1) != 1 || c != 'S') return 0;
712     if (s_read(&c,1) != 1 || c != 'S') return 0;
713     if (s_read(&c,1) != 1 || c != 'H') return 0;
714 #endif
715     strcpy(vstring, "SSH-");
716     vsp = vstring+4;
717     if (s_read(&c,1) != 1 || c != '-') return 0;
718     i = 0;
719     while (1) {
720         if (s_read(&c,1) != 1)
721             return 0;
722         if (vsp < vstring+sizeof(vstring)-1)
723             *vsp++ = c;
724         if (i >= 0) {
725             if (c == '-') {
726                 version[i] = '\0';
727                 i = -1;
728             } else if (i < sizeof(version)-1)
729                 version[i++] = c;
730         }
731         else if (c == '\n')
732             break;
733     }
734
735     *vsp = 0;
736     sprintf(vlog, "Server version: %s", vstring);
737     vlog[strcspn(vlog, "\r\n")] = '\0';
738     logevent(vlog);
739
740     if (ssh_versioncmp(version, "1.99") >= 0) {
741         /*
742          * This is a v2 server. Begin v2 protocol.
743          */
744         char *verstring = "SSH-2.0-PuTTY";
745         SHA_Init(&exhash);
746         /*
747          * Hash our version string and their version string.
748          */
749         sha_string(&exhash, verstring, strlen(verstring));
750         sha_string(&exhash, vstring, strcspn(vstring, "\r\n"));
751         sprintf(vstring, "%s\n", verstring);
752         sprintf(vlog, "We claim version: %s", verstring);
753         logevent(vlog);
754         logevent("Using SSH protocol version 2");
755         s_write(vstring, strlen(vstring));
756         ssh_protocol = ssh2_protocol;
757         s_rdpkt = ssh2_rdpkt;
758     } else {
759         /*
760          * This is a v1 server. Begin v1 protocol.
761          */
762         sprintf(vstring, "SSH-%s-PuTTY\n",
763                 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
764         sprintf(vlog, "We claim version: %s", vstring);
765         vlog[strcspn(vlog, "\r\n")] = '\0';
766         logevent(vlog);
767         logevent("Using SSH protocol version 1");
768         s_write(vstring, strlen(vstring));
769         ssh_protocol = ssh1_protocol;
770         s_rdpkt = ssh1_rdpkt;
771     }
772     return 1;
773 }
774
775 /*
776  * Handle the key exchange and user authentication phases.
777  */
778 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
779 {
780     int i, j, len;
781     unsigned char session_id[16];
782     unsigned char *rsabuf, *keystr1, *keystr2;
783     unsigned char cookie[8];
784     struct RSAKey servkey, hostkey;
785     struct MD5Context md5c;
786     static unsigned long supported_ciphers_mask, supported_auths_mask;
787     int cipher_type;
788
789     crBegin;
790
791     if (!ispkt) crWaitUntil(ispkt);
792
793     if (pktin.type != SSH1_SMSG_PUBLIC_KEY)
794         fatalbox("Public key packet not received");
795
796     logevent("Received public keys");
797
798     memcpy(cookie, pktin.body, 8);
799
800     i = makekey(pktin.body+8, &servkey, &keystr1);
801     j = makekey(pktin.body+8+i, &hostkey, &keystr2);
802
803     /*
804      * Hash the host key and print the hash in the log box. Just as
805      * a last resort in case the registry's host key checking is
806      * compromised, we'll allow the user some ability to verify
807      * host keys by eye.
808      */
809     MD5Init(&md5c);
810     MD5Update(&md5c, keystr2, hostkey.bytes);
811     MD5Final(session_id, &md5c);
812     {
813         char logmsg[80];
814         int i;
815         logevent("Host key MD5 is:");
816         strcpy(logmsg, "      ");
817         for (i = 0; i < 16; i++)
818             sprintf(logmsg+strlen(logmsg), "%02x", session_id[i]);
819         logevent(logmsg);
820     }
821
822     supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
823     supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
824
825     MD5Init(&md5c);
826     MD5Update(&md5c, keystr2, hostkey.bytes);
827     MD5Update(&md5c, keystr1, servkey.bytes);
828     MD5Update(&md5c, pktin.body, 8);
829     MD5Final(session_id, &md5c);
830
831     for (i=0; i<32; i++)
832         session_key[i] = random_byte();
833
834     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
835
836     rsabuf = malloc(len);
837     if (!rsabuf)
838         fatalbox("Out of memory");
839
840     /*
841      * Verify the host key.
842      */
843     {
844         /*
845          * First format the key into a string.
846          */
847         int len = rsastr_len(&hostkey);
848         char *keystr = malloc(len);
849         if (!keystr)
850             fatalbox("Out of memory");
851         rsastr_fmt(keystr, &hostkey);
852         verify_ssh_host_key(savedhost, keystr);
853         free(keystr);
854     }
855
856     for (i=0; i<32; i++) {
857         rsabuf[i] = session_key[i];
858         if (i < 16)
859             rsabuf[i] ^= session_id[i];
860     }
861
862     if (hostkey.bytes > servkey.bytes) {
863         rsaencrypt(rsabuf, 32, &servkey);
864         rsaencrypt(rsabuf, servkey.bytes, &hostkey);
865     } else {
866         rsaencrypt(rsabuf, 32, &hostkey);
867         rsaencrypt(rsabuf, hostkey.bytes, &servkey);
868     }
869
870     logevent("Encrypted session key");
871
872     cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
873                   cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES : 
874                   SSH_CIPHER_3DES;
875     if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
876         c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
877         cipher_type = SSH_CIPHER_3DES;
878     }
879     switch (cipher_type) {
880       case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
881       case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
882       case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
883     }
884
885     send_packet(SSH1_CMSG_SESSION_KEY,
886                 PKT_CHAR, cipher_type,
887                 PKT_DATA, cookie, 8,
888                 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
889                 PKT_DATA, rsabuf, len,
890                 PKT_INT, 0,
891                 PKT_END);
892
893     logevent("Trying to enable encryption...");
894
895     free(rsabuf);
896
897     cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
898              cipher_type == SSH_CIPHER_DES ? &ssh_des :
899              &ssh_3des;
900     cipher->sesskey(session_key);
901
902     crWaitUntil(ispkt);
903
904     if (pktin.type != SSH1_SMSG_SUCCESS)
905         fatalbox("Encryption not successfully enabled");
906
907     logevent("Successfully started encryption");
908
909     fflush(stdout);
910     {
911         static char username[100];
912         static int pos = 0;
913         static char c;
914         if (!IS_SCP && !*cfg.username) {
915             c_write("login as: ", 10);
916             while (pos >= 0) {
917                 crWaitUntil(!ispkt);
918                 while (inlen--) switch (c = *in++) {
919                   case 10: case 13:
920                     username[pos] = 0;
921                     pos = -1;
922                     break;
923                   case 8: case 127:
924                     if (pos > 0) {
925                         c_write("\b \b", 3);
926                         pos--;
927                     }
928                     break;
929                   case 21: case 27:
930                     while (pos > 0) {
931                         c_write("\b \b", 3);
932                         pos--;
933                     }
934                     break;
935                   case 3: case 4:
936                     random_save_seed();
937                     exit(0);
938                     break;
939                   default:
940                     if (((c >= ' ' && c <= '~') ||
941                          ((unsigned char)c >= 160)) && pos < 40) {
942                         username[pos++] = c;
943                         c_write(&c, 1);
944                     }
945                     break;
946                 }
947             }
948             c_write("\r\n", 2);
949             username[strcspn(username, "\n\r")] = '\0';
950         } else {
951             char stuff[200];
952             strncpy(username, cfg.username, 99);
953             username[99] = '\0';
954             if (!IS_SCP) {
955                 sprintf(stuff, "Sent username \"%s\".\r\n", username);
956                 c_write(stuff, strlen(stuff));
957             }
958         }
959
960         send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
961         {
962             char userlog[20+sizeof(username)];
963             sprintf(userlog, "Sent username \"%s\"", username);
964             logevent(userlog);
965         }
966     }
967
968     crWaitUntil(ispkt);
969
970     while (pktin.type == SSH1_SMSG_FAILURE) {
971         static char password[100];
972         static int pos;
973         static char c;
974         static int pwpkt_type;
975
976         /*
977          * Show password prompt, having first obtained it via a TIS
978          * exchange if we're doing TIS authentication.
979          */
980         pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
981
982         if (IS_SCP) {
983             char prompt[200];
984             sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
985             if (!ssh_get_password(prompt, password, sizeof(password))) {
986                 /*
987                  * get_password failed to get a password (for
988                  * example because one was supplied on the command
989                  * line which has already failed to work).
990                  * Terminate.
991                  */
992                 logevent("No more passwords to try");
993                 ssh_state = SSH_STATE_CLOSED;
994                 crReturn(1);
995             }
996         } else {
997
998         if (pktin.type == SSH1_SMSG_FAILURE &&
999             cfg.try_tis_auth &&
1000             (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1001             pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1002             logevent("Requested TIS authentication");
1003             send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1004             crWaitUntil(ispkt);
1005             if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1006                 logevent("TIS authentication declined");
1007                 c_write("TIS authentication refused.\r\n", 29);
1008             } else {
1009                 int challengelen = ((pktin.body[0] << 24) |
1010                                     (pktin.body[1] << 16) |
1011                                     (pktin.body[2] << 8) |
1012                                     (pktin.body[3]));
1013                 logevent("Received TIS challenge");
1014                 c_write(pktin.body+4, challengelen);
1015             }
1016         }
1017         if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD)
1018             c_write("password: ", 10);
1019
1020         pos = 0;
1021         while (pos >= 0) {
1022             crWaitUntil(!ispkt);
1023             while (inlen--) switch (c = *in++) {
1024               case 10: case 13:
1025                 password[pos] = 0;
1026                 pos = -1;
1027                 break;
1028               case 8: case 127:
1029                 if (pos > 0)
1030                     pos--;
1031                 break;
1032               case 21: case 27:
1033                 pos = 0;
1034                 break;
1035               case 3: case 4:
1036                 random_save_seed();
1037                 exit(0);
1038                 break;
1039               default:
1040                 if (((c >= ' ' && c <= '~') ||
1041                      ((unsigned char)c >= 160)) && pos < 40)
1042                     password[pos++] = c;
1043                 break;
1044             }
1045         }
1046         c_write("\r\n", 2);
1047
1048         }
1049
1050         send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1051         logevent("Sent password");
1052         memset(password, 0, strlen(password));
1053         crWaitUntil(ispkt);
1054         if (pktin.type == SSH1_SMSG_FAILURE) {
1055             c_write("Access denied\r\n", 15);
1056             logevent("Authentication refused");
1057         } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1058             logevent("Received disconnect request");
1059             ssh_state = SSH_STATE_CLOSED;
1060             crReturn(1);
1061         } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1062             fatalbox("Strange packet received, type %d", pktin.type);
1063         }
1064     }
1065
1066     logevent("Authentication successful");
1067
1068     crFinish(1);
1069 }
1070
1071 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1072     crBegin;
1073
1074     random_init();
1075
1076     while (!do_ssh1_login(in, inlen, ispkt)) {
1077         crReturnV;
1078     }
1079     if (ssh_state == SSH_STATE_CLOSED)
1080         crReturnV;
1081
1082     if (!cfg.nopty) {
1083         send_packet(SSH1_CMSG_REQUEST_PTY,
1084                     PKT_STR, cfg.termtype,
1085                     PKT_INT, rows, PKT_INT, cols,
1086                     PKT_INT, 0, PKT_INT, 0,
1087                     PKT_CHAR, 0,
1088                     PKT_END);
1089         ssh_state = SSH_STATE_INTERMED;
1090         do { crReturnV; } while (!ispkt);
1091         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1092             fatalbox("Protocol confusion");
1093         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1094             c_write("Server refused to allocate pty\r\n", 32);
1095         }
1096         logevent("Allocated pty");
1097     }
1098
1099     send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1100     logevent("Started session");
1101
1102     ssh_state = SSH_STATE_SESSION;
1103     if (size_needed)
1104         ssh_size();
1105
1106     while (1) {
1107         crReturnV;
1108         if (ispkt) {
1109             if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1110                 pktin.type == SSH1_SMSG_STDERR_DATA) {
1111                 long len = GET_32BIT(pktin.body);
1112                 c_write(pktin.body+4, len);
1113             } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1114                 ssh_state = SSH_STATE_CLOSED;
1115                 logevent("Received disconnect request");
1116             } else if (pktin.type == SSH1_SMSG_SUCCESS) {
1117                 /* may be from EXEC_SHELL on some servers */
1118             } else if (pktin.type == SSH1_SMSG_FAILURE) {
1119                 /* may be from EXEC_SHELL on some servers
1120                  * if no pty is available or in other odd cases. Ignore */
1121             } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1122                 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
1123             } else {
1124                 fatalbox("Strange packet received: type %d", pktin.type);
1125             }
1126         } else {
1127             send_packet(SSH1_CMSG_STDIN_DATA,
1128                         PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
1129         }
1130     }
1131
1132     crFinishV;
1133 }
1134
1135 /*
1136  * SSH2 packet construction functions.
1137  */
1138 void ssh2_pkt_adddata(void *data, int len) {
1139     pktout.length += len;
1140     if (pktout.maxlen < pktout.length) {
1141         pktout.maxlen = pktout.length + 256;
1142         pktout.data = (pktout.data == NULL ? malloc(pktout.maxlen+APIEXTRA) :
1143                        realloc(pktout.data, pktout.maxlen+APIEXTRA));
1144         if (!pktout.data)
1145             fatalbox("Out of memory");
1146     }
1147     memcpy(pktout.data+pktout.length-len, data, len);
1148 }
1149 void ssh2_pkt_addbyte(unsigned char byte) {
1150     ssh2_pkt_adddata(&byte, 1);
1151 }
1152 void ssh2_pkt_init(int pkt_type) {
1153     pktout.length = 5;
1154     ssh2_pkt_addbyte((unsigned char)pkt_type);
1155 }
1156 void ssh2_pkt_addbool(unsigned char value) {
1157     ssh2_pkt_adddata(&value, 1);
1158 }
1159 void ssh2_pkt_adduint32(unsigned long value) {
1160     unsigned char x[4];
1161     PUT_32BIT(x, value);
1162     ssh2_pkt_adddata(x, 4);
1163 }
1164 void ssh2_pkt_addstring_start(void) {
1165     ssh2_pkt_adduint32(0);
1166     pktout.savedpos = pktout.length;
1167 }
1168 void ssh2_pkt_addstring_str(char *data) {
1169     ssh2_pkt_adddata(data, strlen(data));
1170     PUT_32BIT(pktout.data + pktout.savedpos - 4,
1171               pktout.length - pktout.savedpos);
1172 }
1173 void ssh2_pkt_addstring_data(char *data, int len) {
1174     ssh2_pkt_adddata(data, len);
1175     PUT_32BIT(pktout.data + pktout.savedpos - 4,
1176               pktout.length - pktout.savedpos);
1177 }
1178 void ssh2_pkt_addstring(char *data) {
1179     ssh2_pkt_addstring_start();
1180     ssh2_pkt_addstring_str(data);
1181 }
1182 char *ssh2_mpint_fmt(Bignum b, int *len) {
1183     unsigned char *p;
1184     int i, n = b[0];
1185     p = malloc(n * 2 + 1);
1186     if (!p)
1187         fatalbox("out of memory");
1188     p[0] = 0;
1189     for (i = 0; i < n; i++) {
1190         p[i*2+1] = (b[n-i] >> 8) & 0xFF;
1191         p[i*2+2] = (b[n-i]     ) & 0xFF;
1192     }
1193     i = 0;
1194     while (p[i] == 0 && (p[i+1] & 0x80) == 0)
1195         i++;
1196     memmove(p, p+i, n*2+1-i);
1197     *len = n*2+1-i;
1198     return p;
1199 }
1200 void ssh2_pkt_addmp(Bignum b) {
1201     unsigned char *p;
1202     int len;
1203     p = ssh2_mpint_fmt(b, &len);
1204     ssh2_pkt_addstring_start();
1205     ssh2_pkt_addstring_data(p, len);
1206     free(p);
1207 }
1208 void ssh2_pkt_send(void) {
1209     int cipherblk, maclen, padding, i;
1210     unsigned long outgoing_sequence = 0;
1211
1212     /*
1213      * Add padding. At least four bytes, and must also bring total
1214      * length (minus MAC) up to a multiple of the block size.
1215      */
1216     cipherblk = cipher ? cipher->blksize : 8;   /* block size */
1217     cipherblk = cipherblk < 8 ? 8 : cipherblk;   /* or 8 if blksize < 8 */
1218     padding = 4;
1219     padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
1220     pktout.data[4] = padding;
1221     for (i = 0; i < padding; i++)
1222         pktout.data[pktout.length + i] = random_byte();
1223     PUT_32BIT(pktout.data, pktout.length + padding - 4);
1224     if (csmac)
1225         csmac->generate(pktout.data, outgoing_sequence++,
1226                       pktout.length + padding);
1227     if (cscipher)
1228         cscipher->encrypt(pktout.data, pktout.length + padding);
1229     maclen = csmac ? csmac->len : 0;
1230 #if 0
1231     debug(("Sending packet len=%d\r\n", pktout.length+padding+maclen));
1232     for (i = 0; i < pktout.length+padding+maclen; i++)
1233         debug(("  %02x", (unsigned char)pktout.data[i]));
1234     debug(("\r\n"));
1235 #endif
1236     s_write(pktout.data, pktout.length + padding + maclen);
1237 }
1238
1239 void sha_mpint(SHA_State *s, Bignum b) {
1240     unsigned char *p;
1241     int len;
1242     p = ssh2_mpint_fmt(b, &len);
1243     sha_string(s, p, len);
1244     free(p);
1245 }
1246
1247 /*
1248  * SSH2 packet decode functions.
1249  */
1250 void ssh2_pkt_getstring(char **p, int *length) {
1251     *p = NULL;
1252     if (pktin.length - pktin.savedpos < 4)
1253         return;
1254     *length = GET_32BIT(pktin.data+pktin.savedpos);
1255     pktin.savedpos += 4;
1256     if (pktin.length - pktin.savedpos < *length)
1257         return;
1258     *p = pktin.data+pktin.savedpos;
1259     pktin.savedpos += *length;
1260 }
1261 Bignum ssh2_pkt_getmp(void) {
1262     char *p;
1263     int i, j, length;
1264     Bignum b;
1265
1266     ssh2_pkt_getstring(&p, &length);
1267     if (!p)
1268         return NULL;
1269     if (p[0] & 0x80)
1270         fatalbox("internal error: Can't handle negative mpints");
1271     b = newbn((length+1)/2);
1272     for (i = 0; i < length; i++) {
1273         j = length - 1 - i;
1274         if (j & 1)
1275             b[j/2+1] |= ((unsigned char)p[i]) << 8;
1276         else
1277             b[j/2+1] |= ((unsigned char)p[i]);
1278     }
1279     return b;
1280 }
1281
1282 void bndebug(char *string, Bignum b) {
1283     unsigned char *p;
1284     int i, len;
1285     p = ssh2_mpint_fmt(b, &len);
1286     debug(("%s", string));
1287     for (i = 0; i < len; i++)
1288         debug(("  %02x", p[i]));
1289     debug(("\r\n"));
1290     free(p);
1291 }
1292
1293 /*
1294  * Utility routine for decoding comma-separated strings in KEXINIT.
1295  */
1296 int in_commasep_string(char *needle, char *haystack, int haylen) {
1297     int needlen = strlen(needle);
1298     while (1) {
1299         /*
1300          * Is it at the start of the string?
1301          */
1302         if (haylen >= needlen &&       /* haystack is long enough */
1303             !memcmp(needle, haystack, needlen) &&    /* initial match */
1304             (haylen == needlen || haystack[needlen] == ',')
1305                                        /* either , or EOS follows */
1306             )
1307             return 1;
1308         /*
1309          * If not, search for the next comma and resume after that.
1310          * If no comma found, terminate.
1311          */
1312         while (haylen > 0 && *haystack != ',')
1313             haylen--, haystack++;
1314         if (haylen == 0)
1315             return 0;
1316         haylen--, haystack++;          /* skip over comma itself */
1317     }
1318 }
1319
1320 /*
1321  * SSH2 key creation method.
1322  */
1323 void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1324     SHA_State s;
1325     /* First 20 bytes. */
1326     SHA_Init(&s);
1327     sha_mpint(&s, K);
1328     SHA_Bytes(&s, H, 20);
1329     SHA_Bytes(&s, &chr, 1);
1330     SHA_Bytes(&s, H, 20);
1331     SHA_Final(&s, keyspace);
1332     /* Next 20 bytes. */
1333     SHA_Init(&s);
1334     sha_mpint(&s, K);
1335     SHA_Bytes(&s, H, 20);
1336     SHA_Bytes(&s, keyspace, 20);
1337     SHA_Final(&s, keyspace+20);
1338 }
1339
1340 /*
1341  * Handle the SSH2 key exchange phase.
1342  */
1343 static int do_ssh2_kex(unsigned char *in, int inlen, int ispkt)
1344 {
1345     static int i, len;
1346     static char *str;
1347     static Bignum e, f, K;
1348     static struct ssh_cipher *cscipher_tobe = NULL;
1349     static struct ssh_cipher *sccipher_tobe = NULL;
1350     static struct ssh_mac *csmac_tobe = NULL;
1351     static struct ssh_mac *scmac_tobe = NULL;
1352     static struct ssh_compress *cscomp_tobe = NULL;
1353     static struct ssh_compress *sccomp_tobe = NULL;
1354     static char *hostkeydata, *sigdata;
1355     static int hostkeylen, siglen;
1356     static unsigned char exchange_hash[20];
1357     static unsigned char keyspace[40];
1358
1359     crBegin;
1360
1361     /*
1362      * Construct and send our key exchange packet.
1363      */
1364     ssh2_pkt_init(SSH2_MSG_KEXINIT);
1365     for (i = 0; i < 16; i++)
1366         ssh2_pkt_addbyte((unsigned char)random_byte());
1367     /* List key exchange algorithms. */
1368     ssh2_pkt_addstring_start();
1369     for (i = 0; i < lenof(kex_algs); i++) {
1370         ssh2_pkt_addstring_str(kex_algs[i]->name);
1371         if (i < lenof(kex_algs)-1)
1372             ssh2_pkt_addstring_str(",");
1373     }
1374     /* List server host key algorithms. */
1375     ssh2_pkt_addstring_start();
1376     for (i = 0; i < lenof(hostkey_algs); i++) {
1377         ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1378         if (i < lenof(hostkey_algs)-1)
1379             ssh2_pkt_addstring_str(",");
1380     }
1381     /* List client->server encryption algorithms. */
1382     ssh2_pkt_addstring_start();
1383     for (i = 0; i < lenof(ciphers); i++) {
1384         ssh2_pkt_addstring_str(ciphers[i]->name);
1385         if (i < lenof(ciphers)-1)
1386             ssh2_pkt_addstring_str(",");
1387     }
1388     /* List server->client encryption algorithms. */
1389     ssh2_pkt_addstring_start();
1390     for (i = 0; i < lenof(ciphers); i++) {
1391         ssh2_pkt_addstring_str(ciphers[i]->name);
1392         if (i < lenof(ciphers)-1)
1393             ssh2_pkt_addstring_str(",");
1394     }
1395     /* List client->server MAC algorithms. */
1396     ssh2_pkt_addstring_start();
1397     for (i = 0; i < lenof(macs); i++) {
1398         ssh2_pkt_addstring_str(macs[i]->name);
1399         if (i < lenof(macs)-1)
1400             ssh2_pkt_addstring_str(",");
1401     }
1402     /* List server->client MAC algorithms. */
1403     ssh2_pkt_addstring_start();
1404     for (i = 0; i < lenof(macs); i++) {
1405         ssh2_pkt_addstring_str(macs[i]->name);
1406         if (i < lenof(macs)-1)
1407             ssh2_pkt_addstring_str(",");
1408     }
1409     /* List client->server compression algorithms. */
1410     ssh2_pkt_addstring_start();
1411     for (i = 0; i < lenof(compressions); i++) {
1412         ssh2_pkt_addstring_str(compressions[i]->name);
1413         if (i < lenof(compressions)-1)
1414             ssh2_pkt_addstring_str(",");
1415     }
1416     /* List server->client compression algorithms. */
1417     ssh2_pkt_addstring_start();
1418     for (i = 0; i < lenof(compressions); i++) {
1419         ssh2_pkt_addstring_str(compressions[i]->name);
1420         if (i < lenof(compressions)-1)
1421             ssh2_pkt_addstring_str(",");
1422     }
1423     /* List client->server languages. Empty list. */
1424     ssh2_pkt_addstring_start();
1425     /* List server->client languages. Empty list. */
1426     ssh2_pkt_addstring_start();
1427     /* First KEX packet does _not_ follow, because we're not that brave. */
1428     ssh2_pkt_addbool(FALSE);
1429     /* Reserved. */
1430     ssh2_pkt_adduint32(0);
1431     sha_string(&exhash, pktout.data+5, pktout.length-5);
1432     ssh2_pkt_send();
1433
1434     if (!ispkt) crWaitUntil(ispkt);
1435     sha_string(&exhash, pktin.data+5, pktin.length-5);
1436
1437     /*
1438      * Now examine the other side's KEXINIT to see what we're up
1439      * to.
1440      */
1441     if (pktin.type != SSH2_MSG_KEXINIT)
1442         fatalbox("expected key exchange packet from server");
1443     kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1444     csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1445     pktin.savedpos += 16;              /* skip garbage cookie */
1446     ssh2_pkt_getstring(&str, &len);    /* key exchange algorithms */
1447     for (i = 0; i < lenof(kex_algs); i++) {
1448         if (in_commasep_string(kex_algs[i]->name, str, len)) {
1449             kex = kex_algs[i];
1450             break;
1451         }
1452     }
1453     ssh2_pkt_getstring(&str, &len);    /* host key algorithms */
1454     for (i = 0; i < lenof(hostkey_algs); i++) {
1455         if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1456             hostkey = hostkey_algs[i];
1457             break;
1458         }
1459     }
1460     ssh2_pkt_getstring(&str, &len);    /* client->server cipher */
1461     for (i = 0; i < lenof(ciphers); i++) {
1462         if (in_commasep_string(ciphers[i]->name, str, len)) {
1463             cscipher_tobe = ciphers[i];
1464             break;
1465         }
1466     }
1467     ssh2_pkt_getstring(&str, &len);    /* server->client cipher */
1468     for (i = 0; i < lenof(ciphers); i++) {
1469         if (in_commasep_string(ciphers[i]->name, str, len)) {
1470             sccipher_tobe = ciphers[i];
1471             break;
1472         }
1473     }
1474     ssh2_pkt_getstring(&str, &len);    /* client->server mac */
1475     for (i = 0; i < lenof(macs); i++) {
1476         if (in_commasep_string(macs[i]->name, str, len)) {
1477             csmac_tobe = macs[i];
1478             break;
1479         }
1480     }
1481     ssh2_pkt_getstring(&str, &len);    /* server->client mac */
1482     for (i = 0; i < lenof(macs); i++) {
1483         if (in_commasep_string(macs[i]->name, str, len)) {
1484             scmac_tobe = macs[i];
1485             break;
1486         }
1487     }
1488     ssh2_pkt_getstring(&str, &len);    /* client->server compression */
1489     for (i = 0; i < lenof(compressions); i++) {
1490         if (in_commasep_string(compressions[i]->name, str, len)) {
1491             cscomp_tobe = compressions[i];
1492             break;
1493         }
1494     }
1495     ssh2_pkt_getstring(&str, &len);    /* server->client compression */
1496     for (i = 0; i < lenof(compressions); i++) {
1497         if (in_commasep_string(compressions[i]->name, str, len)) {
1498             sccomp_tobe = compressions[i];
1499             break;
1500         }
1501     }
1502     debug(("key exchange is %s\r\n", kex ? kex->name : NULL));
1503     debug(("host key alg is %s\r\n", hostkey ? hostkey->name : NULL));
1504     debug(("cscipher alg is %s\r\n", cscipher_tobe ? cscipher_tobe->name : NULL));
1505     debug(("sccipher alg is %s\r\n", sccipher_tobe ? sccipher_tobe->name : NULL));
1506     debug(("csmac alg is %s\r\n", csmac_tobe ? csmac_tobe->name : NULL));
1507     debug(("scmac alg is %s\r\n", scmac_tobe ? scmac_tobe->name : NULL));
1508     debug(("cscomp alg is %s\r\n", cscomp_tobe ? cscomp_tobe->name : NULL));
1509     debug(("sccomp alg is %s\r\n", sccomp_tobe ? sccomp_tobe->name : NULL));
1510
1511     /*
1512      * Currently we only support Diffie-Hellman and DSS, so let's
1513      * bomb out if those aren't selected.
1514      */
1515     if (kex != &ssh_diffiehellman || hostkey != &ssh_dss)
1516         fatalbox("internal fault: chaos in SSH 2 transport layer");
1517
1518     /*
1519      * Now we begin the fun. Generate and send e for Diffie-Hellman.
1520      */
1521     e = dh_create_e();
1522     bndebug("e=", e);
1523     ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
1524     ssh2_pkt_addmp(e);
1525     ssh2_pkt_send();
1526
1527     crWaitUntil(ispkt);
1528     if (pktin.type != SSH2_MSG_KEXDH_REPLY)
1529         fatalbox("expected key exchange packet from server");
1530     ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
1531     f = ssh2_pkt_getmp();
1532     bndebug("f=", f);
1533     ssh2_pkt_getstring(&sigdata, &siglen);
1534
1535     K = dh_find_K(f);
1536     bndebug("K=", K);
1537
1538     sha_string(&exhash, hostkeydata, hostkeylen);
1539     sha_mpint(&exhash, e);
1540     sha_mpint(&exhash, f);
1541     sha_mpint(&exhash, K);
1542     SHA_Final(&exhash, exchange_hash);
1543
1544     debug(("Exchange hash is:\r\n"));
1545     for (i = 0; i < 20; i++)
1546         debug((" %02x", exchange_hash[i]));
1547     debug(("\r\n"));
1548
1549     /*
1550      * FIXME: verify host key. This bit will be moderately
1551      * unpleasant, because of having to rewrite it to work
1552      * alongside the old scheme.
1553      */
1554
1555     /*
1556      * FIXME: verify signature of exchange hash.
1557      */
1558
1559     /*
1560      * Send SSH2_MSG_NEWKEYS. Expect it from server.
1561      */
1562     ssh2_pkt_init(SSH2_MSG_NEWKEYS);
1563     ssh2_pkt_send();
1564     crWaitUntil(ispkt);
1565     if (pktin.type != SSH2_MSG_NEWKEYS)
1566         fatalbox("expected new-keys packet from server");
1567
1568     /*
1569      * Create and initialise session keys.
1570      */
1571     cscipher = cscipher_tobe;
1572     sccipher = sccipher_tobe;
1573     csmac = csmac_tobe;
1574     scmac = scmac_tobe;
1575     cscomp = cscomp_tobe;
1576     sccomp = sccomp_tobe;
1577     /*
1578      * Set IVs after keys.
1579      */
1580     ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
1581     ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
1582     ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
1583     ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
1584     ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
1585     ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
1586
1587     crWaitUntil(0);
1588
1589     crFinish(1);
1590 }
1591
1592 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt) {
1593     crBegin;
1594
1595     random_init();
1596
1597     while (!do_ssh2_kex(in, inlen, ispkt)) {
1598         crReturnV;
1599     }
1600
1601     crFinishV;
1602 }
1603
1604 /*
1605  * Called to set up the connection. Will arrange for WM_NETEVENT
1606  * messages to be passed to the specified window, whose window
1607  * procedure should then call telnet_msg().
1608  *
1609  * Returns an error message, or NULL on success.
1610  */
1611 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
1612     char *p;
1613         
1614 #ifdef MSCRYPTOAPI
1615     if(crypto_startup() == 0)
1616         return "Microsoft high encryption pack not installed!";
1617 #endif
1618
1619     p = connect_to_host(host, port, realhost);
1620     if (p != NULL)
1621         return p;
1622
1623     if (!do_ssh_init())
1624         return "Protocol initialisation error";
1625
1626     if (WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
1627         switch (WSAGetLastError()) {
1628           case WSAENETDOWN: return "Network is down";
1629           default: return "WSAAsyncSelect(): unknown error";
1630         }
1631
1632     return NULL;
1633 }
1634
1635 /*
1636  * Process a WM_NETEVENT message. Will return 0 if the connection
1637  * has closed, or <0 for a socket error.
1638  */
1639 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
1640     int ret;
1641     char buf[256];
1642
1643     /*
1644      * Because reading less than the whole of the available pending
1645      * data can generate an FD_READ event, we need to allow for the
1646      * possibility that FD_READ may arrive with FD_CLOSE already in
1647      * the queue; so it's possible that we can get here even with s
1648      * invalid. If so, we return 1 and don't worry about it.
1649      */
1650     if (s == INVALID_SOCKET)
1651         return 1;
1652
1653     if (WSAGETSELECTERROR(lParam) != 0)
1654         return -WSAGETSELECTERROR(lParam);
1655
1656     switch (WSAGETSELECTEVENT(lParam)) {
1657       case FD_READ:
1658       case FD_CLOSE:
1659         ret = recv(s, buf, sizeof(buf), 0);
1660         if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
1661             return 1;
1662         if (ret < 0)                   /* any _other_ error */
1663             return -10000-WSAGetLastError();
1664         if (ret == 0) {
1665             s = INVALID_SOCKET;
1666             return 0;
1667         }
1668         ssh_gotdata (buf, ret);
1669         if (ssh_state == SSH_STATE_CLOSED) {
1670             closesocket(s);
1671             s = INVALID_SOCKET;
1672             return 0;
1673         }
1674         return 1;
1675     }
1676     return 1;                          /* shouldn't happen, but WTF */
1677 }
1678
1679 /*
1680  * Called to send data down the Telnet connection.
1681  */
1682 static void ssh_send (char *buf, int len) {
1683     if (s == INVALID_SOCKET)
1684         return;
1685
1686     ssh_protocol(buf, len, 0);
1687 }
1688
1689 /*
1690  * Called to set the size of the window from Telnet's POV.
1691  */
1692 static void ssh_size(void) {
1693     switch (ssh_state) {
1694       case SSH_STATE_BEFORE_SIZE:
1695       case SSH_STATE_CLOSED:
1696         break;                         /* do nothing */
1697       case SSH_STATE_INTERMED:
1698         size_needed = TRUE;            /* buffer for later */
1699         break;
1700       case SSH_STATE_SESSION:
1701         if (!cfg.nopty) {
1702             send_packet(SSH1_CMSG_WINDOW_SIZE,
1703                         PKT_INT, rows, PKT_INT, cols,
1704                         PKT_INT, 0, PKT_INT, 0, PKT_END);
1705         }
1706     }
1707 }
1708
1709 /*
1710  * (Send Telnet special codes)
1711  */
1712 static void ssh_special (Telnet_Special code) {
1713     /* do nothing */
1714 }
1715
1716
1717 /*
1718  * Read and decrypt one incoming SSH packet.
1719  * (only used by pSCP)
1720  */
1721 static void get_packet(void)
1722 {
1723     unsigned char buf[4096], *p;
1724     long to_read;
1725     int len;
1726
1727     assert(IS_SCP);
1728
1729     p = NULL;
1730     len = 0;
1731
1732     while ((to_read = s_rdpkt(&p, &len)) > 0) {
1733         if (to_read > sizeof(buf)) to_read = sizeof(buf);
1734         len = s_read(buf, to_read);
1735         if (len != to_read) {
1736             closesocket(s);
1737             s = INVALID_SOCKET;
1738             return;
1739         }
1740         p = buf;
1741     }
1742
1743     assert(len == 0);
1744 }
1745
1746 /*
1747  * Receive a block of data over the SSH link. Block until
1748  * all data is available. Return nr of bytes read (0 if lost connection).
1749  * (only used by pSCP)
1750  */
1751 int ssh_scp_recv(unsigned char *buf, int len)
1752 {
1753     static int pending_input_len = 0;
1754     static unsigned char *pending_input_ptr;
1755     int to_read = len;
1756
1757     assert(IS_SCP);
1758
1759     if (pending_input_len >= to_read) {
1760         memcpy(buf, pending_input_ptr, to_read);
1761         pending_input_ptr += to_read;
1762         pending_input_len -= to_read;
1763         return len;
1764     }
1765     
1766     if (pending_input_len > 0) {
1767         memcpy(buf, pending_input_ptr, pending_input_len);
1768         buf += pending_input_len;
1769         to_read -= pending_input_len;
1770         pending_input_len = 0;
1771     }
1772
1773     if (s == INVALID_SOCKET)
1774         return 0;
1775     while (to_read > 0) {
1776         get_packet();
1777         if (s == INVALID_SOCKET)
1778             return 0;
1779         if (pktin.type == SSH1_SMSG_STDOUT_DATA) {
1780             int plen = GET_32BIT(pktin.body);
1781             if (plen <= to_read) {
1782                 memcpy(buf, pktin.body + 4, plen);
1783                 buf += plen;
1784                 to_read -= plen;
1785             } else {
1786                 memcpy(buf, pktin.body + 4, to_read);
1787                 pending_input_len = plen - to_read;
1788                 pending_input_ptr = pktin.body + 4 + to_read;
1789                 to_read = 0;
1790             }
1791         } else if (pktin.type == SSH1_SMSG_STDERR_DATA) {
1792             int plen = GET_32BIT(pktin.body);
1793             fwrite(pktin.body + 4, plen, 1, stderr);
1794         } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1795                 logevent("Received disconnect request");
1796         } else if (pktin.type == SSH1_SMSG_SUCCESS ||
1797                    pktin.type == SSH1_SMSG_FAILURE) {
1798                 /* ignore */
1799         } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1800             char logbuf[100];
1801             sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
1802             logevent(logbuf);
1803             send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
1804             logevent("Closing connection");
1805             closesocket(s);
1806             s = INVALID_SOCKET;
1807         } else {
1808             fatalbox("Strange packet received: type %d", pktin.type);
1809         }
1810     }
1811
1812     return len;
1813 }
1814
1815 /*
1816  * Send a block of data over the SSH link.
1817  * Block until all data is sent.
1818  * (only used by pSCP)
1819  */
1820 void ssh_scp_send(unsigned char *buf, int len)
1821 {
1822     assert(IS_SCP);
1823     if (s == INVALID_SOCKET)
1824         return;
1825     send_packet(SSH1_CMSG_STDIN_DATA,
1826                 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
1827 }
1828
1829 /*
1830  * Send an EOF notification to the server.
1831  * (only used by pSCP)
1832  */
1833 void ssh_scp_send_eof(void)
1834 {
1835     assert(IS_SCP);
1836     if (s == INVALID_SOCKET)
1837         return;
1838     send_packet(SSH1_CMSG_EOF, PKT_END);
1839 }
1840
1841 /*
1842  * Set up the connection, login on the remote host and
1843  * start execution of a command.
1844  * Returns an error message, or NULL on success.
1845  * (only used by pSCP)
1846  */
1847 char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
1848 {
1849     char buf[160], *p;
1850
1851     assert(IS_SCP);
1852
1853 #ifdef MSCRYPTOAPI
1854     if (crypto_startup() == 0)
1855         return "Microsoft high encryption pack not installed!";
1856 #endif
1857
1858     p = connect_to_host(host, port, realhost);
1859     if (p != NULL)
1860         return p;
1861
1862     random_init();
1863
1864     if (!do_ssh_init())
1865         return "Protocol initialisation error";
1866
1867     /* Exchange keys and login */
1868     do {
1869         get_packet();
1870         if (s == INVALID_SOCKET)
1871             return "Connection closed by remote host";
1872     } while (!do_ssh1_login(NULL, 0, 1));
1873
1874     if (ssh_state == SSH_STATE_CLOSED) {
1875         closesocket(s);
1876         s = INVALID_SOCKET;
1877         return "Session initialisation error";
1878     }
1879
1880     /* Execute command */
1881     sprintf(buf, "Sending command: %.100s", cmd);
1882     logevent(buf);
1883     send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
1884
1885     return NULL;
1886 }
1887
1888
1889 Backend ssh_backend = {
1890     ssh_init,
1891     ssh_msg,
1892     ssh_send,
1893     ssh_size,
1894     ssh_special
1895 };
1896