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