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