]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
Stop plink losing data at start of session
[PuTTY.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 (!(flags & FLAG_CONNECTION) && (flags & FLAG_VERBOSE)) \
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_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
47
48 #define SSH1_AUTH_TIS           5
49
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
80
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
86
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]))
92
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); }
98
99 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
100
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)     \
108         do {\
109             crLine=__LINE__; return (z); case __LINE__:;\
110         } while (0)
111 #define crReturnV       \
112         do {\
113             crLine=__LINE__; return; case __LINE__:;\
114         } while (0)
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))
119
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;
124
125 /* for ssh 2; we miss out single-DES because it isn't supported */
126 struct ssh_cipher *ciphers[] = { &ssh_3des_ssh2, &ssh_blowfish };
127
128 extern struct ssh_kex ssh_diffiehellman;
129 struct ssh_kex *kex_algs[] = { &ssh_diffiehellman };
130
131 extern struct ssh_hostkey ssh_dss;
132 struct ssh_hostkey *hostkey_algs[] = { &ssh_dss };
133
134 extern struct ssh_mac ssh_sha1;
135
136 SHA_State exhash;
137
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
143 };
144 struct ssh_mac *macs[] = { &ssh_sha1, &ssh_mac_none };
145
146 struct ssh_compress ssh_comp_none = {
147     "none"
148 };
149 struct ssh_compress *compressions[] = { &ssh_comp_none };
150
151 static SOCKET s = INVALID_SOCKET;
152
153 static unsigned char session_key[32];
154 static struct ssh_cipher *cipher = NULL;
155 static struct ssh_cipher *cscipher = NULL;
156 static struct ssh_cipher *sccipher = NULL;
157 static struct ssh_mac *csmac = NULL;
158 static struct ssh_mac *scmac = NULL;
159 static struct ssh_compress *cscomp = NULL;
160 static struct ssh_compress *sccomp = NULL;
161 static struct ssh_kex *kex = NULL;
162 static struct ssh_hostkey *hostkey = NULL;
163 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
164
165 static char *savedhost;
166 static int ssh_send_ok;
167
168 static enum {
169     SSH_STATE_BEFORE_SIZE,
170     SSH_STATE_INTERMED,
171     SSH_STATE_SESSION,
172     SSH_STATE_CLOSED
173 } ssh_state = SSH_STATE_BEFORE_SIZE;
174
175 static int size_needed = FALSE;
176
177 static void s_write (char *buf, int len) {
178     while (len > 0) {
179         int i = send (s, buf, len, 0);
180         noise_ultralight(i);
181         if (i <= 0)
182             fatalbox("Lost connection while sending");
183         if (i > 0)
184             len -= i, buf += i;
185     }
186 }
187
188 static int s_read (char *buf, int len) {
189     int ret = 0;
190     while (len > 0) {
191         int i = recv (s, buf, len, 0);
192         noise_ultralight(i);
193         if (i > 0)
194             len -= i, buf += i, ret += i;
195         else
196             return i;
197     }
198     return ret;
199 }
200
201 static void c_write (char *buf, int len) {
202     if (!(flags & FLAG_CONNECTION)) {
203         int i;
204         for (i = 0; i < len; i++)
205             if (buf[i] != '\r')
206                 fputc(buf[i], stderr);
207         return;
208     }
209     while (len--) 
210         c_write1(*buf++);
211 }
212
213 struct Packet {
214     long length;
215     int type;
216     unsigned char *data;
217     unsigned char *body;
218     long savedpos;
219     long maxlen;
220 };
221
222 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
223 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
224
225 static int ssh_version;
226 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
227 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
228 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
229 static void ssh_size(void);
230
231 static int (*s_rdpkt)(unsigned char **data, int *datalen);
232
233 /*
234  * Collect incoming data in the incoming packet buffer.
235  * Decipher and verify the packet when it is completely read.
236  * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
237  * Update the *data and *datalen variables.
238  * Return the additional nr of bytes needed, or 0 when
239  * a complete packet is available.
240  */
241 static int ssh1_rdpkt(unsigned char **data, int *datalen)
242 {
243     static long len, pad, biglen, to_read;
244     static unsigned long realcrc, gotcrc;
245     static unsigned char *p;
246     static int i;
247
248     crBegin;
249
250 next_packet:
251
252     pktin.type = 0;
253     pktin.length = 0;
254
255     for (i = len = 0; i < 4; i++) {
256         while ((*datalen) == 0)
257             crReturn(4-i);
258         len = (len << 8) + **data;
259         (*data)++, (*datalen)--;
260     }
261
262 #ifdef FWHACK
263     if (len == 0x52656d6f) {       /* "Remo"te server has closed ... */
264         len = 0x300;               /* big enough to carry to end */
265     }
266 #endif
267
268     pad = 8 - (len % 8);
269     biglen = len + pad;
270     pktin.length = len - 5;
271
272     if (pktin.maxlen < biglen) {
273         pktin.maxlen = biglen;
274         pktin.data = (pktin.data == NULL ? malloc(biglen+APIEXTRA) :
275                       realloc(pktin.data, biglen+APIEXTRA));
276         if (!pktin.data)
277             fatalbox("Out of memory");
278     }
279
280     to_read = biglen;
281     p = pktin.data;
282     while (to_read > 0) {
283         static int chunk;
284         chunk = to_read;
285         while ((*datalen) == 0)
286             crReturn(to_read);
287         if (chunk > (*datalen))
288             chunk = (*datalen);
289         memcpy(p, *data, chunk);
290         *data += chunk;
291         *datalen -= chunk;
292         p += chunk;
293         to_read -= chunk;
294     }
295
296     if (cipher)
297         cipher->decrypt(pktin.data, biglen);
298
299     pktin.type = pktin.data[pad];
300     pktin.body = pktin.data + pad + 1;
301
302     realcrc = crc32(pktin.data, biglen-4);
303     gotcrc = GET_32BIT(pktin.data+biglen-4);
304     if (gotcrc != realcrc) {
305         fatalbox("Incorrect CRC received on packet");
306     }
307
308     if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
309         pktin.type == SSH1_SMSG_STDERR_DATA ||
310         pktin.type == SSH1_MSG_DEBUG ||
311         pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE) {
312         long strlen = GET_32BIT(pktin.body);
313         if (strlen + 4 != pktin.length)
314             fatalbox("Received data packet with bogus string length");
315     }
316
317     if (pktin.type == SSH1_MSG_DEBUG) {
318         /* log debug message */
319         char buf[80];
320         int strlen = GET_32BIT(pktin.body);
321         strcpy(buf, "Remote: ");
322         if (strlen > 70) strlen = 70;
323         memcpy(buf+8, pktin.body+4, strlen);
324         buf[8+strlen] = '\0';
325         logevent(buf);
326         goto next_packet;
327     } else if (pktin.type == SSH1_MSG_IGNORE) {
328         /* do nothing */
329         goto next_packet;
330     }
331
332     crFinish(0);
333 }
334
335 static int ssh2_rdpkt(unsigned char **data, int *datalen)
336 {
337     static long len, pad, payload, packetlen, maclen;
338     static int i;
339     static int cipherblk;
340     static unsigned long incoming_sequence = 0;
341
342     crBegin;
343
344 next_packet:
345
346     pktin.type = 0;
347     pktin.length = 0;
348
349     if (cipher)
350         cipherblk = cipher->blksize;
351     else
352         cipherblk = 8;
353     if (cipherblk < 8)
354         cipherblk = 8;
355
356     if (pktin.maxlen < cipherblk) {
357         pktin.maxlen = cipherblk;
358         pktin.data = (pktin.data == NULL ? malloc(cipherblk+APIEXTRA) :
359                       realloc(pktin.data, cipherblk+APIEXTRA));
360         if (!pktin.data)
361             fatalbox("Out of memory");
362     }
363
364     /*
365      * Acquire and decrypt the first block of the packet. This will
366      * contain the length and padding details.
367      */
368      for (i = len = 0; i < cipherblk; i++) {
369         while ((*datalen) == 0)
370             crReturn(cipherblk-i);
371         pktin.data[i] = *(*data)++;
372         (*datalen)--;
373     }
374 #ifdef FWHACK
375     if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
376         /* FIXME */
377     }
378 #endif
379     if (sccipher)
380         sccipher->decrypt(pktin.data, cipherblk);
381
382     /*
383      * Now get the length and padding figures.
384      */
385     len = GET_32BIT(pktin.data);
386     pad = pktin.data[4];
387
388     /*
389      * This enables us to deduce the payload length.
390      */
391     payload = len - pad - 1;
392
393     pktin.length = payload + 5;
394
395     /*
396      * So now we can work out the total packet length.
397      */
398     packetlen = len + 4;
399     maclen = scmac ? scmac->len : 0;
400
401     /*
402      * Adjust memory allocation if packet is too big.
403      */
404     if (pktin.maxlen < packetlen) {
405         pktin.maxlen = packetlen;
406         pktin.data = (pktin.data == NULL ? malloc(packetlen+APIEXTRA) :
407                       realloc(pktin.data, packetlen+APIEXTRA));
408         if (!pktin.data)
409             fatalbox("Out of memory");
410     }
411
412     /*
413      * Read and decrypt the remainder of the packet.
414      */
415     for (i = cipherblk; i < packetlen + maclen; i++) {
416         while ((*datalen) == 0)
417             crReturn(packetlen + maclen - i);
418         pktin.data[i] = *(*data)++;
419         (*datalen)--;
420     }
421     /* Decrypt everything _except_ the MAC. */
422     if (sccipher)
423         sccipher->decrypt(pktin.data + cipherblk, packetlen - cipherblk);
424
425 #if 0
426     debug(("Got packet len=%d pad=%d\r\n", len, pad));
427     for (i = 0; i < packetlen; i++)
428         debug(("  %02x", (unsigned char)pktin.data[i]));
429     debug(("\r\n"));
430 #endif
431
432     /*
433      * Check the MAC.
434      */
435     if (scmac && !scmac->verify(pktin.data, len+4, incoming_sequence))
436         fatalbox("Incorrect MAC received on packet");
437     incoming_sequence++;               /* whether or not we MACed */
438
439     pktin.savedpos = 6;
440     pktin.type = pktin.data[5];
441
442     if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
443         goto next_packet;              /* FIXME: print DEBUG message */
444
445     crFinish(0);
446 }
447
448 static void ssh_gotdata(unsigned char *data, int datalen)
449 {
450     while (datalen > 0) {
451         if ( s_rdpkt(&data, &datalen) == 0 ) {
452             ssh_protocol(NULL, 0, 1);
453             if (ssh_state == SSH_STATE_CLOSED) {
454                 return;
455             }
456         }
457     }
458 }
459
460
461 static void s_wrpkt_start(int type, int len) {
462     int pad, biglen;
463
464     len += 5;                          /* type and CRC */
465     pad = 8 - (len%8);
466     biglen = len + pad;
467
468     pktout.length = len-5;
469     if (pktout.maxlen < biglen) {
470         pktout.maxlen = biglen;
471 #ifdef MSCRYPTOAPI
472         /* Allocate enough buffer space for extra block
473          * for MS CryptEncrypt() */
474         pktout.data = (pktout.data == NULL ? malloc(biglen+12) :
475                        realloc(pktout.data, biglen+12));
476 #else
477         pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
478                        realloc(pktout.data, biglen+4));
479 #endif
480         if (!pktout.data)
481             fatalbox("Out of memory");
482     }
483
484     pktout.type = type;
485     pktout.body = pktout.data+4+pad+1;
486 }
487
488 static void s_wrpkt(void) {
489     int pad, len, biglen, i;
490     unsigned long crc;
491
492     len = pktout.length + 5;           /* type and CRC */
493     pad = 8 - (len%8);
494     biglen = len + pad;
495
496     pktout.body[-1] = pktout.type;
497     for (i=0; i<pad; i++)
498         pktout.data[i+4] = random_byte();
499     crc = crc32(pktout.data+4, biglen-4);
500     PUT_32BIT(pktout.data+biglen, crc);
501     PUT_32BIT(pktout.data, len);
502
503     if (cipher)
504         cipher->encrypt(pktout.data+4, biglen);
505
506     s_write(pktout.data, biglen+4);
507 }
508
509 /*
510  * Construct a packet with the specified contents and
511  * send it to the server.
512  */
513 static void send_packet(int pkttype, ...)
514 {
515     va_list args;
516     unsigned char *p, *argp, argchar;
517     unsigned long argint;
518     int pktlen, argtype, arglen;
519     Bignum bn;
520     int i;
521
522     pktlen = 0;
523     va_start(args, pkttype);
524     while ((argtype = va_arg(args, int)) != PKT_END) {
525         switch (argtype) {
526           case PKT_INT:
527             (void) va_arg(args, int);
528             pktlen += 4;
529             break;
530           case PKT_CHAR:
531             (void) va_arg(args, char);
532             pktlen++;
533             break;
534           case PKT_DATA:
535             (void) va_arg(args, unsigned char *);
536             arglen = va_arg(args, int);
537             pktlen += arglen;
538             break;
539           case PKT_STR:
540             argp = va_arg(args, unsigned char *);
541             arglen = strlen(argp);
542             pktlen += 4 + arglen;
543             break;
544           case PKT_BIGNUM:
545             bn = va_arg(args, Bignum);
546             i = 16 * bn[0] - 1;
547             while ( i > 0 && (bn[i/16+1] >> (i%16)) == 0 )
548                 i--;
549             pktlen += 2 + (i+7)/8;
550             break;
551           default:
552             assert(0);
553         }
554     }
555     va_end(args);
556
557     s_wrpkt_start(pkttype, pktlen);
558     p = pktout.body;
559
560     va_start(args, pkttype);
561     while ((argtype = va_arg(args, int)) != PKT_END) {
562         switch (argtype) {
563           case PKT_INT:
564             argint = va_arg(args, int);
565             PUT_32BIT(p, argint);
566             p += 4;
567             break;
568           case PKT_CHAR:
569             argchar = va_arg(args, unsigned char);
570             *p = argchar;
571             p++;
572             break;
573           case PKT_DATA:
574             argp = va_arg(args, unsigned char *);
575             arglen = va_arg(args, int);
576             memcpy(p, argp, arglen);
577             p += arglen;
578             break;
579           case PKT_STR:
580             argp = va_arg(args, unsigned char *);
581             arglen = strlen(argp);
582             PUT_32BIT(p, arglen);
583             memcpy(p + 4, argp, arglen);
584             p += 4 + arglen;
585             break;
586           case PKT_BIGNUM:
587             bn = va_arg(args, Bignum);
588             i = 16 * bn[0] - 1;
589             while ( i > 0 && (bn[i/16+1] >> (i%16)) == 0 )
590                 i--;
591             *p++ = (i >> 8) & 0xFF;
592             *p++ = i & 0xFF;
593             i = (i + 7) / 8;
594             while (i-- > 0) {
595                 if (i % 2)
596                     *p++ = bn[i/2+1] >> 8;
597                 else
598                     *p++ = bn[i/2+1] & 0xFF;
599             }
600             break;
601         }
602     }
603     va_end(args);
604
605     s_wrpkt();
606 }
607
608
609 /*
610  * Connect to specified host and port.
611  * Returns an error message, or NULL on success.
612  * Also places the canonical host name into `realhost'.
613  */
614 static char *connect_to_host(char *host, int port, char **realhost)
615 {
616     SOCKADDR_IN addr;
617     struct hostent *h;
618     unsigned long a;
619 #ifdef FWHACK
620     char *FWhost;
621     int FWport;
622 #endif
623
624     savedhost = malloc(1+strlen(host));
625     if (!savedhost)
626         fatalbox("Out of memory");
627     strcpy(savedhost, host);
628
629     if (port < 0)
630         port = 22;                     /* default ssh port */
631
632 #ifdef FWHACK
633     FWhost = host;
634     FWport = port;
635     host = FWSTR;
636     port = 23;
637 #endif
638
639     /*
640      * Try to find host.
641      */
642     if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
643         if ( (h = gethostbyname(host)) == NULL)
644             switch (WSAGetLastError()) {
645               case WSAENETDOWN: return "Network is down";
646               case WSAHOST_NOT_FOUND: case WSANO_DATA:
647                 return "Host does not exist";
648               case WSATRY_AGAIN: return "Host not found";
649               default: return "gethostbyname: unknown error";
650             }
651         memcpy (&a, h->h_addr, sizeof(a));
652         *realhost = h->h_name;
653     } else
654         *realhost = host;
655 #ifdef FWHACK
656     *realhost = FWhost;
657 #endif
658     a = ntohl(a);
659
660     /*
661      * Open socket.
662      */
663     s = socket(AF_INET, SOCK_STREAM, 0);
664     if (s == INVALID_SOCKET)
665         switch (WSAGetLastError()) {
666           case WSAENETDOWN: return "Network is down";
667           case WSAEAFNOSUPPORT: return "TCP/IP support not present";
668           default: return "socket(): unknown error";
669         }
670
671     /*
672      * Bind to local address.
673      */
674     addr.sin_family = AF_INET;
675     addr.sin_addr.s_addr = htonl(INADDR_ANY);
676     addr.sin_port = htons(0);
677     if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
678         switch (WSAGetLastError()) {
679           case WSAENETDOWN: return "Network is down";
680           default: return "bind(): unknown error";
681         }
682
683     /*
684      * Connect to remote address.
685      */
686     addr.sin_addr.s_addr = htonl(a);
687     addr.sin_port = htons((short)port);
688     if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
689         switch (WSAGetLastError()) {
690           case WSAENETDOWN: return "Network is down";
691           case WSAECONNREFUSED: return "Connection refused";
692           case WSAENETUNREACH: return "Network is unreachable";
693           case WSAEHOSTUNREACH: return "No route to host";
694           default: return "connect(): unknown error";
695         }
696
697 #ifdef FWHACK
698     send(s, "connect ", 8, 0);
699     send(s, FWhost, strlen(FWhost), 0);
700     {
701         char buf[20];
702         sprintf(buf, " %d\n", FWport);
703         send (s, buf, strlen(buf), 0);
704     }
705 #endif
706
707     return NULL;
708 }
709
710 static int ssh_versioncmp(char *a, char *b) {
711     char *ae, *be;
712     unsigned long av, bv;
713
714     av = strtoul(a, &ae, 10);
715     bv = strtoul(b, &be, 10);
716     if (av != bv) return (av < bv ? -1 : +1);
717     if (*ae == '.') ae++;
718     if (*be == '.') be++;
719     av = strtoul(ae, &ae, 10);
720     bv = strtoul(be, &be, 10);
721     if (av != bv) return (av < bv ? -1 : +1);
722     return 0;
723 }
724
725
726 /*
727  * Utility routine for putting an SSH-protocol `string' into a SHA
728  * state.
729  */
730 #include <stdio.h>
731 void sha_string(SHA_State *s, void *str, int len) {
732     unsigned char lenblk[4];
733 static FILE *fp;
734     PUT_32BIT(lenblk, len);
735 if (!fp) fp = fopen("h:\\statham\\windows\\putty\\data","wb");
736 fwrite(lenblk, 4, 1, fp);
737     SHA_Bytes(s, lenblk, 4);
738 fwrite(str, len, 1, fp);
739 fflush(fp);
740     SHA_Bytes(s, str, len);
741 }
742
743 /*
744  * SSH2 packet construction functions.
745  */
746 void ssh2_pkt_adddata(void *data, int len) {
747     pktout.length += len;
748     if (pktout.maxlen < pktout.length) {
749         pktout.maxlen = pktout.length + 256;
750         pktout.data = (pktout.data == NULL ? malloc(pktout.maxlen+APIEXTRA) :
751                        realloc(pktout.data, pktout.maxlen+APIEXTRA));
752         if (!pktout.data)
753             fatalbox("Out of memory");
754     }
755     memcpy(pktout.data+pktout.length-len, data, len);
756 }
757 void ssh2_pkt_addbyte(unsigned char byte) {
758     ssh2_pkt_adddata(&byte, 1);
759 }
760 void ssh2_pkt_init(int pkt_type) {
761     pktout.length = 5;
762     ssh2_pkt_addbyte((unsigned char)pkt_type);
763 }
764 void ssh2_pkt_addbool(unsigned char value) {
765     ssh2_pkt_adddata(&value, 1);
766 }
767 void ssh2_pkt_adduint32(unsigned long value) {
768     unsigned char x[4];
769     PUT_32BIT(x, value);
770     ssh2_pkt_adddata(x, 4);
771 }
772 void ssh2_pkt_addstring_start(void) {
773     ssh2_pkt_adduint32(0);
774     pktout.savedpos = pktout.length;
775 }
776 void ssh2_pkt_addstring_str(char *data) {
777     ssh2_pkt_adddata(data, strlen(data));
778     PUT_32BIT(pktout.data + pktout.savedpos - 4,
779               pktout.length - pktout.savedpos);
780 }
781 void ssh2_pkt_addstring_data(char *data, int len) {
782     ssh2_pkt_adddata(data, len);
783     PUT_32BIT(pktout.data + pktout.savedpos - 4,
784               pktout.length - pktout.savedpos);
785 }
786 void ssh2_pkt_addstring(char *data) {
787     ssh2_pkt_addstring_start();
788     ssh2_pkt_addstring_str(data);
789 }
790 char *ssh2_mpint_fmt(Bignum b, int *len) {
791     unsigned char *p;
792     int i, n = b[0];
793     p = malloc(n * 2 + 1);
794     if (!p)
795         fatalbox("out of memory");
796     p[0] = 0;
797     for (i = 0; i < n; i++) {
798         p[i*2+1] = (b[n-i] >> 8) & 0xFF;
799         p[i*2+2] = (b[n-i]     ) & 0xFF;
800     }
801     i = 0;
802     while (p[i] == 0 && (p[i+1] & 0x80) == 0)
803         i++;
804     memmove(p, p+i, n*2+1-i);
805     *len = n*2+1-i;
806     return p;
807 }
808 void ssh2_pkt_addmp(Bignum b) {
809     unsigned char *p;
810     int len;
811     p = ssh2_mpint_fmt(b, &len);
812     ssh2_pkt_addstring_start();
813     ssh2_pkt_addstring_data(p, len);
814     free(p);
815 }
816 void ssh2_pkt_send(void) {
817     int cipherblk, maclen, padding, i;
818     static unsigned long outgoing_sequence = 0;
819
820     /*
821      * Add padding. At least four bytes, and must also bring total
822      * length (minus MAC) up to a multiple of the block size.
823      */
824     cipherblk = cipher ? cipher->blksize : 8;   /* block size */
825     cipherblk = cipherblk < 8 ? 8 : cipherblk;   /* or 8 if blksize < 8 */
826     padding = 4;
827     padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
828     pktout.data[4] = padding;
829     for (i = 0; i < padding; i++)
830         pktout.data[pktout.length + i] = random_byte();
831     PUT_32BIT(pktout.data, pktout.length + padding - 4);
832     if (csmac)
833         csmac->generate(pktout.data, pktout.length + padding,
834                         outgoing_sequence);
835     outgoing_sequence++;               /* whether or not we MACed */
836
837 #if 0
838     debug(("Sending packet len=%d\r\n", pktout.length+padding));
839     for (i = 0; i < pktout.length+padding; i++)
840         debug(("  %02x", (unsigned char)pktout.data[i]));
841     debug(("\r\n"));
842 #endif
843
844     if (cscipher)
845         cscipher->encrypt(pktout.data, pktout.length + padding);
846     maclen = csmac ? csmac->len : 0;
847
848     s_write(pktout.data, pktout.length + padding + maclen);
849 }
850
851 #if 0
852 void bndebug(char *string, Bignum b) {
853     unsigned char *p;
854     int i, len;
855     p = ssh2_mpint_fmt(b, &len);
856     debug(("%s", string));
857     for (i = 0; i < len; i++)
858         debug((" %02x", p[i]));
859     debug(("\r\n"));
860     free(p);
861 }
862 #endif
863
864 void sha_mpint(SHA_State *s, Bignum b) {
865     unsigned char *p;
866     int len;
867     p = ssh2_mpint_fmt(b, &len);
868     sha_string(s, p, len);
869     free(p);
870 }
871
872 /*
873  * SSH2 packet decode functions.
874  */
875 unsigned long ssh2_pkt_getuint32(void) {
876     unsigned long value;
877     if (pktin.length - pktin.savedpos < 4)
878         return 0;                      /* arrgh, no way to decline (FIXME?) */
879     value = GET_32BIT(pktin.data+pktin.savedpos);
880     pktin.savedpos += 4;
881     return value;
882 }
883 void ssh2_pkt_getstring(char **p, int *length) {
884     *p = NULL;
885     if (pktin.length - pktin.savedpos < 4)
886         return;
887     *length = GET_32BIT(pktin.data+pktin.savedpos);
888     pktin.savedpos += 4;
889     if (pktin.length - pktin.savedpos < *length)
890         return;
891     *p = pktin.data+pktin.savedpos;
892     pktin.savedpos += *length;
893 }
894 Bignum ssh2_pkt_getmp(void) {
895     char *p;
896     int i, j, length;
897     Bignum b;
898
899     ssh2_pkt_getstring(&p, &length);
900     if (!p)
901         return NULL;
902     if (p[0] & 0x80)
903         fatalbox("internal error: Can't handle negative mpints");
904     b = newbn((length+1)/2);
905     for (i = 0; i < length; i++) {
906         j = length - 1 - i;
907         if (j & 1)
908             b[j/2+1] |= ((unsigned char)p[i]) << 8;
909         else
910             b[j/2+1] |= ((unsigned char)p[i]);
911     }
912     return b;
913 }
914
915 static int do_ssh_init(void) {
916     char c, *vsp;
917     char version[10];
918     char vstring[80];
919     char vlog[sizeof(vstring)+20];
920     int i;
921
922 #ifdef FWHACK
923     i = 0;
924     while (s_read(&c, 1) == 1) {
925         if (c == 'S' && i < 2) i++;
926         else if (c == 'S' && i == 2) i = 2;
927         else if (c == 'H' && i == 2) break;
928         else i = 0;
929     }
930 #else
931     if (s_read(&c,1) != 1 || c != 'S') return 0;
932     if (s_read(&c,1) != 1 || c != 'S') return 0;
933     if (s_read(&c,1) != 1 || c != 'H') return 0;
934 #endif
935     strcpy(vstring, "SSH-");
936     vsp = vstring+4;
937     if (s_read(&c,1) != 1 || c != '-') return 0;
938     i = 0;
939     while (1) {
940         if (s_read(&c,1) != 1)
941             return 0;
942         if (vsp < vstring+sizeof(vstring)-1)
943             *vsp++ = c;
944         if (i >= 0) {
945             if (c == '-') {
946                 version[i] = '\0';
947                 i = -1;
948             } else if (i < sizeof(version)-1)
949                 version[i++] = c;
950         }
951         else if (c == '\n')
952             break;
953     }
954
955     *vsp = 0;
956     sprintf(vlog, "Server version: %s", vstring);
957     vlog[strcspn(vlog, "\r\n")] = '\0';
958     logevent(vlog);
959
960     if (ssh_versioncmp(version, "2.0" /* FIXME: "1.99" */ ) >= 0) {
961         /*
962          * This is a v2 server. Begin v2 protocol.
963          */
964         char *verstring = "SSH-2.0-PuTTY";
965         SHA_Init(&exhash);
966         /*
967          * Hash our version string and their version string.
968          */
969         sha_string(&exhash, verstring, strlen(verstring));
970         sha_string(&exhash, vstring, strcspn(vstring, "\r\n"));
971         sprintf(vstring, "%s\n", verstring);
972         sprintf(vlog, "We claim version: %s", verstring);
973         logevent(vlog);
974         logevent("Using SSH protocol version 2");
975         s_write(vstring, strlen(vstring));
976         ssh_protocol = ssh2_protocol;
977         ssh_version = 2;
978         s_rdpkt = ssh2_rdpkt;
979     } else {
980         /*
981          * This is a v1 server. Begin v1 protocol.
982          */
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';
987         logevent(vlog);
988         logevent("Using SSH protocol version 1");
989         s_write(vstring, strlen(vstring));
990         ssh_protocol = ssh1_protocol;
991         ssh_version = 1;
992         s_rdpkt = ssh1_rdpkt;
993     }
994     ssh_send_ok = 0;
995     return 1;
996 }
997
998 /*
999  * Handle the key exchange and user authentication phases.
1000  */
1001 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1002 {
1003     int i, j, len;
1004     unsigned char *rsabuf, *keystr1, *keystr2;
1005     unsigned char cookie[8];
1006     struct RSAKey servkey, hostkey;
1007     struct MD5Context md5c;
1008     static unsigned long supported_ciphers_mask, supported_auths_mask;
1009     static int tried_publickey;
1010     static unsigned char session_id[16];
1011     int cipher_type;
1012
1013     crBegin;
1014
1015     if (!ispkt) crWaitUntil(ispkt);
1016
1017     if (pktin.type != SSH1_SMSG_PUBLIC_KEY)
1018         fatalbox("Public key packet not received");
1019
1020     logevent("Received public keys");
1021
1022     memcpy(cookie, pktin.body, 8);
1023
1024     i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1025     j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1026
1027     /*
1028      * Hash the host key and print the hash in the log box. Just as
1029      * a last resort in case the registry's host key checking is
1030      * compromised, we'll allow the user some ability to verify
1031      * host keys by eye.
1032      */
1033     MD5Init(&md5c);
1034     MD5Update(&md5c, keystr2, hostkey.bytes);
1035     MD5Final(session_id, &md5c);
1036     {
1037         char logmsg[80];
1038         int i;
1039         logevent("Host key MD5 is:");
1040         strcpy(logmsg, "      ");
1041         for (i = 0; i < 16; i++)
1042             sprintf(logmsg+strlen(logmsg), "%02x", session_id[i]);
1043         logevent(logmsg);
1044     }
1045
1046     supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1047     supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1048
1049     MD5Init(&md5c);
1050     MD5Update(&md5c, keystr2, hostkey.bytes);
1051     MD5Update(&md5c, keystr1, servkey.bytes);
1052     MD5Update(&md5c, pktin.body, 8);
1053     MD5Final(session_id, &md5c);
1054
1055     for (i=0; i<32; i++)
1056         session_key[i] = random_byte();
1057
1058     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1059
1060     rsabuf = malloc(len);
1061     if (!rsabuf)
1062         fatalbox("Out of memory");
1063
1064     /*
1065      * Verify the host key.
1066      */
1067     {
1068         /*
1069          * First format the key into a string.
1070          */
1071         int len = rsastr_len(&hostkey);
1072         char *keystr = malloc(len);
1073         if (!keystr)
1074             fatalbox("Out of memory");
1075         rsastr_fmt(keystr, &hostkey);
1076         verify_ssh_host_key(savedhost, keystr);
1077         free(keystr);
1078     }
1079
1080     for (i=0; i<32; i++) {
1081         rsabuf[i] = session_key[i];
1082         if (i < 16)
1083             rsabuf[i] ^= session_id[i];
1084     }
1085
1086     if (hostkey.bytes > servkey.bytes) {
1087         rsaencrypt(rsabuf, 32, &servkey);
1088         rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1089     } else {
1090         rsaencrypt(rsabuf, 32, &hostkey);
1091         rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1092     }
1093
1094     logevent("Encrypted session key");
1095
1096     cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
1097                   cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES : 
1098                   SSH_CIPHER_3DES;
1099     if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1100         c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1101         cipher_type = SSH_CIPHER_3DES;
1102     }
1103     switch (cipher_type) {
1104       case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1105       case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1106       case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1107     }
1108
1109     send_packet(SSH1_CMSG_SESSION_KEY,
1110                 PKT_CHAR, cipher_type,
1111                 PKT_DATA, cookie, 8,
1112                 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1113                 PKT_DATA, rsabuf, len,
1114                 PKT_INT, 0,
1115                 PKT_END);
1116
1117     logevent("Trying to enable encryption...");
1118
1119     free(rsabuf);
1120
1121     cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
1122              cipher_type == SSH_CIPHER_DES ? &ssh_des :
1123              &ssh_3des;
1124     cipher->sesskey(session_key);
1125
1126     crWaitUntil(ispkt);
1127
1128     if (pktin.type != SSH1_SMSG_SUCCESS)
1129         fatalbox("Encryption not successfully enabled");
1130
1131     logevent("Successfully started encryption");
1132
1133     fflush(stdout);
1134     {
1135         static char username[100];
1136         static int pos = 0;
1137         static char c;
1138         if (!(flags & FLAG_CONNECTION) && !*cfg.username) {
1139             c_write("login as: ", 10);
1140             while (pos >= 0) {
1141                 crWaitUntil(!ispkt);
1142                 while (inlen--) switch (c = *in++) {
1143                   case 10: case 13:
1144                     username[pos] = 0;
1145                     pos = -1;
1146                     break;
1147                   case 8: case 127:
1148                     if (pos > 0) {
1149                         c_write("\b \b", 3);
1150                         pos--;
1151                     }
1152                     break;
1153                   case 21: case 27:
1154                     while (pos > 0) {
1155                         c_write("\b \b", 3);
1156                         pos--;
1157                     }
1158                     break;
1159                   case 3: case 4:
1160                     random_save_seed();
1161                     exit(0);
1162                     break;
1163                   default:
1164                     if (((c >= ' ' && c <= '~') ||
1165                          ((unsigned char)c >= 160)) && pos < 40) {
1166                         username[pos++] = c;
1167                         c_write(&c, 1);
1168                     }
1169                     break;
1170                 }
1171             }
1172             c_write("\r\n", 2);
1173             username[strcspn(username, "\n\r")] = '\0';
1174         } else {
1175             char stuff[200];
1176             strncpy(username, cfg.username, 99);
1177             username[99] = '\0';
1178             if (flags & FLAG_VERBOSE) {
1179                 sprintf(stuff, "Sent username \"%s\".\r\n", username);
1180                 c_write(stuff, strlen(stuff));
1181             }
1182         }
1183
1184         send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1185         {
1186             char userlog[20+sizeof(username)];
1187             sprintf(userlog, "Sent username \"%s\"", username);
1188             logevent(userlog);
1189         }
1190     }
1191
1192     crWaitUntil(ispkt);
1193
1194     tried_publickey = 0;
1195
1196     while (pktin.type == SSH1_SMSG_FAILURE) {
1197         static char password[100];
1198         static int pos;
1199         static char c;
1200         static int pwpkt_type;
1201         /*
1202          * Show password prompt, having first obtained it via a TIS
1203          * exchange if we're doing TIS authentication.
1204          */
1205         pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1206         if (*cfg.keyfile && !tried_publickey)
1207             pwpkt_type = SSH1_CMSG_AUTH_RSA;
1208
1209         if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD && !FLAG_WINDOWED) {
1210             char prompt[200];
1211             sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
1212             if (!ssh_get_password(prompt, password, sizeof(password))) {
1213                 /*
1214                  * get_password failed to get a password (for
1215                  * example because one was supplied on the command
1216                  * line which has already failed to work).
1217                  * Terminate.
1218                  */
1219                 logevent("No more passwords to try");
1220                 ssh_state = SSH_STATE_CLOSED;
1221                 crReturn(1);
1222             }
1223         } else {
1224
1225             if (pktin.type == SSH1_SMSG_FAILURE &&
1226                 cfg.try_tis_auth &&
1227                 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1228                 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1229                 logevent("Requested TIS authentication");
1230                 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1231                 crWaitUntil(ispkt);
1232                 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1233                     logevent("TIS authentication declined");
1234                     c_write("TIS authentication refused.\r\n", 29);
1235                 } else {
1236                     int challengelen = ((pktin.body[0] << 24) |
1237                                         (pktin.body[1] << 16) |
1238                                         (pktin.body[2] << 8) |
1239                                         (pktin.body[3]));
1240                     logevent("Received TIS challenge");
1241                     c_write(pktin.body+4, challengelen);
1242                 }
1243             }
1244             if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD)
1245                 c_write("password: ", 10);
1246             if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1247                 if (flags & FLAG_VERBOSE)
1248                     c_write("Trying public key authentication.\r\n", 35);
1249                 if (!rsakey_encrypted(cfg.keyfile)) {
1250                     if (flags & FLAG_VERBOSE)
1251                         c_write("No passphrase required.\r\n", 25);
1252                     goto tryauth;
1253                 }
1254                 c_write("passphrase: ", 12);
1255             }
1256
1257             pos = 0;
1258             while (pos >= 0) {
1259                 crWaitUntil(!ispkt);
1260                 while (inlen--) switch (c = *in++) {
1261                   case 10: case 13:
1262                     password[pos] = 0;
1263                     pos = -1;
1264                     break;
1265                   case 8: case 127:
1266                     if (pos > 0)
1267                         pos--;
1268                     break;
1269                   case 21: case 27:
1270                     pos = 0;
1271                     break;
1272                   case 3: case 4:
1273                     random_save_seed();
1274                     exit(0);
1275                     break;
1276                   default:
1277                     if (((c >= ' ' && c <= '~') ||
1278                          ((unsigned char)c >= 160)) && pos < sizeof(password))
1279                         password[pos++] = c;
1280                     break;
1281                 }
1282             }
1283             c_write("\r\n", 2);
1284
1285         }
1286
1287         tryauth:
1288         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1289             /*
1290              * Try public key authentication with the specified
1291              * key file.
1292              */
1293             static struct RSAKey pubkey;
1294             static Bignum challenge, response;
1295             static int i;
1296             static unsigned char buffer[32];
1297
1298             tried_publickey = 1;
1299             i = loadrsakey(cfg.keyfile, &pubkey, password);
1300             if (i == 0) {
1301                 c_write("Couldn't load public key from ", 30);
1302                 c_write(cfg.keyfile, strlen(cfg.keyfile));
1303                 c_write(".\r\n", 3);
1304                 continue;              /* go and try password */
1305             }
1306             if (i == -1) {
1307                 c_write("Wrong passphrase.\r\n", 19);
1308                 tried_publickey = 0;
1309                 continue;              /* try again */
1310             }
1311
1312             /*
1313              * Send a public key attempt.
1314              */
1315             send_packet(SSH1_CMSG_AUTH_RSA,
1316                         PKT_BIGNUM, pubkey.modulus, PKT_END);
1317
1318             crWaitUntil(ispkt);
1319             if (pktin.type == SSH1_SMSG_FAILURE) {
1320                 if (flags & FLAG_VERBOSE)
1321                     c_write("Server refused our public key.\r\n", 32);
1322                 continue;              /* go and try password */
1323             }
1324             if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE)
1325                 fatalbox("Bizarre response to offer of public key");
1326             ssh1_read_bignum(pktin.body, &challenge);
1327             response = rsadecrypt(challenge, &pubkey);
1328             freebn(pubkey.private_exponent);   /* burn the evidence */
1329
1330             for (i = 0; i < 32; i += 2) {
1331                 buffer[i] = response[16-i/2] >> 8;
1332                 buffer[i+1] = response[16-i/2] & 0xFF;
1333             }
1334
1335             MD5Init(&md5c);
1336             MD5Update(&md5c, buffer, 32);
1337             MD5Update(&md5c, session_id, 16);
1338             MD5Final(buffer, &md5c);
1339
1340             send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1341                         PKT_DATA, buffer, 16, PKT_END);
1342
1343             crWaitUntil(ispkt);
1344             if (pktin.type == SSH1_SMSG_FAILURE) {
1345                 if (flags & FLAG_VERBOSE)
1346                     c_write("Failed to authenticate with our public key.\r\n",
1347                             45);
1348                 continue;              /* go and try password */
1349             } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1350                 fatalbox("Bizarre response to RSA authentication response");
1351             }
1352
1353             break;                     /* we're through! */
1354         } else {
1355             send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1356         }
1357         logevent("Sent password");
1358         memset(password, 0, strlen(password));
1359         crWaitUntil(ispkt);
1360         if (pktin.type == SSH1_SMSG_FAILURE) {
1361             if (flags & FLAG_VERBOSE)
1362                 c_write("Access denied\r\n", 15);
1363             logevent("Authentication refused");
1364         } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1365             logevent("Received disconnect request");
1366             ssh_state = SSH_STATE_CLOSED;
1367             crReturn(1);
1368         } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1369             fatalbox("Strange packet received, type %d", pktin.type);
1370         }
1371     }
1372
1373     logevent("Authentication successful");
1374
1375     crFinish(1);
1376 }
1377
1378 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1379     crBegin;
1380
1381     random_init();
1382
1383     while (!do_ssh1_login(in, inlen, ispkt)) {
1384         crReturnV;
1385     }
1386     if (ssh_state == SSH_STATE_CLOSED)
1387         crReturnV;
1388
1389     if (!cfg.nopty) {
1390         send_packet(SSH1_CMSG_REQUEST_PTY,
1391                     PKT_STR, cfg.termtype,
1392                     PKT_INT, rows, PKT_INT, cols,
1393                     PKT_INT, 0, PKT_INT, 0,
1394                     PKT_CHAR, 0,
1395                     PKT_END);
1396         ssh_state = SSH_STATE_INTERMED;
1397         do { crReturnV; } while (!ispkt);
1398         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1399             fatalbox("Protocol confusion");
1400         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1401             c_write("Server refused to allocate pty\r\n", 32);
1402         }
1403         logevent("Allocated pty");
1404     }
1405
1406     if (*cfg.remote_cmd)
1407         send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1408     else
1409         send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1410     logevent("Started session");
1411
1412     ssh_state = SSH_STATE_SESSION;
1413     if (size_needed)
1414         ssh_size();
1415
1416     ssh_send_ok = 1;
1417     while (1) {
1418         crReturnV;
1419         if (ispkt) {
1420             if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1421                 pktin.type == SSH1_SMSG_STDERR_DATA) {
1422                 long len = GET_32BIT(pktin.body);
1423                 c_write(pktin.body+4, len);
1424             } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1425                 ssh_state = SSH_STATE_CLOSED;
1426                 logevent("Received disconnect request");
1427             } else if (pktin.type == SSH1_SMSG_SUCCESS) {
1428                 /* may be from EXEC_SHELL on some servers */
1429             } else if (pktin.type == SSH1_SMSG_FAILURE) {
1430                 /* may be from EXEC_SHELL on some servers
1431                  * if no pty is available or in other odd cases. Ignore */
1432             } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1433                 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
1434             } else {
1435                 fatalbox("Strange packet received: type %d", pktin.type);
1436             }
1437         } else {
1438             send_packet(SSH1_CMSG_STDIN_DATA,
1439                         PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
1440         }
1441     }
1442
1443     crFinishV;
1444 }
1445
1446 /*
1447  * Utility routine for decoding comma-separated strings in KEXINIT.
1448  */
1449 int in_commasep_string(char *needle, char *haystack, int haylen) {
1450     int needlen = strlen(needle);
1451     while (1) {
1452         /*
1453          * Is it at the start of the string?
1454          */
1455         if (haylen >= needlen &&       /* haystack is long enough */
1456             !memcmp(needle, haystack, needlen) &&    /* initial match */
1457             (haylen == needlen || haystack[needlen] == ',')
1458                                        /* either , or EOS follows */
1459             )
1460             return 1;
1461         /*
1462          * If not, search for the next comma and resume after that.
1463          * If no comma found, terminate.
1464          */
1465         while (haylen > 0 && *haystack != ',')
1466             haylen--, haystack++;
1467         if (haylen == 0)
1468             return 0;
1469         haylen--, haystack++;          /* skip over comma itself */
1470     }
1471 }
1472
1473 /*
1474  * SSH2 key creation method.
1475  */
1476 void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1477     SHA_State s;
1478     /* First 20 bytes. */
1479     SHA_Init(&s);
1480     sha_mpint(&s, K);
1481     SHA_Bytes(&s, H, 20);
1482     SHA_Bytes(&s, &chr, 1);
1483     SHA_Bytes(&s, H, 20);
1484     SHA_Final(&s, keyspace);
1485     /* Next 20 bytes. */
1486     SHA_Init(&s);
1487     sha_mpint(&s, K);
1488     SHA_Bytes(&s, H, 20);
1489     SHA_Bytes(&s, keyspace, 20);
1490     SHA_Final(&s, keyspace+20);
1491 }
1492
1493 /*
1494  * Handle the SSH2 transport layer.
1495  */
1496 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
1497 {
1498     static int i, len;
1499     static char *str;
1500     static Bignum e, f, K;
1501     static struct ssh_cipher *cscipher_tobe = NULL;
1502     static struct ssh_cipher *sccipher_tobe = NULL;
1503     static struct ssh_mac *csmac_tobe = NULL;
1504     static struct ssh_mac *scmac_tobe = NULL;
1505     static struct ssh_compress *cscomp_tobe = NULL;
1506     static struct ssh_compress *sccomp_tobe = NULL;
1507     static char *hostkeydata, *sigdata, *keystr;
1508     static int hostkeylen, siglen;
1509     static unsigned char exchange_hash[20];
1510     static unsigned char keyspace[40];
1511
1512     crBegin;
1513     random_init();
1514
1515     begin_key_exchange:
1516     /*
1517      * Construct and send our key exchange packet.
1518      */
1519     ssh2_pkt_init(SSH2_MSG_KEXINIT);
1520     for (i = 0; i < 16; i++)
1521         ssh2_pkt_addbyte((unsigned char)random_byte());
1522     /* List key exchange algorithms. */
1523     ssh2_pkt_addstring_start();
1524     for (i = 0; i < lenof(kex_algs); i++) {
1525         ssh2_pkt_addstring_str(kex_algs[i]->name);
1526         if (i < lenof(kex_algs)-1)
1527             ssh2_pkt_addstring_str(",");
1528     }
1529     /* List server host key algorithms. */
1530     ssh2_pkt_addstring_start();
1531     for (i = 0; i < lenof(hostkey_algs); i++) {
1532         ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1533         if (i < lenof(hostkey_algs)-1)
1534             ssh2_pkt_addstring_str(",");
1535     }
1536     /* List client->server encryption algorithms. */
1537     ssh2_pkt_addstring_start();
1538     for (i = 0; i < lenof(ciphers); i++) {
1539         ssh2_pkt_addstring_str(ciphers[i]->name);
1540         if (i < lenof(ciphers)-1)
1541             ssh2_pkt_addstring_str(",");
1542     }
1543     /* List server->client encryption algorithms. */
1544     ssh2_pkt_addstring_start();
1545     for (i = 0; i < lenof(ciphers); i++) {
1546         ssh2_pkt_addstring_str(ciphers[i]->name);
1547         if (i < lenof(ciphers)-1)
1548             ssh2_pkt_addstring_str(",");
1549     }
1550     /* List client->server MAC algorithms. */
1551     ssh2_pkt_addstring_start();
1552     for (i = 0; i < lenof(macs); i++) {
1553         ssh2_pkt_addstring_str(macs[i]->name);
1554         if (i < lenof(macs)-1)
1555             ssh2_pkt_addstring_str(",");
1556     }
1557     /* List server->client MAC algorithms. */
1558     ssh2_pkt_addstring_start();
1559     for (i = 0; i < lenof(macs); i++) {
1560         ssh2_pkt_addstring_str(macs[i]->name);
1561         if (i < lenof(macs)-1)
1562             ssh2_pkt_addstring_str(",");
1563     }
1564     /* List client->server compression algorithms. */
1565     ssh2_pkt_addstring_start();
1566     for (i = 0; i < lenof(compressions); i++) {
1567         ssh2_pkt_addstring_str(compressions[i]->name);
1568         if (i < lenof(compressions)-1)
1569             ssh2_pkt_addstring_str(",");
1570     }
1571     /* List server->client compression algorithms. */
1572     ssh2_pkt_addstring_start();
1573     for (i = 0; i < lenof(compressions); i++) {
1574         ssh2_pkt_addstring_str(compressions[i]->name);
1575         if (i < lenof(compressions)-1)
1576             ssh2_pkt_addstring_str(",");
1577     }
1578     /* List client->server languages. Empty list. */
1579     ssh2_pkt_addstring_start();
1580     /* List server->client languages. Empty list. */
1581     ssh2_pkt_addstring_start();
1582     /* First KEX packet does _not_ follow, because we're not that brave. */
1583     ssh2_pkt_addbool(FALSE);
1584     /* Reserved. */
1585     ssh2_pkt_adduint32(0);
1586     sha_string(&exhash, pktout.data+5, pktout.length-5);
1587     ssh2_pkt_send();
1588
1589     if (!ispkt) crWaitUntil(ispkt);
1590     sha_string(&exhash, pktin.data+5, pktin.length-5);
1591
1592     /*
1593      * Now examine the other side's KEXINIT to see what we're up
1594      * to.
1595      */
1596     if (pktin.type != SSH2_MSG_KEXINIT) {
1597         fatalbox("expected key exchange packet from server");
1598     }
1599     kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1600     csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1601     pktin.savedpos += 16;              /* skip garbage cookie */
1602     ssh2_pkt_getstring(&str, &len);    /* key exchange algorithms */
1603     for (i = 0; i < lenof(kex_algs); i++) {
1604         if (in_commasep_string(kex_algs[i]->name, str, len)) {
1605             kex = kex_algs[i];
1606             break;
1607         }
1608     }
1609     ssh2_pkt_getstring(&str, &len);    /* host key algorithms */
1610     for (i = 0; i < lenof(hostkey_algs); i++) {
1611         if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1612             hostkey = hostkey_algs[i];
1613             break;
1614         }
1615     }
1616     ssh2_pkt_getstring(&str, &len);    /* client->server cipher */
1617     for (i = 0; i < lenof(ciphers); i++) {
1618         if (in_commasep_string(ciphers[i]->name, str, len)) {
1619             cscipher_tobe = ciphers[i];
1620             break;
1621         }
1622     }
1623     ssh2_pkt_getstring(&str, &len);    /* server->client cipher */
1624     for (i = 0; i < lenof(ciphers); i++) {
1625         if (in_commasep_string(ciphers[i]->name, str, len)) {
1626             sccipher_tobe = ciphers[i];
1627             break;
1628         }
1629     }
1630     ssh2_pkt_getstring(&str, &len);    /* client->server mac */
1631     for (i = 0; i < lenof(macs); i++) {
1632         if (in_commasep_string(macs[i]->name, str, len)) {
1633             csmac_tobe = macs[i];
1634             break;
1635         }
1636     }
1637     ssh2_pkt_getstring(&str, &len);    /* server->client mac */
1638     for (i = 0; i < lenof(macs); i++) {
1639         if (in_commasep_string(macs[i]->name, str, len)) {
1640             scmac_tobe = macs[i];
1641             break;
1642         }
1643     }
1644     ssh2_pkt_getstring(&str, &len);    /* client->server compression */
1645     for (i = 0; i < lenof(compressions); i++) {
1646         if (in_commasep_string(compressions[i]->name, str, len)) {
1647             cscomp_tobe = compressions[i];
1648             break;
1649         }
1650     }
1651     ssh2_pkt_getstring(&str, &len);    /* server->client compression */
1652     for (i = 0; i < lenof(compressions); i++) {
1653         if (in_commasep_string(compressions[i]->name, str, len)) {
1654             sccomp_tobe = compressions[i];
1655             break;
1656         }
1657     }
1658
1659     /*
1660      * Currently we only support Diffie-Hellman and DSS, so let's
1661      * bomb out if those aren't selected.
1662      */
1663     if (kex != &ssh_diffiehellman || hostkey != &ssh_dss)
1664         fatalbox("internal fault: chaos in SSH 2 transport layer");
1665
1666     /*
1667      * Now we begin the fun. Generate and send e for Diffie-Hellman.
1668      */
1669     e = dh_create_e();
1670     ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
1671     ssh2_pkt_addmp(e);
1672     ssh2_pkt_send();
1673
1674     crWaitUntil(ispkt);
1675     if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
1676         fatalbox("expected key exchange packet from server");
1677     }
1678     ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
1679     f = ssh2_pkt_getmp();
1680     ssh2_pkt_getstring(&sigdata, &siglen);
1681
1682     K = dh_find_K(f);
1683
1684     sha_string(&exhash, hostkeydata, hostkeylen);
1685     sha_mpint(&exhash, e);
1686     sha_mpint(&exhash, f);
1687     sha_mpint(&exhash, K);
1688     SHA_Final(&exhash, exchange_hash);
1689
1690 #if 0
1691     debug(("Exchange hash is:\r\n"));
1692     for (i = 0; i < 20; i++)
1693         debug((" %02x", exchange_hash[i]));
1694     debug(("\r\n"));
1695 #endif
1696
1697     hostkey->setkey(hostkeydata, hostkeylen);
1698     if (!hostkey->verifysig(sigdata, siglen, exchange_hash, 20))
1699         fatalbox("Server failed host key check");
1700
1701     /*
1702      * Expect SSH2_MSG_NEWKEYS from server.
1703      */
1704     crWaitUntil(ispkt);
1705     if (pktin.type != SSH2_MSG_NEWKEYS)
1706         fatalbox("expected new-keys packet from server");
1707
1708     /*
1709      * Authenticate remote host: verify host key. (We've already
1710      * checked the signature of the exchange hash.)
1711      */
1712     keystr = hostkey->fmtkey();
1713     verify_ssh_host_key(savedhost, keystr);
1714     free(keystr);
1715
1716     /*
1717      * Send SSH2_MSG_NEWKEYS.
1718      */
1719     ssh2_pkt_init(SSH2_MSG_NEWKEYS);
1720     ssh2_pkt_send();
1721
1722     /*
1723      * Create and initialise session keys.
1724      */
1725     cscipher = cscipher_tobe;
1726     sccipher = sccipher_tobe;
1727     csmac = csmac_tobe;
1728     scmac = scmac_tobe;
1729     cscomp = cscomp_tobe;
1730     sccomp = sccomp_tobe;
1731     /*
1732      * Set IVs after keys.
1733      */
1734     ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
1735     ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
1736     ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
1737     ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
1738     ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
1739     ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
1740
1741     /*
1742      * Now we're encrypting. Begin returning 1 to the protocol main
1743      * function so that other things can run on top of the
1744      * transport. If we ever see a KEXINIT, we must go back to the
1745      * start.
1746      */
1747     do {
1748         crReturn(1);
1749     } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
1750     goto begin_key_exchange;
1751
1752     crFinish(1);
1753 }
1754
1755 /*
1756  * SSH2: remote identifier for the main session channel.
1757  */
1758 static unsigned long ssh_remote_channel;
1759
1760 /*
1761  * Handle the SSH2 userauth and connection layers.
1762  */
1763 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
1764 {
1765     static unsigned long remote_winsize;
1766     static unsigned long remote_maxpkt;
1767
1768     crBegin;
1769
1770     /*
1771      * Request userauth protocol, and await a response to it.
1772      */
1773     ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
1774     ssh2_pkt_addstring("ssh-userauth");
1775     ssh2_pkt_send();
1776     crWaitUntilV(ispkt);
1777     if (pktin.type != SSH2_MSG_SERVICE_ACCEPT)
1778         fatalbox("Server refused user authentication protocol");
1779
1780     /*
1781      * FIXME: currently we support only password authentication.
1782      * (This places us technically in violation of the SSH2 spec.
1783      * We must fix this.)
1784      */
1785     while (1) {
1786         /*
1787          * Get a username and a password.
1788          */
1789         static char username[100];
1790         static char password[100];
1791         static int pos = 0;
1792         static char c;
1793
1794         if ((flags & FLAG_CONNECTION) && !*cfg.username) {
1795             c_write("login as: ", 10);
1796             while (pos >= 0) {
1797                 crWaitUntilV(!ispkt);
1798                 while (inlen--) switch (c = *in++) {
1799                   case 10: case 13:
1800                     username[pos] = 0;
1801                     pos = -1;
1802                     break;
1803                   case 8: case 127:
1804                     if (pos > 0) {
1805                         c_write("\b \b", 3);
1806                         pos--;
1807                     }
1808                     break;
1809                   case 21: case 27:
1810                     while (pos > 0) {
1811                         c_write("\b \b", 3);
1812                         pos--;
1813                     }
1814                     break;
1815                   case 3: case 4:
1816                     random_save_seed();
1817                     exit(0);
1818                     break;
1819                   default:
1820                     if (((c >= ' ' && c <= '~') ||
1821                          ((unsigned char)c >= 160)) && pos < 40) {
1822                         username[pos++] = c;
1823                         c_write(&c, 1);
1824                     }
1825                     break;
1826                 }
1827             }
1828             c_write("\r\n", 2);
1829             username[strcspn(username, "\n\r")] = '\0';
1830         } else {
1831             char stuff[200];
1832             strncpy(username, cfg.username, 99);
1833             username[99] = '\0';
1834             if (flags & FLAG_VERBOSE) {
1835                 sprintf(stuff, "Using username \"%s\".\r\n", username);
1836                 c_write(stuff, strlen(stuff));
1837             }
1838         }
1839
1840         if (!(flags & FLAG_WINDOWED)) {
1841             char prompt[200];
1842             sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
1843             if (!ssh_get_password(prompt, password, sizeof(password))) {
1844                 /*
1845                  * get_password failed to get a password (for
1846                  * example because one was supplied on the command
1847                  * line which has already failed to work).
1848                  * Terminate.
1849                  */
1850                 logevent("No more passwords to try");
1851                 ssh_state = SSH_STATE_CLOSED;
1852                 crReturnV;
1853             }
1854         } else {
1855             c_write("password: ", 10);
1856
1857             pos = 0;
1858             while (pos >= 0) {
1859                 crWaitUntilV(!ispkt);
1860                 while (inlen--) switch (c = *in++) {
1861                   case 10: case 13:
1862                     password[pos] = 0;
1863                     pos = -1;
1864                     break;
1865                   case 8: case 127:
1866                     if (pos > 0)
1867                         pos--;
1868                     break;
1869                   case 21: case 27:
1870                     pos = 0;
1871                     break;
1872                   case 3: case 4:
1873                     random_save_seed();
1874                     exit(0);
1875                     break;
1876                   default:
1877                     if (((c >= ' ' && c <= '~') ||
1878                          ((unsigned char)c >= 160)) && pos < 40)
1879                         password[pos++] = c;
1880                     break;
1881                 }
1882             }
1883             c_write("\r\n", 2);
1884         }
1885
1886         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
1887         ssh2_pkt_addstring(username);
1888         ssh2_pkt_addstring("ssh-connection");   /* service requested */
1889         ssh2_pkt_addstring("password");
1890         ssh2_pkt_addbool(FALSE);
1891         ssh2_pkt_addstring(password);
1892         ssh2_pkt_send();
1893
1894         crWaitUntilV(ispkt);
1895         if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
1896             c_write("Access denied\r\n", 15);
1897             logevent("Authentication refused");
1898         } else
1899             break;
1900     }
1901
1902     /*
1903      * Now we're authenticated for the connection protocol. The
1904      * connection protocol will automatically have started at this
1905      * point; there's no need to send SERVICE_REQUEST.
1906      */
1907
1908     /*
1909      * So now create a channel with a session in it.
1910      */
1911     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
1912     ssh2_pkt_addstring("session");
1913     ssh2_pkt_adduint32(100);           /* as good as any */
1914     ssh2_pkt_adduint32(0xFFFFFFFFUL);  /* very big window which we ignore */
1915     ssh2_pkt_adduint32(0xFFFFFFFFUL);  /* very big max pkt size */
1916     ssh2_pkt_send();
1917     crWaitUntilV(ispkt);
1918     if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
1919         fatalbox("Server refused to open a session");
1920         /* FIXME: error data comes back in FAILURE packet */
1921     }
1922     if (ssh2_pkt_getuint32() != 100) {
1923         fatalbox("Server's channel confirmation cited wrong channel");
1924     }
1925     ssh_remote_channel = ssh2_pkt_getuint32();
1926     remote_winsize = ssh2_pkt_getuint32();
1927     remote_maxpkt = ssh2_pkt_getuint32();
1928     logevent("Opened channel for session");
1929
1930     /*
1931      * Now allocate a pty for the session.
1932      */
1933     ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
1934     ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
1935     ssh2_pkt_addstring("pty-req");
1936     ssh2_pkt_addbool(1);               /* want reply */
1937     ssh2_pkt_addstring(cfg.termtype);
1938     ssh2_pkt_adduint32(cols);
1939     ssh2_pkt_adduint32(rows);
1940     ssh2_pkt_adduint32(0);             /* pixel width */
1941     ssh2_pkt_adduint32(0);             /* pixel height */
1942     ssh2_pkt_addstring_start();
1943     ssh2_pkt_addstring_data("\0", 1);  /* TTY_OP_END, no special options */
1944     ssh2_pkt_send();
1945
1946     do {                               /* FIXME: pay attention to these */
1947         crWaitUntilV(ispkt);
1948     } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1949
1950     if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
1951         if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
1952             fatalbox("Server got confused by pty request");
1953         }
1954         c_write("Server refused to allocate pty\r\n", 32);
1955     } else {
1956         logevent("Allocated pty");
1957     }
1958
1959     /*
1960      * Start a shell.
1961      */
1962     ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
1963     ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
1964     ssh2_pkt_addstring("shell");
1965     ssh2_pkt_addbool(1);               /* want reply */
1966     ssh2_pkt_send();
1967     do {                               /* FIXME: pay attention to these */
1968         crWaitUntilV(ispkt);
1969     } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1970     if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
1971         if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
1972             fatalbox("Server got confused by shell request");
1973         }
1974         fatalbox("Server refused to start a shell");
1975     } else {
1976         logevent("Started a shell");
1977     }
1978
1979     /*
1980      * Transfer data!
1981      */
1982     ssh_send_ok = 1;
1983     while (1) {
1984         crReturnV;
1985         if (ispkt) {
1986             if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
1987                 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1988                 char *data;
1989                 int length;
1990                 if (ssh2_pkt_getuint32() != 100)
1991                     continue;          /* wrong channel */
1992                 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
1993                     ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
1994                     continue;          /* extended but not stderr */
1995                 ssh2_pkt_getstring(&data, &length);
1996                 if (data)
1997                     c_write(data, length);
1998             } else if (pktin.type == SSH2_MSG_DISCONNECT) {
1999                 ssh_state = SSH_STATE_CLOSED;
2000                 logevent("Received disconnect request");
2001             } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2002                 continue;              /* exit status et al; ignore (FIXME?) */
2003             } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2004                 continue;              /* ignore for now (FIXME!) */
2005             } else {
2006                 fatalbox("Strange packet received: type %d", pktin.type);
2007             }
2008         } else {
2009             /* FIXME: for now, ignore window size */
2010             ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2011             ssh2_pkt_adduint32(ssh_remote_channel);
2012             ssh2_pkt_addstring_start();
2013             ssh2_pkt_addstring_data(in, inlen);
2014             ssh2_pkt_send();
2015         }
2016     }
2017
2018     crFinishV;
2019 }
2020
2021 /*
2022  * Handle the top-level SSH2 protocol.
2023  */
2024 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2025 {
2026     if (do_ssh2_transport(in, inlen, ispkt) == 0)
2027         return;
2028     do_ssh2_authconn(in, inlen, ispkt);
2029 }
2030
2031 /*
2032  * Called to set up the connection. Will arrange for WM_NETEVENT
2033  * messages to be passed to the specified window, whose window
2034  * procedure should then call telnet_msg().
2035  *
2036  * Returns an error message, or NULL on success.
2037  */
2038 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
2039     char *p;
2040         
2041 #ifdef MSCRYPTOAPI
2042     if(crypto_startup() == 0)
2043         return "Microsoft high encryption pack not installed!";
2044 #endif
2045
2046     p = connect_to_host(host, port, realhost);
2047     if (p != NULL)
2048         return p;
2049
2050     if (!do_ssh_init())
2051         return "Protocol initialisation error";
2052
2053     if (hwnd && WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
2054         switch (WSAGetLastError()) {
2055           case WSAENETDOWN: return "Network is down";
2056           default: return "WSAAsyncSelect(): unknown error";
2057         }
2058
2059     return NULL;
2060 }
2061
2062 /*
2063  * Process a WM_NETEVENT message. Will return 0 if the connection
2064  * has closed, or <0 for a socket error.
2065  */
2066 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
2067     int ret;
2068     char buf[256];
2069
2070     /*
2071      * Because reading less than the whole of the available pending
2072      * data can generate an FD_READ event, we need to allow for the
2073      * possibility that FD_READ may arrive with FD_CLOSE already in
2074      * the queue; so it's possible that we can get here even with s
2075      * invalid. If so, we return 1 and don't worry about it.
2076      */
2077     if (s == INVALID_SOCKET)
2078         return 1;
2079
2080     if (WSAGETSELECTERROR(lParam) != 0)
2081         return -WSAGETSELECTERROR(lParam);
2082
2083     switch (WSAGETSELECTEVENT(lParam)) {
2084       case FD_READ:
2085       case FD_CLOSE:
2086         ret = recv(s, buf, sizeof(buf), 0);
2087         if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
2088             return 1;
2089         if (ret < 0)                   /* any _other_ error */
2090             return -10000-WSAGetLastError();
2091         if (ret == 0) {
2092             s = INVALID_SOCKET;
2093             return 0;
2094         }
2095         ssh_gotdata (buf, ret);
2096         if (ssh_state == SSH_STATE_CLOSED) {
2097             closesocket(s);
2098             s = INVALID_SOCKET;
2099             return 0;
2100         }
2101         return 1;
2102     }
2103     return 1;                          /* shouldn't happen, but WTF */
2104 }
2105
2106 /*
2107  * Called to send data down the Telnet connection.
2108  */
2109 static void ssh_send (char *buf, int len) {
2110     if (s == INVALID_SOCKET)
2111         return;
2112
2113     ssh_protocol(buf, len, 0);
2114 }
2115
2116 /*
2117  * Called to set the size of the window from Telnet's POV.
2118  */
2119 static void ssh_size(void) {
2120     switch (ssh_state) {
2121       case SSH_STATE_BEFORE_SIZE:
2122       case SSH_STATE_CLOSED:
2123         break;                         /* do nothing */
2124       case SSH_STATE_INTERMED:
2125         size_needed = TRUE;            /* buffer for later */
2126         break;
2127       case SSH_STATE_SESSION:
2128         if (!cfg.nopty) {
2129             send_packet(SSH1_CMSG_WINDOW_SIZE,
2130                         PKT_INT, rows, PKT_INT, cols,
2131                         PKT_INT, 0, PKT_INT, 0, PKT_END);
2132         }
2133     }
2134 }
2135
2136 /*
2137  * Send Telnet special codes. TS_EOF is useful for `plink', so you
2138  * can send an EOF and collect resulting output (e.g. `plink
2139  * hostname sort').
2140  */
2141 static void ssh_special (Telnet_Special code) {
2142     if (code == TS_EOF) {
2143         if (ssh_version = 1) {
2144             send_packet(SSH1_CMSG_EOF, PKT_END);
2145         } else {
2146             ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
2147             ssh2_pkt_adduint32(ssh_remote_channel);
2148             ssh2_pkt_send();
2149         }
2150     } else {
2151         /* do nothing */
2152     }
2153 }
2154
2155
2156 /*
2157  * Read and decrypt one incoming SSH packet.
2158  * (only used by pSCP)
2159  */
2160 static void get_packet(void)
2161 {
2162     unsigned char buf[4096], *p;
2163     long to_read;
2164     int len;
2165
2166     p = NULL;
2167     len = 0;
2168
2169     while ((to_read = s_rdpkt(&p, &len)) > 0) {
2170         if (to_read > sizeof(buf)) to_read = sizeof(buf);
2171         len = s_read(buf, to_read);
2172         if (len != to_read) {
2173             closesocket(s);
2174             s = INVALID_SOCKET;
2175             return;
2176         }
2177         p = buf;
2178     }
2179
2180     assert(len == 0);
2181 }
2182
2183 /*
2184  * Receive a block of data over the SSH link. Block until
2185  * all data is available. Return nr of bytes read (0 if lost connection).
2186  * (only used by pSCP)
2187  */
2188 int ssh_scp_recv(unsigned char *buf, int len)
2189 {
2190     static int pending_input_len = 0;
2191     static unsigned char *pending_input_ptr;
2192     int to_read = len;
2193
2194     if (pending_input_len >= to_read) {
2195         memcpy(buf, pending_input_ptr, to_read);
2196         pending_input_ptr += to_read;
2197         pending_input_len -= to_read;
2198         return len;
2199     }
2200     
2201     if (pending_input_len > 0) {
2202         memcpy(buf, pending_input_ptr, pending_input_len);
2203         buf += pending_input_len;
2204         to_read -= pending_input_len;
2205         pending_input_len = 0;
2206     }
2207
2208     if (s == INVALID_SOCKET)
2209         return 0;
2210     while (to_read > 0) {
2211         get_packet();
2212         if (s == INVALID_SOCKET)
2213             return 0;
2214         if (pktin.type == SSH1_SMSG_STDOUT_DATA) {
2215             int plen = GET_32BIT(pktin.body);
2216             if (plen <= to_read) {
2217                 memcpy(buf, pktin.body + 4, plen);
2218                 buf += plen;
2219                 to_read -= plen;
2220             } else {
2221                 memcpy(buf, pktin.body + 4, to_read);
2222                 pending_input_len = plen - to_read;
2223                 pending_input_ptr = pktin.body + 4 + to_read;
2224                 to_read = 0;
2225             }
2226         } else if (pktin.type == SSH1_SMSG_STDERR_DATA) {
2227             int plen = GET_32BIT(pktin.body);
2228             fwrite(pktin.body + 4, plen, 1, stderr);
2229         } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2230                 logevent("Received disconnect request");
2231         } else if (pktin.type == SSH1_SMSG_SUCCESS ||
2232                    pktin.type == SSH1_SMSG_FAILURE) {
2233                 /* ignore */
2234         } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2235             char logbuf[100];
2236             sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
2237             logevent(logbuf);
2238             send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2239             logevent("Closing connection");
2240             closesocket(s);
2241             s = INVALID_SOCKET;
2242         } else {
2243             fatalbox("Strange packet received: type %d", pktin.type);
2244         }
2245     }
2246
2247     return len;
2248 }
2249
2250 /*
2251  * Send a block of data over the SSH link.
2252  * Block until all data is sent.
2253  * (only used by pSCP)
2254  */
2255 void ssh_scp_send(unsigned char *buf, int len)
2256 {
2257     if (s == INVALID_SOCKET)
2258         return;
2259     send_packet(SSH1_CMSG_STDIN_DATA,
2260                 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2261 }
2262
2263 /*
2264  * Send an EOF notification to the server.
2265  * (only used by pSCP)
2266  */
2267 void ssh_scp_send_eof(void)
2268 {
2269     if (s == INVALID_SOCKET)
2270         return;
2271     send_packet(SSH1_CMSG_EOF, PKT_END);
2272 }
2273
2274 /*
2275  * Set up the connection, login on the remote host and
2276  * start execution of a command.
2277  * Returns an error message, or NULL on success.
2278  * (only used by pSCP)
2279  */
2280 char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
2281 {
2282     char buf[160], *p;
2283
2284 #ifdef MSCRYPTOAPI
2285     if (crypto_startup() == 0)
2286         return "Microsoft high encryption pack not installed!";
2287 #endif
2288
2289     p = connect_to_host(host, port, realhost);
2290     if (p != NULL)
2291         return p;
2292
2293     random_init();
2294
2295     if (!do_ssh_init())
2296         return "Protocol initialisation error";
2297
2298     /* Exchange keys and login */
2299     do {
2300         get_packet();
2301         if (s == INVALID_SOCKET)
2302             return "Connection closed by remote host";
2303     } while (!do_ssh1_login(NULL, 0, 1));
2304
2305     if (ssh_state == SSH_STATE_CLOSED) {
2306         closesocket(s);
2307         s = INVALID_SOCKET;
2308         return "Session initialisation error";
2309     }
2310
2311     /* Execute command */
2312     sprintf(buf, "Sending command: %.100s", cmd);
2313     logevent(buf);
2314     send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
2315
2316     return NULL;
2317 }
2318
2319 static SOCKET ssh_socket(void) { return s; }
2320
2321 static int ssh_sendok(void) { return ssh_send_ok; }
2322
2323 Backend ssh_backend = {
2324     ssh_init,
2325     ssh_msg,
2326     ssh_send,
2327     ssh_size,
2328     ssh_special,
2329     ssh_socket,
2330     ssh_sendok
2331 };