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