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