]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
Menu items now turn on and off in a vaguely useful way.
[PuTTY.git] / ssh.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #ifndef macintosh
4 #include <winsock.h>
5 #endif /* not macintosh */
6
7 #include "putty.h"
8 #include "ssh.h"
9
10 /* Coroutine mechanics for the sillier bits of the code */
11 #define crBegin1        static int crLine = 0;
12 #define crBegin2        switch(crLine) { case 0:;
13 #define crBegin         crBegin1; crBegin2;
14 #define crFinish(z)     } crLine = 0; return (z)
15 #define crFinishV       } crLine = 0; return
16 #define crReturn(z)     \
17         do {\
18             crLine=__LINE__; return (z); case __LINE__:;\
19         } while (0)
20 #define crReturnV       \
21         do {\
22             crLine=__LINE__; return; case __LINE__:;\
23         } while (0)
24 #define crStop(z)       do{ crLine = 0; return (z); }while(0)
25 #define crStopV         do{ crLine = 0; return; }while(0)
26
27 #ifndef macintosh
28 static SOCKET s = INVALID_SOCKET;
29 #endif
30
31 static unsigned char session_key[32];
32 static struct ssh_cipher *cipher = NULL;
33
34 static char *savedhost;
35
36 static enum {
37     SSH_STATE_BEFORE_SIZE,
38     SSH_STATE_INTERMED,
39     SSH_STATE_SESSION
40 } ssh_state = SSH_STATE_BEFORE_SIZE;
41
42 static int size_needed = FALSE;
43
44 #ifdef macintosh
45 static void s_write (unsigned char *buf, int len) {
46     panic("s_write not implemented");
47 }
48 #else /* not macintosh */
49 static void s_write (char *buf, int len) {
50     while (len > 0) {
51         int i = send (s, buf, len, 0);
52         if (i > 0)
53             len -= i, buf += i;
54     }
55 }
56 #endif /* not macintosh */
57
58 #ifdef macintosh
59 static int s_read (unsigned char *buf, int len) {
60     panic("s_read not implemented");
61 }
62 #else /* not macintosh */
63 static int s_read (char *buf, int len) {
64     int ret = 0;
65     while (len > 0) {
66         int i = recv (s, buf, len, 0);
67         if (i > 0)
68             len -= i, buf += i, ret += i;
69         else
70             return i;
71     }
72     return ret;
73 }
74 #endif
75
76 static void c_write (char *buf, int len) {
77     while (len--) {
78         int new_head = (inbuf_head + 1) & INBUF_MASK;
79         int c = (unsigned char) *buf;
80         if (new_head != inbuf_reap) {
81             inbuf[inbuf_head] = *buf++;
82             inbuf_head = new_head;
83         }
84     }
85 }
86
87 struct Packet {
88     long length;
89     int type;
90     unsigned long crc;
91     unsigned char *data;
92     unsigned char *body;
93     long maxlen;
94 };
95
96 static struct Packet pktin = { 0, 0, 0, NULL, 0 };
97 static struct Packet pktout = { 0, 0, 0, NULL, 0 };
98
99 static void ssh_protocol(unsigned char *in, int inlen, int ispkt);
100 static void ssh_size(void);
101
102 static void ssh_gotdata(unsigned char *data, int datalen) {
103     static long len, biglen, to_read;
104     static unsigned char c, *p;
105     static int i, pad;
106     static char padding[8];
107     static unsigned char word[4];
108
109     crBegin;
110     while (1) {
111         for (i = len = 0; i < 4; i++) {
112             while (datalen == 0)
113                 crReturnV;
114             len = (len << 8) + *data;
115             data++, datalen--;
116         }
117
118 #ifdef FWHACK
119         if (len == 0x52656d6f) {       /* "Remo"te server has closed ... */
120             len = 0x300;               /* big enough to carry to end */
121         }
122 #endif
123
124         pad = 8 - (len%8);
125
126         biglen = len + pad;
127
128         len -= 5;                      /* type and CRC */
129
130         pktin.length = len;
131         if (pktin.maxlen < biglen) {
132             pktin.maxlen = biglen;
133             pktin.data = (pktin.data == NULL ? malloc(biglen) :
134                         realloc(pktin.data, biglen));
135             if (!pktin.data)
136                 fatalbox("Out of memory");
137         }
138
139         p = pktin.data, to_read = biglen;
140         while (to_read > 0) {
141             static int chunk;
142             chunk = to_read;
143             while (datalen == 0)
144                 crReturnV;
145             if (chunk > datalen)
146                 chunk = datalen;
147             memcpy(p, data, chunk);
148             data += chunk;
149             datalen -= chunk;
150             p += chunk;
151             to_read -= chunk;
152         }
153
154         if (cipher)
155             cipher->decrypt(pktin.data, biglen);
156
157         pktin.type = pktin.data[pad];
158         pktin.body = pktin.data+pad+1;
159
160         if (pktin.type == 36) {        /* SSH_MSG_DEBUG */
161             /* FIXME: log it */
162         } else
163             ssh_protocol(NULL, 0, 1);
164     }
165     crFinishV;
166 }
167
168 static void s_wrpkt_start(int type, int len) {
169     int pad, biglen;
170
171     len += 5;                          /* type and CRC */
172     pad = 8 - (len%8);
173     biglen = len + pad;
174
175     pktout.length = len-5;
176     if (pktout.maxlen < biglen) {
177         pktout.maxlen = biglen;
178         pktout.data = (pktout.data == NULL ? malloc(biglen) :
179                        realloc(pktout.data, biglen));
180         if (!pktout.data)
181             fatalbox("Out of memory");
182     }
183
184     pktout.type = type;
185     pktout.body = pktout.data+4+pad+1;
186 }
187
188 static void s_wrpkt(void) {
189     int pad, len, biglen, i;
190     unsigned long crc;
191
192     len = pktout.length + 5;           /* type and CRC */
193     pad = 8 - (len%8);
194     biglen = len + pad;
195
196     pktout.body[-1] = pktout.type;
197     for (i=0; i<pad; i++)
198         pktout.data[i+4] = random_byte();
199     crc = crc32(pktout.data+4, biglen-4);
200
201     pktout.data[biglen+0] = (unsigned char) ((crc >> 24) & 0xFF);
202     pktout.data[biglen+1] = (unsigned char) ((crc >> 16) & 0xFF);
203     pktout.data[biglen+2] = (unsigned char) ((crc >> 8) & 0xFF);
204     pktout.data[biglen+3] = (unsigned char) (crc & 0xFF);
205
206     pktout.data[0] = (len >> 24) & 0xFF;
207     pktout.data[1] = (len >> 16) & 0xFF;
208     pktout.data[2] = (len >> 8) & 0xFF;
209     pktout.data[3] = len & 0xFF;
210
211     if (cipher)
212         cipher->encrypt(pktout.data+4, biglen);
213
214     s_write(pktout.data, biglen+4);
215 }
216
217 static int do_ssh_init(void) {
218     unsigned char c;
219     char version[10];
220     char vstring[40];
221     int i;
222
223 #ifdef FWHACK
224     i = 0;
225     while (s_read(&c, 1) == 1) {
226         if (c == 'S' && i < 2) i++;
227         else if (c == 'S' && i == 2) i = 2;
228         else if (c == 'H' && i == 2) break;
229         else i = 0;
230     }
231 #else
232     if (s_read(&c,1) != 1 || c != 'S') return 0;
233     if (s_read(&c,1) != 1 || c != 'S') return 0;
234     if (s_read(&c,1) != 1 || c != 'H') return 0;
235 #endif
236     if (s_read(&c,1) != 1 || c != '-') return 0;
237     i = 0;
238     while (1) {
239         if (s_read(&c,1) != 1)
240             return 0;
241         if (i >= 0) {
242             if (c == '-') {
243                 version[i] = '\0';
244                 i = -1;
245             } else if (i < sizeof(version)-1)
246                 version[i++] = c;
247         }
248         else if (c == '\n')
249             break;
250     }
251
252     sprintf(vstring, "SSH-%s-7.7.7\n",
253             (strcmp(version, "1.5") <= 0 ? version : "1.5"));
254     s_write((unsigned char *)vstring, strlen(vstring));
255     return 1;
256 }
257
258 static void ssh_protocol(unsigned char *in, int inlen, int ispkt) {
259     int i, j, len;
260     unsigned char session_id[16];
261     unsigned char *rsabuf, *keystr1, *keystr2;
262     unsigned char cookie[8];
263     struct RSAKey servkey, hostkey;
264     struct MD5Context md5c;
265
266     extern struct ssh_cipher ssh_3des;
267
268     crBegin;
269
270     random_init();
271
272     while (!ispkt)
273         crReturnV;
274
275     if (pktin.type != 2)
276         fatalbox("Public key packet not received");
277
278     memcpy(cookie, pktin.body, 8);
279
280     MD5Init(&md5c);
281
282     i = makekey(pktin.body+8, &servkey, &keystr1);
283
284     j = makekey(pktin.body+8+i, &hostkey, &keystr2);
285
286     MD5Update(&md5c, keystr2, hostkey.bytes);
287     MD5Update(&md5c, keystr1, servkey.bytes);
288     MD5Update(&md5c, pktin.body, 8);
289
290     MD5Final(session_id, &md5c);
291
292     for (i=0; i<32; i++)
293         session_key[i] = random_byte();
294
295     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
296
297     rsabuf = malloc(len);
298     if (!rsabuf)
299         fatalbox("Out of memory");
300
301     verify_ssh_host_key(savedhost, &hostkey);
302
303     for (i=0; i<32; i++) {
304         rsabuf[i] = session_key[i];
305         if (i < 16)
306             rsabuf[i] ^= session_id[i];
307     }
308
309     if (hostkey.bytes > servkey.bytes) {
310         rsaencrypt(rsabuf, 32, &servkey);
311         rsaencrypt(rsabuf, servkey.bytes, &hostkey);
312     } else {
313         rsaencrypt(rsabuf, 32, &hostkey);
314         rsaencrypt(rsabuf, hostkey.bytes, &servkey);
315     }
316
317     s_wrpkt_start(3, len+15);
318     pktout.body[0] = 3;                /* SSH_CIPHER_3DES */
319     memcpy(pktout.body+1, cookie, 8);
320     pktout.body[9] = (len*8) >> 8;
321     pktout.body[10] = (len*8) & 0xFF;
322     memcpy(pktout.body+11, rsabuf, len);
323     pktout.body[len+11] = pktout.body[len+12] = 0;   /* protocol flags */
324     pktout.body[len+13] = pktout.body[len+14] = 0;
325     s_wrpkt();
326
327     free(rsabuf);
328
329     cipher = &ssh_3des;
330     cipher->sesskey(session_key);
331
332     do { crReturnV; } while (!ispkt);
333
334     if (pktin.type != 14)
335         fatalbox("Encryption not successfully enabled");
336
337     fflush(stdout);
338     {
339         static char username[100];
340         static int pos = 0;
341         static char c;
342         if (!*cfg.username) {
343             c_write("login as: ", 10);
344             while (pos >= 0) {
345                 do { crReturnV; } while (ispkt);
346                 while (inlen--) switch (c = *in++) {
347                   case 10: case 13:
348                     username[pos] = 0;
349                     pos = -1;
350                     break;
351                   case 8: case 127:
352                     if (pos > 0) {
353                         c_write("\b \b", 3);
354                         pos--;
355                     }
356                     break;
357                   case 21: case 27:
358                     while (pos > 0) {
359                         c_write("\b \b", 3);
360                         pos--;
361                     }
362                     break;
363                   case 3: case 4:
364                     random_save_seed();
365                     exit(0);
366                     break;
367                   default:
368                     if (c >= ' ' && c <= '~' && pos < 40) {
369                         username[pos++] = c;
370                         c_write(&c, 1);
371                     }
372                     break;
373                 }
374             }
375             c_write("\r\n", 2);
376             username[strcspn(username, "\n\r")] = '\0';
377         } else {
378             char stuff[200];
379             strncpy(username, cfg.username, 99);
380             username[99] = '\0';
381             sprintf(stuff, "Sent username \"%s\".\r\n", username);
382             c_write(stuff, strlen(stuff));
383         }
384         s_wrpkt_start(4, 4+strlen(username));
385         pktout.body[0] = pktout.body[1] = pktout.body[2] = 0;
386         pktout.body[3] = strlen(username);
387         memcpy(pktout.body+4, username, strlen(username));
388         s_wrpkt();
389     }
390
391     do { crReturnV; } while (!ispkt);
392
393     while (pktin.type == 15) {
394         static char password[100];
395         static int pos;
396         static char c;
397         c_write("password: ", 10);
398         pos = 0;
399         while (pos >= 0) {
400             do { crReturnV; } while (ispkt);
401             while (inlen--) switch (c = *in++) {
402               case 10: case 13:
403                 password[pos] = 0;
404                 pos = -1;
405                 break;
406               case 8: case 127:
407                 if (pos > 0)
408                     pos--;
409                 break;
410               case 21: case 27:
411                 pos = 0;
412                 break;
413               case 3: case 4:
414                 random_save_seed();
415                 exit(0);
416                 break;
417               default:
418                 if (c >= ' ' && c <= '~' && pos < 40)
419                     password[pos++] = c;
420                 break;
421             }
422         }
423         c_write("\r\n", 2);
424         s_wrpkt_start(9, 4+strlen(password));
425         pktout.body[0] = pktout.body[1] = pktout.body[2] = 0;
426         pktout.body[3] = strlen(password);
427         memcpy(pktout.body+4, password, strlen(password));
428         s_wrpkt();
429         memset(password, 0, strlen(password));
430         do { crReturnV; } while (!ispkt);
431         if (pktin.type == 15) {
432             c_write("Access denied\r\n", 15);
433         } else if (pktin.type != 14) {
434             fatalbox("Strange packet received, type %d", pktin.type);
435         }
436     }
437
438     if (!cfg.nopty) {
439         i = strlen(cfg.termtype);
440         s_wrpkt_start(10, i+5*4+1);
441         pktout.body[0] = (i >> 24) & 0xFF;
442         pktout.body[1] = (i >> 16) & 0xFF;
443         pktout.body[2] = (i >> 8) & 0xFF;
444         pktout.body[3] = i & 0xFF;
445         memcpy(pktout.body+4, cfg.termtype, i);
446         i += 4;
447         pktout.body[i++] = (rows >> 24) & 0xFF;
448         pktout.body[i++] = (rows >> 16) & 0xFF;
449         pktout.body[i++] = (rows >> 8) & 0xFF;
450         pktout.body[i++] = rows & 0xFF;
451         pktout.body[i++] = (cols >> 24) & 0xFF;
452         pktout.body[i++] = (cols >> 16) & 0xFF;
453         pktout.body[i++] = (cols >> 8) & 0xFF;
454         pktout.body[i++] = cols & 0xFF;
455         memset(pktout.body+i, 0, 9);       /* 0 pixwidth, 0 pixheight, 0.b endofopt */
456         s_wrpkt();
457         ssh_state = SSH_STATE_INTERMED;
458         do { crReturnV; } while (!ispkt);
459         if (pktin.type != 14 && pktin.type != 15) {
460             fatalbox("Protocol confusion");
461         } else if (pktin.type == 15) {
462             c_write("Server refused to allocate pty\r\n", 32);
463         }
464     }
465
466     s_wrpkt_start(12, 0);
467     s_wrpkt();
468
469     ssh_state = SSH_STATE_SESSION;
470     if (size_needed)
471         ssh_size();
472
473     while (1) {
474         crReturnV;
475         if (ispkt) {
476             if (pktin.type == 17 || pktin.type == 18) {
477                 long len = 0;
478                 for (i = 0; i < 4; i++)
479                     len = (len << 8) + pktin.body[i];
480                 c_write((char *)pktin.body+4, len);
481             } else if (pktin.type == 1) {
482                 /* SSH_MSG_DISCONNECT: do nothing */
483             } else if (pktin.type == 14) {
484                 /* SSH_MSG_SUCCESS: may be from EXEC_SHELL on some servers */
485             } else if (pktin.type == 15) {
486                 /* SSH_MSG_FAILURE: may be from EXEC_SHELL on some servers
487                  * if no pty is available or in other odd cases. Ignore */
488             } else if (pktin.type == 20) {
489                 /* EXITSTATUS */
490                 s_wrpkt_start(33, 0);
491                 s_wrpkt();
492             } else {
493                 fatalbox("Strange packet received: type %d", pktin.type);
494             }
495         } else {
496             s_wrpkt_start(16, 4+inlen);
497             pktout.body[0] = (inlen >> 24) & 0xFF;
498             pktout.body[1] = (inlen >> 16) & 0xFF;
499             pktout.body[2] = (inlen >> 8) & 0xFF;
500             pktout.body[3] = inlen & 0xFF;
501             memcpy(pktout.body+4, in, inlen);
502             s_wrpkt();
503         }
504     }
505
506     crFinishV;
507 }
508
509 /*
510  * Called to set up the connection. Will arrange for WM_NETEVENT
511  * messages to be passed to the specified window, whose window
512  * procedure should then call telnet_msg().
513  *
514  * Returns an error message, or NULL on success.
515  *
516  * Also places the canonical host name into `realhost'.
517  */
518 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
519     SOCKADDR_IN addr;
520     struct hostent *h;
521     unsigned long a;
522 #ifdef FWHACK
523     char *FWhost;
524     int FWport;
525 #endif
526
527     savedhost = malloc(1+strlen(host));
528     if (!savedhost)
529         fatalbox("Out of memory");
530     strcpy(savedhost, host);
531
532 #ifdef FWHACK
533     FWhost = host;
534     FWport = port;
535     host = FWSTR;
536     port = 23;
537 #endif
538
539     /*
540      * Try to find host.
541      */
542     if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
543         if ( (h = gethostbyname(host)) == NULL)
544             switch (WSAGetLastError()) {
545               case WSAENETDOWN: return "Network is down";
546               case WSAHOST_NOT_FOUND: case WSANO_DATA:
547                 return "Host does not exist";
548               case WSATRY_AGAIN: return "Host not found";
549               default: return "gethostbyname: unknown error";
550             }
551         memcpy (&a, h->h_addr, sizeof(a));
552         *realhost = h->h_name;
553     } else
554         *realhost = host;
555 #ifdef FWHACK
556     *realhost = FWhost;
557 #endif
558     a = ntohl(a);
559
560     if (port < 0)
561         port = 22;                     /* default ssh port */
562
563     /*
564      * Open socket.
565      */
566     s = socket(AF_INET, SOCK_STREAM, 0);
567     if (s == INVALID_SOCKET)
568         switch (WSAGetLastError()) {
569           case WSAENETDOWN: return "Network is down";
570           case WSAEAFNOSUPPORT: return "TCP/IP support not present";
571           default: return "socket(): unknown error";
572         }
573
574     /*
575      * Bind to local address.
576      */
577     addr.sin_family = AF_INET;
578     addr.sin_addr.s_addr = htonl(INADDR_ANY);
579     addr.sin_port = htons(0);
580     if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
581         switch (WSAGetLastError()) {
582           case WSAENETDOWN: return "Network is down";
583           default: return "bind(): unknown error";
584         }
585
586     /*
587      * Connect to remote address.
588      */
589     addr.sin_addr.s_addr = htonl(a);
590     addr.sin_port = htons((short)port);
591     if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
592         switch (WSAGetLastError()) {
593           case WSAENETDOWN: return "Network is down";
594           case WSAECONNREFUSED: return "Connection refused";
595           case WSAENETUNREACH: return "Network is unreachable";
596           case WSAEHOSTUNREACH: return "No route to host";
597           default: return "connect(): unknown error";
598         }
599
600 #ifdef FWHACK
601     send(s, "connect ", 8, 0);
602     send(s, FWhost, strlen(FWhost), 0);
603     {
604         char buf[20];
605         sprintf(buf, " %d\n", FWport);
606         send (s, buf, strlen(buf), 0);
607     }
608 #endif
609
610     if (!do_ssh_init())
611         return "Protocol initialisation error";
612
613     if (WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
614         switch (WSAGetLastError()) {
615           case WSAENETDOWN: return "Network is down";
616           default: return "WSAAsyncSelect(): unknown error";
617         }
618
619     return NULL;
620 }
621
622 /*
623  * Process a WM_NETEVENT message. Will return 0 if the connection
624  * has closed, or <0 for a socket error.
625  */
626 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
627     int ret;
628     char buf[256];
629
630     if (s == INVALID_SOCKET)           /* how the hell did we get here?! */
631         return -5000;
632
633     if (WSAGETSELECTERROR(lParam) != 0)
634         return -WSAGETSELECTERROR(lParam);
635
636     switch (WSAGETSELECTEVENT(lParam)) {
637       case FD_READ:
638         ret = recv(s, buf, sizeof(buf), 0);
639         if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
640             return 1;
641         if (ret < 0)                   /* any _other_ error */
642             return -10000-WSAGetLastError();
643         if (ret == 0) {
644             s = INVALID_SOCKET;
645             return 0;                  /* can't happen, in theory */
646         }
647         ssh_gotdata (buf, ret);
648         return 1;
649       case FD_CLOSE:
650         s = INVALID_SOCKET;
651         return 0;
652     }
653     return 1;                          /* shouldn't happen, but WTF */
654 }
655
656 /*
657  * Called to send data down the Telnet connection.
658  */
659 static void ssh_send (char *buf, int len) {
660     if (s == INVALID_SOCKET)
661         return;
662
663     ssh_protocol(buf, len, 0);
664 }
665
666 /*
667  * Called to set the size of the window from Telnet's POV.
668  */
669 static void ssh_size(void) {
670     switch (ssh_state) {
671       case SSH_STATE_BEFORE_SIZE:
672         break;                         /* do nothing */
673       case SSH_STATE_INTERMED:
674         size_needed = TRUE;            /* buffer for later */
675         break;
676       case SSH_STATE_SESSION:
677         if (!cfg.nopty) {
678             s_wrpkt_start(11, 16);
679             pktout.body[0] = (rows >> 24) & 0xFF;
680             pktout.body[1] = (rows >> 16) & 0xFF;
681             pktout.body[2] = (rows >> 8) & 0xFF;
682             pktout.body[3] = rows & 0xFF;
683             pktout.body[4] = (cols >> 24) & 0xFF;
684             pktout.body[5] = (cols >> 16) & 0xFF;
685             pktout.body[6] = (cols >> 8) & 0xFF;
686             pktout.body[7] = cols & 0xFF;
687             memset(pktout.body+8, 0, 8);
688             s_wrpkt();
689         }
690     }
691 }
692
693 /*
694  * (Send Telnet special codes)
695  */
696 static void ssh_special (Telnet_Special code) {
697     /* do nothing */
698 }
699
700 Backend ssh_backend = {
701     ssh_init,
702     ssh_msg,
703     ssh_send,
704     ssh_size,
705     ssh_special
706 };