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