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