]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
Security improvement: check that string length field in
[PuTTY.git] / ssh.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <winsock.h>
4
5 #include "putty.h"
6
7 #ifndef FALSE
8 #define FALSE 0
9 #endif
10 #ifndef TRUE
11 #define TRUE 1
12 #endif
13
14 #include "ssh.h"
15
16 #define SSH_MSG_DISCONNECT 1
17 #define SSH_SMSG_PUBLIC_KEY 2
18 #define SSH_CMSG_SESSION_KEY 3
19 #define SSH_CMSG_USER 4
20 #define SSH_CMSG_AUTH_PASSWORD 9
21 #define SSH_CMSG_REQUEST_PTY 10
22 #define SSH_CMSG_EXEC_SHELL 12
23 #define SSH_CMSG_STDIN_DATA 16
24 #define SSH_SMSG_STDOUT_DATA 17
25 #define SSH_SMSG_STDERR_DATA 18
26 #define SSH_SMSG_SUCCESS 14
27 #define SSH_SMSG_FAILURE 15
28 #define SSH_SMSG_EXITSTATUS 20
29 #define SSH_MSG_IGNORE 32
30 #define SSH_CMSG_EXIT_CONFIRMATION 33
31 #define SSH_MSG_DEBUG 36
32 #define SSH_CMSG_AUTH_TIS 39
33 #define SSH_SMSG_AUTH_TIS_CHALLENGE 40
34 #define SSH_CMSG_AUTH_TIS_RESPONSE 41
35
36 #define SSH_AUTH_TIS              5
37
38 /* Coroutine mechanics for the sillier bits of the code */
39 #define crBegin1        static int crLine = 0;
40 #define crBegin2        switch(crLine) { case 0:;
41 #define crBegin         crBegin1; crBegin2;
42 #define crFinish(z)     } crLine = 0; return (z)
43 #define crFinishV       } crLine = 0; return
44 #define crReturn(z)     \
45         do {\
46             crLine=__LINE__; return (z); case __LINE__:;\
47         } while (0)
48 #define crReturnV       \
49         do {\
50             crLine=__LINE__; return; case __LINE__:;\
51         } while (0)
52 #define crStop(z)       do{ crLine = 0; return (z); }while(0)
53 #define crStopV         do{ crLine = 0; return; }while(0)
54
55 #ifndef FALSE
56 #define FALSE 0
57 #endif
58 #ifndef TRUE
59 #define TRUE 1
60 #endif
61
62 static SOCKET s = INVALID_SOCKET;
63
64 static unsigned char session_key[32];
65 static struct ssh_cipher *cipher = NULL;
66
67 static char *savedhost;
68
69 static enum {
70     SSH_STATE_BEFORE_SIZE,
71     SSH_STATE_INTERMED,
72     SSH_STATE_SESSION,
73     SSH_STATE_CLOSED
74 } ssh_state = SSH_STATE_BEFORE_SIZE;
75
76 static int size_needed = FALSE;
77
78 static void s_write (char *buf, int len) {
79     while (len > 0) {
80         int i = send (s, buf, len, 0);
81         if (i > 0)
82             len -= i, buf += i;
83     }
84 }
85
86 static int s_read (char *buf, int len) {
87     int ret = 0;
88     while (len > 0) {
89         int i = recv (s, buf, len, 0);
90         if (i > 0)
91             len -= i, buf += i, ret += i;
92         else
93             return i;
94     }
95     return ret;
96 }
97
98 static void c_write (char *buf, int len) {
99     while (len--) {
100         int new_head = (inbuf_head + 1) & INBUF_MASK;
101         if (new_head != inbuf_reap) {
102             inbuf[inbuf_head] = *buf++;
103             inbuf_head = new_head;
104         } else {
105             term_out();
106             if( inbuf_head == inbuf_reap ) len++; else break;
107         }
108     }
109 }
110
111 struct Packet {
112     long length;
113     int type;
114     unsigned long crc;
115     unsigned char *data;
116     unsigned char *body;
117     long maxlen;
118 };
119
120 static struct Packet pktin = { 0, 0, 0, NULL, 0 };
121 static struct Packet pktout = { 0, 0, 0, NULL, 0 };
122
123 static void ssh_protocol(unsigned char *in, int inlen, int ispkt);
124 static void ssh_size(void);
125
126 static void ssh_gotdata(unsigned char *data, int datalen) {
127     static long len, biglen, to_read;
128     static unsigned char *p;
129     static int i, pad;
130     static unsigned long realcrc, gotcrc;
131
132     crBegin;
133     while (1) {
134         for (i = len = 0; i < 4; i++) {
135             while (datalen == 0)
136                 crReturnV;
137             len = (len << 8) + *data;
138             data++, datalen--;
139         }
140
141 #ifdef FWHACK
142         if (len == 0x52656d6f) {       /* "Remo"te server has closed ... */
143             len = 0x300;               /* big enough to carry to end */
144         }
145 #endif
146
147         pad = 8 - (len%8);
148
149         biglen = len + pad;
150
151         len -= 5;                      /* type and CRC */
152
153         pktin.length = len;
154         if (pktin.maxlen < biglen) {
155             pktin.maxlen = biglen;
156 #ifdef MSCRYPTOAPI
157             /* Allocate enough buffer space for extra block
158              * for MS CryptEncrypt() */
159             pktin.data = (pktin.data == NULL ? malloc(biglen+8) :
160                           realloc(pktin.data, biglen+8));
161 #else
162             pktin.data = (pktin.data == NULL ? malloc(biglen) :
163                           realloc(pktin.data, biglen));
164 #endif
165             if (!pktin.data)
166                 fatalbox("Out of memory");
167         }
168
169         p = pktin.data, to_read = biglen;
170         while (to_read > 0) {
171             static int chunk;
172             chunk = to_read;
173             while (datalen == 0)
174                 crReturnV;
175             if (chunk > datalen)
176                 chunk = datalen;
177             memcpy(p, data, chunk);
178             data += chunk;
179             datalen -= chunk;
180             p += chunk;
181             to_read -= chunk;
182         }
183
184         if (cipher)
185             cipher->decrypt(pktin.data, biglen);
186
187         pktin.type = pktin.data[pad];
188         pktin.body = pktin.data+pad+1;
189
190         realcrc = crc32(pktin.data, biglen-4);
191         gotcrc = (pktin.data[biglen-4] << 24);
192         gotcrc |= (pktin.data[biglen-3] << 16);
193         gotcrc |= (pktin.data[biglen-2] <<  8);
194         gotcrc |= (pktin.data[biglen-1] <<  0);
195         if (gotcrc != realcrc) {
196             fatalbox("Incorrect CRC received on packet");
197         }
198
199         if (pktin.type == SSH_MSG_DEBUG) {
200             /* FIXME: log it */
201         } else if (pktin.type == SSH_MSG_IGNORE) {
202             /* do nothing */;
203         } else
204             ssh_protocol(NULL, 0, 1);
205     }
206     crFinishV;
207 }
208
209 static void s_wrpkt_start(int type, int len) {
210     int pad, biglen;
211
212     len += 5;                          /* type and CRC */
213     pad = 8 - (len%8);
214     biglen = len + pad;
215
216     pktout.length = len-5;
217     if (pktout.maxlen < biglen) {
218         pktout.maxlen = biglen;
219 #ifdef MSCRYPTOAPI
220         /* Allocate enough buffer space for extra block 
221          * for MS CryptEncrypt() */
222         pktout.data = (pktout.data == NULL ? malloc(biglen+8) :
223                        realloc(pktout.data, biglen+8));
224 #else
225         pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
226                        realloc(pktout.data, biglen+4));
227 #endif
228         if (!pktout.data)
229             fatalbox("Out of memory");
230     }
231
232     pktout.type = type;
233     pktout.body = pktout.data+4+pad+1;
234 }
235
236 static void s_wrpkt(void) {
237     int pad, len, biglen, i;
238     unsigned long crc;
239
240     len = pktout.length + 5;           /* type and CRC */
241     pad = 8 - (len%8);
242     biglen = len + pad;
243
244     pktout.body[-1] = pktout.type;
245     for (i=0; i<pad; i++)
246         pktout.data[i+4] = random_byte();
247     crc = crc32(pktout.data+4, biglen-4);
248
249     pktout.data[biglen+0] = (unsigned char) ((crc >> 24) & 0xFF);
250     pktout.data[biglen+1] = (unsigned char) ((crc >> 16) & 0xFF);
251     pktout.data[biglen+2] = (unsigned char) ((crc >> 8) & 0xFF);
252     pktout.data[biglen+3] = (unsigned char) (crc & 0xFF);
253
254     pktout.data[0] = (len >> 24) & 0xFF;
255     pktout.data[1] = (len >> 16) & 0xFF;
256     pktout.data[2] = (len >> 8) & 0xFF;
257     pktout.data[3] = len & 0xFF;
258
259     if (cipher)
260         cipher->encrypt(pktout.data+4, biglen);
261
262     s_write(pktout.data, biglen+4);
263 }
264
265 static int ssh_versioncmp(char *a, char *b) {
266     char *ae, *be;
267     unsigned long av, bv;
268
269     av = strtoul(a, &ae, 10);
270     bv = strtoul(b, &be, 10);
271     if (av != bv) return (av < bv ? -1 : +1);
272     if (*ae == '.') ae++;
273     if (*be == '.') be++;
274     av = strtoul(ae, &ae, 10);
275     bv = strtoul(be, &be, 10);
276     if (av != bv) return (av < bv ? -1 : +1);
277     return 0;
278 }
279
280 static int do_ssh_init(void) {
281     char c, *vsp;
282     char version[10];
283     char vstring[80];
284     char vlog[sizeof(vstring)+20];
285     int i;
286
287 #ifdef FWHACK
288     i = 0;
289     while (s_read(&c, 1) == 1) {
290         if (c == 'S' && i < 2) i++;
291         else if (c == 'S' && i == 2) i = 2;
292         else if (c == 'H' && i == 2) break;
293         else i = 0;
294     }
295 #else
296     if (s_read(&c,1) != 1 || c != 'S') return 0;
297     if (s_read(&c,1) != 1 || c != 'S') return 0;
298     if (s_read(&c,1) != 1 || c != 'H') return 0;
299 #endif
300     strcpy(vstring, "SSH-");
301     vsp = vstring+4;
302     if (s_read(&c,1) != 1 || c != '-') return 0;
303     i = 0;
304     while (1) {
305         if (s_read(&c,1) != 1)
306             return 0;
307         if (vsp < vstring+sizeof(vstring)-1)
308             *vsp++ = c;
309         if (i >= 0) {
310             if (c == '-') {
311                 version[i] = '\0';
312                 i = -1;
313             } else if (i < sizeof(version)-1)
314                 version[i++] = c;
315         }
316         else if (c == '\n')
317             break;
318     }
319
320     *vsp = 0;
321     sprintf(vlog, "Server version: %s", vstring);
322     vlog[strcspn(vlog, "\r\n")] = '\0';
323     logevent(vlog);
324
325     sprintf(vstring, "SSH-%s-PuTTY\n",
326             (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
327     sprintf(vlog, "We claim version: %s", vstring);
328     vlog[strcspn(vlog, "\r\n")] = '\0';
329     logevent(vlog);
330     s_write(vstring, strlen(vstring));
331     return 1;
332 }
333
334 static void ssh_protocol(unsigned char *in, int inlen, int ispkt) {
335     int i, j, len;
336     unsigned char session_id[16];
337     unsigned char *rsabuf, *keystr1, *keystr2;
338     unsigned char cookie[8];
339     struct RSAKey servkey, hostkey;
340     struct MD5Context md5c;
341     static unsigned long supported_ciphers_mask, supported_auths_mask;
342     int cipher_type;
343
344     extern struct ssh_cipher ssh_3des;
345     extern struct ssh_cipher ssh_des;
346     extern struct ssh_cipher ssh_blowfish;
347
348     crBegin;
349
350     random_init();
351
352     while (!ispkt)
353         crReturnV;
354
355     if (pktin.type != SSH_SMSG_PUBLIC_KEY)
356         fatalbox("Public key packet not received");
357
358     logevent("Received public keys");
359
360     memcpy(cookie, pktin.body, 8);
361
362     i = makekey(pktin.body+8, &servkey, &keystr1);
363
364     j = makekey(pktin.body+8+i, &hostkey, &keystr2);
365
366     /*
367      * Hash the host key and print the hash in the log box. Just as
368      * a last resort in case the registry's host key checking is
369      * compromised, we'll allow the user some ability to verify
370      * host keys by eye.
371      */
372     MD5Init(&md5c);
373     MD5Update(&md5c, keystr2, hostkey.bytes);
374     MD5Final(session_id, &md5c);
375     {
376         char logmsg[80];
377         int i;
378         logevent("Host key MD5 is:");
379         strcpy(logmsg, "      ");
380         for (i = 0; i < 16; i++)
381             sprintf(logmsg+strlen(logmsg), "%02x", session_id[i]);
382         logevent(logmsg);
383     }
384
385     supported_ciphers_mask = ((pktin.body[12+i+j] << 24) |
386                               (pktin.body[13+i+j] << 16) |
387                               (pktin.body[14+i+j] << 8) |
388                               (pktin.body[15+i+j]));
389
390     supported_auths_mask = ((pktin.body[16+i+j] << 24) |
391                             (pktin.body[17+i+j] << 16) |
392                             (pktin.body[18+i+j] << 8) |
393                             (pktin.body[19+i+j]));
394
395     MD5Init(&md5c);
396
397     MD5Update(&md5c, keystr2, hostkey.bytes);
398     MD5Update(&md5c, keystr1, servkey.bytes);
399     MD5Update(&md5c, pktin.body, 8);
400
401     MD5Final(session_id, &md5c);
402
403     for (i=0; i<32; i++)
404         session_key[i] = random_byte();
405
406     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
407
408     rsabuf = malloc(len);
409     if (!rsabuf)
410         fatalbox("Out of memory");
411
412     /*
413      * Verify the host key.
414      */
415     {
416         /*
417          * First format the key into a string.
418          */
419         int len = rsastr_len(&hostkey);
420         char *keystr = malloc(len);
421         if (!keystr)
422             fatalbox("Out of memory");
423         rsastr_fmt(keystr, &hostkey);
424         verify_ssh_host_key(savedhost, keystr);
425         free(keystr);
426     }
427
428     for (i=0; i<32; i++) {
429         rsabuf[i] = session_key[i];
430         if (i < 16)
431             rsabuf[i] ^= session_id[i];
432     }
433
434     if (hostkey.bytes > servkey.bytes) {
435         rsaencrypt(rsabuf, 32, &servkey);
436         rsaencrypt(rsabuf, servkey.bytes, &hostkey);
437     } else {
438         rsaencrypt(rsabuf, 32, &hostkey);
439         rsaencrypt(rsabuf, hostkey.bytes, &servkey);
440     }
441
442     logevent("Encrypted session key");
443
444     cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
445                   cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES : 
446                   SSH_CIPHER_3DES;
447     if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
448         c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
449         cipher_type = SSH_CIPHER_3DES;
450     }
451     switch (cipher_type) {
452       case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
453       case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
454       case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
455     }
456
457     s_wrpkt_start(SSH_CMSG_SESSION_KEY, len+15);
458     pktout.body[0] = cipher_type;
459     memcpy(pktout.body+1, cookie, 8);
460     pktout.body[9] = (len*8) >> 8;
461     pktout.body[10] = (len*8) & 0xFF;
462     memcpy(pktout.body+11, rsabuf, len);
463     pktout.body[len+11] = pktout.body[len+12] = 0;   /* protocol flags */
464     pktout.body[len+13] = pktout.body[len+14] = 0;
465     s_wrpkt();
466     logevent("Trying to enable encryption...");
467
468     free(rsabuf);
469
470     cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
471              cipher_type == SSH_CIPHER_DES ? &ssh_des :
472              &ssh_3des;
473     cipher->sesskey(session_key);
474
475     do { crReturnV; } while (!ispkt);
476
477     if (pktin.type != SSH_SMSG_SUCCESS)
478         fatalbox("Encryption not successfully enabled");
479
480     logevent("Successfully started encryption");
481
482     fflush(stdout);
483     {
484         static char username[100];
485         static int pos = 0;
486         static char c;
487         if (!*cfg.username) {
488             c_write("login as: ", 10);
489             while (pos >= 0) {
490                 do { crReturnV; } while (ispkt);
491                 while (inlen--) switch (c = *in++) {
492                   case 10: case 13:
493                     username[pos] = 0;
494                     pos = -1;
495                     break;
496                   case 8: case 127:
497                     if (pos > 0) {
498                         c_write("\b \b", 3);
499                         pos--;
500                     }
501                     break;
502                   case 21: case 27:
503                     while (pos > 0) {
504                         c_write("\b \b", 3);
505                         pos--;
506                     }
507                     break;
508                   case 3: case 4:
509                     random_save_seed();
510                     exit(0);
511                     break;
512                   default:
513                     if (((c >= ' ' && c <= '~') ||
514                          ((unsigned char)c >= 160)) && pos < 40) {
515                         username[pos++] = c;
516                         c_write(&c, 1);
517                     }
518                     break;
519                 }
520             }
521             c_write("\r\n", 2);
522             username[strcspn(username, "\n\r")] = '\0';
523         } else {
524             char stuff[200];
525             strncpy(username, cfg.username, 99);
526             username[99] = '\0';
527             sprintf(stuff, "Sent username \"%s\".\r\n", username);
528             c_write(stuff, strlen(stuff));
529         }
530         s_wrpkt_start(SSH_CMSG_USER, 4+strlen(username));
531         {
532             char userlog[20+sizeof(username)];
533             sprintf(userlog, "Sent username \"%s\"", username);
534             logevent(userlog);
535         }
536         pktout.body[0] = pktout.body[1] = pktout.body[2] = 0;
537         pktout.body[3] = strlen(username);
538         memcpy(pktout.body+4, username, strlen(username));
539         s_wrpkt();
540     }
541
542     do { crReturnV; } while (!ispkt);
543
544     while (pktin.type == SSH_SMSG_FAILURE) {
545         static char password[100];
546         static int pos;
547         static char c;
548         static int pwpkt_type;
549
550         /*
551          * Show password prompt, having first obtained it via a TIS
552          * exchange if we're doing TIS authentication.
553          */
554         pwpkt_type = SSH_CMSG_AUTH_PASSWORD;
555         if (pktin.type == SSH_SMSG_FAILURE &&
556             cfg.try_tis_auth &&
557             (supported_auths_mask & (1<<SSH_AUTH_TIS))) {
558             pwpkt_type = SSH_CMSG_AUTH_TIS_RESPONSE;
559             logevent("Requested TIS authentication");
560             s_wrpkt_start(SSH_CMSG_AUTH_TIS, 0);
561             s_wrpkt();
562             do { crReturnV; } while (!ispkt);
563             if (pktin.type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
564                 logevent("TIS authentication declined");
565                 c_write("TIS authentication refused.\r\n", 29);
566             } else {
567                 int challengelen = ((pktin.body[0] << 24) |
568                                     (pktin.body[1] << 16) |
569                                     (pktin.body[2] << 8) |
570                                     (pktin.body[3]));
571                 logevent("Received TIS challenge");
572                 c_write(pktin.body+4, challengelen);
573             }
574         }
575         if (pwpkt_type == SSH_CMSG_AUTH_PASSWORD)
576             c_write("password: ", 10);
577
578         pos = 0;
579         while (pos >= 0) {
580             do { crReturnV; } while (ispkt);
581             while (inlen--) switch (c = *in++) {
582               case 10: case 13:
583                 password[pos] = 0;
584                 pos = -1;
585                 break;
586               case 8: case 127:
587                 if (pos > 0)
588                     pos--;
589                 break;
590               case 21: case 27:
591                 pos = 0;
592                 break;
593               case 3: case 4:
594                 random_save_seed();
595                 exit(0);
596                 break;
597               default:
598                 if (((c >= ' ' && c <= '~') ||
599                      ((unsigned char)c >= 160)) && pos < 40)
600                     password[pos++] = c;
601                 break;
602             }
603         }
604         c_write("\r\n", 2);
605         s_wrpkt_start(pwpkt_type, 4+strlen(password));
606         pktout.body[0] = pktout.body[1] = pktout.body[2] = 0;
607         pktout.body[3] = strlen(password);
608         memcpy(pktout.body+4, password, strlen(password));
609         s_wrpkt();
610         logevent("Sent password");
611         memset(password, 0, strlen(password));
612         do { crReturnV; } while (!ispkt);
613         if (pktin.type == 15) {
614             c_write("Access denied\r\n", 15);
615             logevent("Authentication refused");
616         } else if (pktin.type != 14) {
617             fatalbox("Strange packet received, type %d", pktin.type);
618         }
619     }
620
621     logevent("Authentication successful");
622
623     if (!cfg.nopty) {
624         i = strlen(cfg.termtype);
625         s_wrpkt_start(SSH_CMSG_REQUEST_PTY, i+5*4+1);
626         pktout.body[0] = (i >> 24) & 0xFF;
627         pktout.body[1] = (i >> 16) & 0xFF;
628         pktout.body[2] = (i >> 8) & 0xFF;
629         pktout.body[3] = i & 0xFF;
630         memcpy(pktout.body+4, cfg.termtype, i);
631         i += 4;
632         pktout.body[i++] = (rows >> 24) & 0xFF;
633         pktout.body[i++] = (rows >> 16) & 0xFF;
634         pktout.body[i++] = (rows >> 8) & 0xFF;
635         pktout.body[i++] = rows & 0xFF;
636         pktout.body[i++] = (cols >> 24) & 0xFF;
637         pktout.body[i++] = (cols >> 16) & 0xFF;
638         pktout.body[i++] = (cols >> 8) & 0xFF;
639         pktout.body[i++] = cols & 0xFF;
640         memset(pktout.body+i, 0, 9);       /* 0 pixwidth, 0 pixheight, 0.b endofopt */
641         s_wrpkt();
642         ssh_state = SSH_STATE_INTERMED;
643         do { crReturnV; } while (!ispkt);
644         if (pktin.type != SSH_SMSG_SUCCESS && pktin.type != SSH_SMSG_FAILURE) {
645             fatalbox("Protocol confusion");
646         } else if (pktin.type == SSH_SMSG_FAILURE) {
647             c_write("Server refused to allocate pty\r\n", 32);
648         }
649         logevent("Allocated pty");
650     }
651
652     s_wrpkt_start(SSH_CMSG_EXEC_SHELL, 0);
653     s_wrpkt();
654     logevent("Started session");
655
656     ssh_state = SSH_STATE_SESSION;
657     if (size_needed)
658         ssh_size();
659
660     while (1) {
661         crReturnV;
662         if (ispkt) {
663             if (pktin.type == SSH_SMSG_STDOUT_DATA ||
664                 pktin.type == SSH_SMSG_STDERR_DATA) {
665                 long len = 0;
666                 for (i = 0; i < 4; i++)
667                     len = (len << 8) + pktin.body[i];
668                 if (len+4 != pktin.length) {
669                     logevent("Received data packet with bogus string length"
670                              ", ignoring");
671                 } else
672                     c_write(pktin.body+4, len);
673             } else if (pktin.type == SSH_MSG_DISCONNECT) {
674                 ssh_state = SSH_STATE_CLOSED;
675                 logevent("Received disconnect request");
676             } else if (pktin.type == SSH_SMSG_SUCCESS) {
677                 /* may be from EXEC_SHELL on some servers */
678             } else if (pktin.type == SSH_SMSG_FAILURE) {
679                 /* may be from EXEC_SHELL on some servers
680                  * if no pty is available or in other odd cases. Ignore */
681             } else if (pktin.type == SSH_SMSG_EXITSTATUS) {
682                 s_wrpkt_start(SSH_CMSG_EXIT_CONFIRMATION, 0);
683                 s_wrpkt();
684             } else {
685                 fatalbox("Strange packet received: type %d", pktin.type);
686             }
687         } else {
688             s_wrpkt_start(SSH_CMSG_STDIN_DATA, 4+inlen);
689             pktout.body[0] = (inlen >> 24) & 0xFF;
690             pktout.body[1] = (inlen >> 16) & 0xFF;
691             pktout.body[2] = (inlen >> 8) & 0xFF;
692             pktout.body[3] = inlen & 0xFF;
693             memcpy(pktout.body+4, in, inlen);
694             s_wrpkt();
695         }
696     }
697
698     crFinishV;
699 }
700
701 /*
702  * Called to set up the connection. Will arrange for WM_NETEVENT
703  * messages to be passed to the specified window, whose window
704  * procedure should then call telnet_msg().
705  *
706  * Returns an error message, or NULL on success.
707  *
708  * Also places the canonical host name into `realhost'.
709  */
710 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
711     SOCKADDR_IN addr;
712     struct hostent *h;
713     unsigned long a;
714 #ifdef FWHACK
715     char *FWhost;
716     int FWport;
717 #endif
718         
719 #ifdef MSCRYPTOAPI
720     if(crypto_startup() == 0)
721         return "Microsoft high encryption pack not installed!";
722 #endif
723
724     savedhost = malloc(1+strlen(host));
725     if (!savedhost)
726         fatalbox("Out of memory");
727     strcpy(savedhost, host);
728
729 #ifdef FWHACK
730     FWhost = host;
731     FWport = port;
732     host = FWSTR;
733     port = 23;
734 #endif
735
736     /*
737      * Try to find host.
738      */
739     if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
740         if ( (h = gethostbyname(host)) == NULL)
741             switch (WSAGetLastError()) {
742               case WSAENETDOWN: return "Network is down";
743               case WSAHOST_NOT_FOUND: case WSANO_DATA:
744                 return "Host does not exist";
745               case WSATRY_AGAIN: return "Host not found";
746               default: return "gethostbyname: unknown error";
747             }
748         memcpy (&a, h->h_addr, sizeof(a));
749         *realhost = h->h_name;
750     } else
751         *realhost = host;
752 #ifdef FWHACK
753     *realhost = FWhost;
754 #endif
755     a = ntohl(a);
756
757     if (port < 0)
758         port = 22;                     /* default ssh port */
759
760     /*
761      * Open socket.
762      */
763     s = socket(AF_INET, SOCK_STREAM, 0);
764     if (s == INVALID_SOCKET)
765         switch (WSAGetLastError()) {
766           case WSAENETDOWN: return "Network is down";
767           case WSAEAFNOSUPPORT: return "TCP/IP support not present";
768           default: return "socket(): unknown error";
769         }
770
771     /*
772      * Bind to local address.
773      */
774     addr.sin_family = AF_INET;
775     addr.sin_addr.s_addr = htonl(INADDR_ANY);
776     addr.sin_port = htons(0);
777     if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
778         switch (WSAGetLastError()) {
779           case WSAENETDOWN: return "Network is down";
780           default: return "bind(): unknown error";
781         }
782
783     /*
784      * Connect to remote address.
785      */
786     addr.sin_addr.s_addr = htonl(a);
787     addr.sin_port = htons((short)port);
788     if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
789         switch (WSAGetLastError()) {
790           case WSAENETDOWN: return "Network is down";
791           case WSAECONNREFUSED: return "Connection refused";
792           case WSAENETUNREACH: return "Network is unreachable";
793           case WSAEHOSTUNREACH: return "No route to host";
794           default: return "connect(): unknown error";
795         }
796
797 #ifdef FWHACK
798     send(s, "connect ", 8, 0);
799     send(s, FWhost, strlen(FWhost), 0);
800     {
801         char buf[20];
802         sprintf(buf, " %d\n", FWport);
803         send (s, buf, strlen(buf), 0);
804     }
805 #endif
806
807     if (!do_ssh_init())
808         return "Protocol initialisation error";
809
810     if (WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
811         switch (WSAGetLastError()) {
812           case WSAENETDOWN: return "Network is down";
813           default: return "WSAAsyncSelect(): unknown error";
814         }
815
816     return NULL;
817 }
818
819 /*
820  * Process a WM_NETEVENT message. Will return 0 if the connection
821  * has closed, or <0 for a socket error.
822  */
823 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
824     int ret;
825     char buf[256];
826
827     /*
828      * Because reading less than the whole of the available pending
829      * data can generate an FD_READ event, we need to allow for the
830      * possibility that FD_READ may arrive with FD_CLOSE already in
831      * the queue; so it's possible that we can get here even with s
832      * invalid. If so, we return 1 and don't worry about it.
833      */
834     if (s == INVALID_SOCKET)
835         return 1;
836
837     if (WSAGETSELECTERROR(lParam) != 0)
838         return -WSAGETSELECTERROR(lParam);
839
840     switch (WSAGETSELECTEVENT(lParam)) {
841       case FD_READ:
842       case FD_CLOSE:
843         ret = recv(s, buf, sizeof(buf), 0);
844         if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
845             return 1;
846         if (ret < 0)                   /* any _other_ error */
847             return -10000-WSAGetLastError();
848         if (ret == 0) {
849             s = INVALID_SOCKET;
850             return 0;
851         }
852         ssh_gotdata (buf, ret);
853         return 1;
854     }
855     return 1;                          /* shouldn't happen, but WTF */
856 }
857
858 /*
859  * Called to send data down the Telnet connection.
860  */
861 static void ssh_send (char *buf, int len) {
862     if (s == INVALID_SOCKET)
863         return;
864
865     ssh_protocol(buf, len, 0);
866 }
867
868 /*
869  * Called to set the size of the window from Telnet's POV.
870  */
871 static void ssh_size(void) {
872     switch (ssh_state) {
873       case SSH_STATE_BEFORE_SIZE:
874       case SSH_STATE_CLOSED:
875         break;                         /* do nothing */
876       case SSH_STATE_INTERMED:
877         size_needed = TRUE;            /* buffer for later */
878         break;
879       case SSH_STATE_SESSION:
880         if (!cfg.nopty) {
881             s_wrpkt_start(11, 16);
882             pktout.body[0] = (rows >> 24) & 0xFF;
883             pktout.body[1] = (rows >> 16) & 0xFF;
884             pktout.body[2] = (rows >> 8) & 0xFF;
885             pktout.body[3] = rows & 0xFF;
886             pktout.body[4] = (cols >> 24) & 0xFF;
887             pktout.body[5] = (cols >> 16) & 0xFF;
888             pktout.body[6] = (cols >> 8) & 0xFF;
889             pktout.body[7] = cols & 0xFF;
890             memset(pktout.body+8, 0, 8);
891             s_wrpkt();
892         }
893     }
894 }
895
896 /*
897  * (Send Telnet special codes)
898  */
899 static void ssh_special (Telnet_Special code) {
900     /* do nothing */
901 }
902
903 Backend ssh_backend = {
904     ssh_init,
905     ssh_msg,
906     ssh_send,
907     ssh_size,
908     ssh_special
909 };