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