]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
Add SSH_STATE_CLOSED to prevent accidentally sending resizes down a
[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         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+4) :
179                        realloc(pktout.data, biglen+4));
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     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(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(pktin.body+4, len);
481             } else if (pktin.type == 1) {
482                 /* SSH_MSG_DISCONNECT */
483                 ssh_state = SSH_STATE_CLOSED;
484             } else if (pktin.type == 14) {
485                 /* SSH_MSG_SUCCESS: may be from EXEC_SHELL on some servers */
486             } else if (pktin.type == 15) {
487                 /* SSH_MSG_FAILURE: may be from EXEC_SHELL on some servers
488                  * if no pty is available or in other odd cases. Ignore */
489             } else if (pktin.type == 20) {
490                 /* EXITSTATUS */
491                 s_wrpkt_start(33, 0);
492                 s_wrpkt();
493             } else {
494                 fatalbox("Strange packet received: type %d", pktin.type);
495             }
496         } else {
497             s_wrpkt_start(16, 4+inlen);
498             pktout.body[0] = (inlen >> 24) & 0xFF;
499             pktout.body[1] = (inlen >> 16) & 0xFF;
500             pktout.body[2] = (inlen >> 8) & 0xFF;
501             pktout.body[3] = inlen & 0xFF;
502             memcpy(pktout.body+4, in, inlen);
503             s_wrpkt();
504         }
505     }
506
507     crFinishV;
508 }
509
510 /*
511  * Called to set up the connection. Will arrange for WM_NETEVENT
512  * messages to be passed to the specified window, whose window
513  * procedure should then call telnet_msg().
514  *
515  * Returns an error message, or NULL on success.
516  *
517  * Also places the canonical host name into `realhost'.
518  */
519 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
520     SOCKADDR_IN addr;
521     struct hostent *h;
522     unsigned long a;
523 #ifdef FWHACK
524     char *FWhost;
525     int FWport;
526 #endif
527
528     savedhost = malloc(1+strlen(host));
529     if (!savedhost)
530         fatalbox("Out of memory");
531     strcpy(savedhost, host);
532
533 #ifdef FWHACK
534     FWhost = host;
535     FWport = port;
536     host = FWSTR;
537     port = 23;
538 #endif
539
540     /*
541      * Try to find host.
542      */
543     if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
544         if ( (h = gethostbyname(host)) == NULL)
545             switch (WSAGetLastError()) {
546               case WSAENETDOWN: return "Network is down";
547               case WSAHOST_NOT_FOUND: case WSANO_DATA:
548                 return "Host does not exist";
549               case WSATRY_AGAIN: return "Host not found";
550               default: return "gethostbyname: unknown error";
551             }
552         memcpy (&a, h->h_addr, sizeof(a));
553         *realhost = h->h_name;
554     } else
555         *realhost = host;
556 #ifdef FWHACK
557     *realhost = FWhost;
558 #endif
559     a = ntohl(a);
560
561     if (port < 0)
562         port = 22;                     /* default ssh port */
563
564     /*
565      * Open socket.
566      */
567     s = socket(AF_INET, SOCK_STREAM, 0);
568     if (s == INVALID_SOCKET)
569         switch (WSAGetLastError()) {
570           case WSAENETDOWN: return "Network is down";
571           case WSAEAFNOSUPPORT: return "TCP/IP support not present";
572           default: return "socket(): unknown error";
573         }
574
575     /*
576      * Bind to local address.
577      */
578     addr.sin_family = AF_INET;
579     addr.sin_addr.s_addr = htonl(INADDR_ANY);
580     addr.sin_port = htons(0);
581     if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
582         switch (WSAGetLastError()) {
583           case WSAENETDOWN: return "Network is down";
584           default: return "bind(): unknown error";
585         }
586
587     /*
588      * Connect to remote address.
589      */
590     addr.sin_addr.s_addr = htonl(a);
591     addr.sin_port = htons((short)port);
592     if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
593         switch (WSAGetLastError()) {
594           case WSAENETDOWN: return "Network is down";
595           case WSAECONNREFUSED: return "Connection refused";
596           case WSAENETUNREACH: return "Network is unreachable";
597           case WSAEHOSTUNREACH: return "No route to host";
598           default: return "connect(): unknown error";
599         }
600
601 #ifdef FWHACK
602     send(s, "connect ", 8, 0);
603     send(s, FWhost, strlen(FWhost), 0);
604     {
605         char buf[20];
606         sprintf(buf, " %d\n", FWport);
607         send (s, buf, strlen(buf), 0);
608     }
609 #endif
610
611     if (!do_ssh_init())
612         return "Protocol initialisation error";
613
614     if (WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
615         switch (WSAGetLastError()) {
616           case WSAENETDOWN: return "Network is down";
617           default: return "WSAAsyncSelect(): unknown error";
618         }
619
620     return NULL;
621 }
622
623 /*
624  * Process a WM_NETEVENT message. Will return 0 if the connection
625  * has closed, or <0 for a socket error.
626  */
627 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
628     int ret;
629     char buf[256];
630
631     if (s == INVALID_SOCKET)           /* how the hell did we get here?! */
632         return -5000;
633
634     if (WSAGETSELECTERROR(lParam) != 0)
635         return -WSAGETSELECTERROR(lParam);
636
637     switch (WSAGETSELECTEVENT(lParam)) {
638       case FD_READ:
639         ret = recv(s, buf, sizeof(buf), 0);
640         if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
641             return 1;
642         if (ret < 0)                   /* any _other_ error */
643             return -10000-WSAGetLastError();
644         if (ret == 0) {
645             s = INVALID_SOCKET;
646             return 0;                  /* can't happen, in theory */
647         }
648         ssh_gotdata (buf, ret);
649         return 1;
650       case FD_CLOSE:
651         s = INVALID_SOCKET;
652         ssh_state = SSH_STATE_CLOSED;
653         return 0;
654     }
655     return 1;                          /* shouldn't happen, but WTF */
656 }
657
658 /*
659  * Called to send data down the Telnet connection.
660  */
661 static void ssh_send (char *buf, int len) {
662     if (s == INVALID_SOCKET)
663         return;
664
665     ssh_protocol(buf, len, 0);
666 }
667
668 /*
669  * Called to set the size of the window from Telnet's POV.
670  */
671 static void ssh_size(void) {
672     switch (ssh_state) {
673       case SSH_STATE_BEFORE_SIZE:
674       case SSH_STATE_CLOSED:
675         break;                         /* do nothing */
676       case SSH_STATE_INTERMED:
677         size_needed = TRUE;            /* buffer for later */
678         break;
679       case SSH_STATE_SESSION:
680         if (!cfg.nopty) {
681             s_wrpkt_start(11, 16);
682             pktout.body[0] = (rows >> 24) & 0xFF;
683             pktout.body[1] = (rows >> 16) & 0xFF;
684             pktout.body[2] = (rows >> 8) & 0xFF;
685             pktout.body[3] = rows & 0xFF;
686             pktout.body[4] = (cols >> 24) & 0xFF;
687             pktout.body[5] = (cols >> 16) & 0xFF;
688             pktout.body[6] = (cols >> 8) & 0xFF;
689             pktout.body[7] = cols & 0xFF;
690             memset(pktout.body+8, 0, 8);
691             s_wrpkt();
692         }
693     }
694 }
695
696 /*
697  * (Send Telnet special codes)
698  */
699 static void ssh_special (Telnet_Special code) {
700     /* do nothing */
701 }
702
703 Backend ssh_backend = {
704     ssh_init,
705     ssh_msg,
706     ssh_send,
707     ssh_size,
708     ssh_special
709 };