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