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