Oops - add a terminator to the array
[u/mdw/putty] / ssh.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4 #include <assert.h>
5 #include <winsock.h>
6
7 #include "putty.h"
8 #include "ssh.h"
9 #include "scp.h"
10
11 #ifndef FALSE
12 #define FALSE 0
13 #endif
14 #ifndef TRUE
15 #define TRUE 1
16 #endif
17
18 #define logevent(s) { logevent(s); \
19 if (IS_SCP && (scp_flags & SCP_VERBOSE) != 0) \
20 fprintf(stderr, "%s\n", s); }
21
22 #define SSH_MSG_DISCONNECT 1
23 #define SSH_SMSG_PUBLIC_KEY 2
24 #define SSH_CMSG_SESSION_KEY 3
25 #define SSH_CMSG_USER 4
26 #define SSH_CMSG_AUTH_PASSWORD 9
27 #define SSH_CMSG_REQUEST_PTY 10
28 #define SSH_CMSG_WINDOW_SIZE 11
29 #define SSH_CMSG_EXEC_SHELL 12
30 #define SSH_CMSG_EXEC_CMD 13
31 #define SSH_SMSG_SUCCESS 14
32 #define SSH_SMSG_FAILURE 15
33 #define SSH_CMSG_STDIN_DATA 16
34 #define SSH_SMSG_STDOUT_DATA 17
35 #define SSH_SMSG_STDERR_DATA 18
36 #define SSH_CMSG_EOF 19
37 #define SSH_SMSG_EXIT_STATUS 20
38 #define SSH_CMSG_EXIT_CONFIRMATION 33
39 #define SSH_MSG_IGNORE 32
40 #define SSH_MSG_DEBUG 36
41 #define SSH_CMSG_AUTH_TIS 39
42 #define SSH_SMSG_AUTH_TIS_CHALLENGE 40
43 #define SSH_CMSG_AUTH_TIS_RESPONSE 41
44
45 #define SSH_AUTH_TIS 5
46
47 #define GET_32BIT(cp) \
48 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
49 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
50 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
51 ((unsigned long)(unsigned char)(cp)[3]))
52
53 #define PUT_32BIT(cp, value) { \
54 (cp)[0] = (unsigned char)((value) >> 24); \
55 (cp)[1] = (unsigned char)((value) >> 16); \
56 (cp)[2] = (unsigned char)((value) >> 8); \
57 (cp)[3] = (unsigned char)(value); }
58
59 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR };
60
61 /* Coroutine mechanics for the sillier bits of the code */
62 #define crBegin1 static int crLine = 0;
63 #define crBegin2 switch(crLine) { case 0:;
64 #define crBegin crBegin1; crBegin2;
65 #define crFinish(z) } crLine = 0; return (z)
66 #define crFinishV } crLine = 0; return
67 #define crReturn(z) \
68 do {\
69 crLine=__LINE__; return (z); case __LINE__:;\
70 } while (0)
71 #define crReturnV \
72 do {\
73 crLine=__LINE__; return; case __LINE__:;\
74 } while (0)
75 #define crStop(z) do{ crLine = 0; return (z); }while(0)
76 #define crStopV do{ crLine = 0; return; }while(0)
77 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
78
79 static SOCKET s = INVALID_SOCKET;
80
81 static unsigned char session_key[32];
82 static struct ssh_cipher *cipher = NULL;
83 int scp_flags = 0;
84 void (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
85
86 static char *savedhost;
87
88 static enum {
89 SSH_STATE_BEFORE_SIZE,
90 SSH_STATE_INTERMED,
91 SSH_STATE_SESSION,
92 SSH_STATE_CLOSED
93 } ssh_state = SSH_STATE_BEFORE_SIZE;
94
95 static int size_needed = FALSE;
96
97 static void s_write (char *buf, int len) {
98 while (len > 0) {
99 int i = send (s, buf, len, 0);
100 if (IS_SCP) {
101 noise_ultralight(i);
102 if (i <= 0)
103 fatalbox("Lost connection while sending");
104 }
105 if (i > 0)
106 len -= i, buf += i;
107 }
108 }
109
110 static int s_read (char *buf, int len) {
111 int ret = 0;
112 while (len > 0) {
113 int i = recv (s, buf, len, 0);
114 if (IS_SCP)
115 noise_ultralight(i);
116 if (i > 0)
117 len -= i, buf += i, ret += i;
118 else
119 return i;
120 }
121 return ret;
122 }
123
124 static void c_write (char *buf, int len) {
125 if (IS_SCP) {
126 if (len > 0 && buf[len-1] == '\n') len--;
127 if (len > 0 && buf[len-1] == '\r') len--;
128 if (len > 0) { fwrite(buf, len, 1, stderr); fputc('\n', stderr); }
129 return;
130 }
131 while (len--) {
132 int new_head = (inbuf_head + 1) & INBUF_MASK;
133 if (new_head != inbuf_reap) {
134 inbuf[inbuf_head] = *buf++;
135 inbuf_head = new_head;
136 } else {
137 term_out();
138 if( inbuf_head == inbuf_reap ) len++; else break;
139 }
140 }
141 }
142
143 struct Packet {
144 long length;
145 int type;
146 unsigned char *data;
147 unsigned char *body;
148 long maxlen;
149 };
150
151 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
152 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
153
154 static void ssh_protocol(unsigned char *in, int inlen, int ispkt);
155 static void ssh_size(void);
156
157
158 /*
159 * Collect incoming data in the incoming packet buffer.
160 * Decihper and verify the packet when it is completely read.
161 * Drop SSH_MSG_DEBUG and SSH_MSG_IGNORE packets.
162 * Update the *data and *datalen variables.
163 * Return the additional nr of bytes needed, or 0 when
164 * a complete packet is available.
165 */
166 static int s_rdpkt(unsigned char **data, int *datalen)
167 {
168 static long len, pad, biglen, to_read;
169 static unsigned long realcrc, gotcrc;
170 static unsigned char *p;
171 static int i;
172
173 crBegin;
174
175 next_packet:
176
177 pktin.type = 0;
178 pktin.length = 0;
179
180 for (i = len = 0; i < 4; i++) {
181 while ((*datalen) == 0)
182 crReturn(4-i);
183 len = (len << 8) + **data;
184 (*data)++, (*datalen)--;
185 }
186
187 #ifdef FWHACK
188 if (len == 0x52656d6f) { /* "Remo"te server has closed ... */
189 len = 0x300; /* big enough to carry to end */
190 }
191 #endif
192
193 pad = 8 - (len % 8);
194 biglen = len + pad;
195 pktin.length = len - 5;
196
197 if (pktin.maxlen < biglen) {
198 pktin.maxlen = biglen;
199 #ifdef MSCRYPTOAPI
200 /* Allocate enough buffer space for extra block
201 * for MS CryptEncrypt() */
202 pktin.data = (pktin.data == NULL ? malloc(biglen+8) :
203 realloc(pktin.data, biglen+8));
204 #else
205 pktin.data = (pktin.data == NULL ? malloc(biglen) :
206 realloc(pktin.data, biglen));
207 #endif
208 if (!pktin.data)
209 fatalbox("Out of memory");
210 }
211
212 to_read = biglen;
213 p = pktin.data;
214 while (to_read > 0) {
215 static int chunk;
216 chunk = to_read;
217 while ((*datalen) == 0)
218 crReturn(to_read);
219 if (chunk > (*datalen))
220 chunk = (*datalen);
221 memcpy(p, *data, chunk);
222 *data += chunk;
223 *datalen -= chunk;
224 p += chunk;
225 to_read -= chunk;
226 }
227
228 if (cipher)
229 cipher->decrypt(pktin.data, biglen);
230
231 pktin.type = pktin.data[pad];
232 pktin.body = pktin.data + pad + 1;
233
234 realcrc = crc32(pktin.data, biglen-4);
235 gotcrc = GET_32BIT(pktin.data+biglen-4);
236 if (gotcrc != realcrc) {
237 fatalbox("Incorrect CRC received on packet");
238 }
239
240 if (pktin.type == SSH_SMSG_STDOUT_DATA ||
241 pktin.type == SSH_SMSG_STDERR_DATA ||
242 pktin.type == SSH_MSG_DEBUG ||
243 pktin.type == SSH_SMSG_AUTH_TIS_CHALLENGE) {
244 long strlen = GET_32BIT(pktin.body);
245 if (strlen + 4 != pktin.length)
246 fatalbox("Received data packet with bogus string length");
247 }
248
249 if (pktin.type == SSH_MSG_DEBUG) {
250 /* log debug message */
251 char buf[80];
252 int strlen = GET_32BIT(pktin.body);
253 strcpy(buf, "Remote: ");
254 if (strlen > 70) strlen = 70;
255 memcpy(buf+8, pktin.body+4, strlen);
256 buf[8+strlen] = '\0';
257 logevent(buf);
258 goto next_packet;
259 } else if (pktin.type == SSH_MSG_IGNORE) {
260 /* do nothing */
261 goto next_packet;
262 }
263
264 crFinish(0);
265 }
266
267 static void ssh_gotdata(unsigned char *data, int datalen)
268 {
269 while (datalen > 0) {
270 if ( s_rdpkt(&data, &datalen) == 0 )
271 ssh_protocol(NULL, 0, 1);
272 }
273 }
274
275
276 static void s_wrpkt_start(int type, int len) {
277 int pad, biglen;
278
279 len += 5; /* type and CRC */
280 pad = 8 - (len%8);
281 biglen = len + pad;
282
283 pktout.length = len-5;
284 if (pktout.maxlen < biglen) {
285 pktout.maxlen = biglen;
286 #ifdef MSCRYPTOAPI
287 /* Allocate enough buffer space for extra block
288 * for MS CryptEncrypt() */
289 pktout.data = (pktout.data == NULL ? malloc(biglen+12) :
290 realloc(pktout.data, biglen+12));
291 #else
292 pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
293 realloc(pktout.data, biglen+4));
294 #endif
295 if (!pktout.data)
296 fatalbox("Out of memory");
297 }
298
299 pktout.type = type;
300 pktout.body = pktout.data+4+pad+1;
301 }
302
303 static void s_wrpkt(void) {
304 int pad, len, biglen, i;
305 unsigned long crc;
306
307 len = pktout.length + 5; /* type and CRC */
308 pad = 8 - (len%8);
309 biglen = len + pad;
310
311 pktout.body[-1] = pktout.type;
312 for (i=0; i<pad; i++)
313 pktout.data[i+4] = random_byte();
314 crc = crc32(pktout.data+4, biglen-4);
315 PUT_32BIT(pktout.data+biglen, crc);
316 PUT_32BIT(pktout.data, len);
317
318 if (cipher)
319 cipher->encrypt(pktout.data+4, biglen);
320
321 s_write(pktout.data, biglen+4);
322 }
323
324 /*
325 * Construct a packet with the specified contents and
326 * send it to the server.
327 */
328 static void send_packet(int pkttype, ...)
329 {
330 va_list args;
331 unsigned char *p, *argp, argchar;
332 unsigned long argint;
333 int pktlen, argtype, arglen;
334
335 pktlen = 0;
336 va_start(args, pkttype);
337 while ((argtype = va_arg(args, int)) != PKT_END) {
338 switch (argtype) {
339 case PKT_INT:
340 (void) va_arg(args, int);
341 pktlen += 4;
342 break;
343 case PKT_CHAR:
344 (void) va_arg(args, char);
345 pktlen++;
346 break;
347 case PKT_DATA:
348 (void) va_arg(args, unsigned char *);
349 arglen = va_arg(args, int);
350 pktlen += arglen;
351 break;
352 case PKT_STR:
353 argp = va_arg(args, unsigned char *);
354 arglen = strlen(argp);
355 pktlen += 4 + arglen;
356 break;
357 default:
358 assert(0);
359 }
360 }
361 va_end(args);
362
363 s_wrpkt_start(pkttype, pktlen);
364 p = pktout.body;
365
366 va_start(args, pkttype);
367 while ((argtype = va_arg(args, int)) != PKT_END) {
368 switch (argtype) {
369 case PKT_INT:
370 argint = va_arg(args, int);
371 PUT_32BIT(p, argint);
372 p += 4;
373 break;
374 case PKT_CHAR:
375 argchar = va_arg(args, unsigned char);
376 *p = argchar;
377 p++;
378 break;
379 case PKT_DATA:
380 argp = va_arg(args, unsigned char *);
381 arglen = va_arg(args, int);
382 memcpy(p, argp, arglen);
383 p += arglen;
384 break;
385 case PKT_STR:
386 argp = va_arg(args, unsigned char *);
387 arglen = strlen(argp);
388 PUT_32BIT(p, arglen);
389 memcpy(p + 4, argp, arglen);
390 p += 4 + arglen;
391 break;
392 }
393 }
394 va_end(args);
395
396 s_wrpkt();
397 }
398
399
400 /*
401 * Connect to specified host and port.
402 * Returns an error message, or NULL on success.
403 * Also places the canonical host name into `realhost'.
404 */
405 static char *connect_to_host(char *host, int port, char **realhost)
406 {
407 SOCKADDR_IN addr;
408 struct hostent *h;
409 unsigned long a;
410 #ifdef FWHACK
411 char *FWhost;
412 int FWport;
413 #endif
414
415 savedhost = malloc(1+strlen(host));
416 if (!savedhost)
417 fatalbox("Out of memory");
418 strcpy(savedhost, host);
419
420 if (port < 0)
421 port = 22; /* default ssh port */
422
423 #ifdef FWHACK
424 FWhost = host;
425 FWport = port;
426 host = FWSTR;
427 port = 23;
428 #endif
429
430 /*
431 * Try to find host.
432 */
433 if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
434 if ( (h = gethostbyname(host)) == NULL)
435 switch (WSAGetLastError()) {
436 case WSAENETDOWN: return "Network is down";
437 case WSAHOST_NOT_FOUND: case WSANO_DATA:
438 return "Host does not exist";
439 case WSATRY_AGAIN: return "Host not found";
440 default: return "gethostbyname: unknown error";
441 }
442 memcpy (&a, h->h_addr, sizeof(a));
443 *realhost = h->h_name;
444 } else
445 *realhost = host;
446 #ifdef FWHACK
447 *realhost = FWhost;
448 #endif
449 a = ntohl(a);
450
451 /*
452 * Open socket.
453 */
454 s = socket(AF_INET, SOCK_STREAM, 0);
455 if (s == INVALID_SOCKET)
456 switch (WSAGetLastError()) {
457 case WSAENETDOWN: return "Network is down";
458 case WSAEAFNOSUPPORT: return "TCP/IP support not present";
459 default: return "socket(): unknown error";
460 }
461
462 /*
463 * Bind to local address.
464 */
465 addr.sin_family = AF_INET;
466 addr.sin_addr.s_addr = htonl(INADDR_ANY);
467 addr.sin_port = htons(0);
468 if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
469 switch (WSAGetLastError()) {
470 case WSAENETDOWN: return "Network is down";
471 default: return "bind(): unknown error";
472 }
473
474 /*
475 * Connect to remote address.
476 */
477 addr.sin_addr.s_addr = htonl(a);
478 addr.sin_port = htons((short)port);
479 if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
480 switch (WSAGetLastError()) {
481 case WSAENETDOWN: return "Network is down";
482 case WSAECONNREFUSED: return "Connection refused";
483 case WSAENETUNREACH: return "Network is unreachable";
484 case WSAEHOSTUNREACH: return "No route to host";
485 default: return "connect(): unknown error";
486 }
487
488 #ifdef FWHACK
489 send(s, "connect ", 8, 0);
490 send(s, FWhost, strlen(FWhost), 0);
491 {
492 char buf[20];
493 sprintf(buf, " %d\n", FWport);
494 send (s, buf, strlen(buf), 0);
495 }
496 #endif
497
498 return NULL;
499 }
500
501 static int ssh_versioncmp(char *a, char *b) {
502 char *ae, *be;
503 unsigned long av, bv;
504
505 av = strtoul(a, &ae, 10);
506 bv = strtoul(b, &be, 10);
507 if (av != bv) return (av < bv ? -1 : +1);
508 if (*ae == '.') ae++;
509 if (*be == '.') be++;
510 av = strtoul(ae, &ae, 10);
511 bv = strtoul(be, &be, 10);
512 if (av != bv) return (av < bv ? -1 : +1);
513 return 0;
514 }
515
516 static int do_ssh_init(void) {
517 char c, *vsp;
518 char version[10];
519 char vstring[80];
520 char vlog[sizeof(vstring)+20];
521 int i;
522
523 #ifdef FWHACK
524 i = 0;
525 while (s_read(&c, 1) == 1) {
526 if (c == 'S' && i < 2) i++;
527 else if (c == 'S' && i == 2) i = 2;
528 else if (c == 'H' && i == 2) break;
529 else i = 0;
530 }
531 #else
532 if (s_read(&c,1) != 1 || c != 'S') return 0;
533 if (s_read(&c,1) != 1 || c != 'S') return 0;
534 if (s_read(&c,1) != 1 || c != 'H') return 0;
535 #endif
536 strcpy(vstring, "SSH-");
537 vsp = vstring+4;
538 if (s_read(&c,1) != 1 || c != '-') return 0;
539 i = 0;
540 while (1) {
541 if (s_read(&c,1) != 1)
542 return 0;
543 if (vsp < vstring+sizeof(vstring)-1)
544 *vsp++ = c;
545 if (i >= 0) {
546 if (c == '-') {
547 version[i] = '\0';
548 i = -1;
549 } else if (i < sizeof(version)-1)
550 version[i++] = c;
551 }
552 else if (c == '\n')
553 break;
554 }
555
556 *vsp = 0;
557 sprintf(vlog, "Server version: %s", vstring);
558 vlog[strcspn(vlog, "\r\n")] = '\0';
559 logevent(vlog);
560
561 sprintf(vstring, "SSH-%s-PuTTY\n",
562 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
563 sprintf(vlog, "We claim version: %s", vstring);
564 vlog[strcspn(vlog, "\r\n")] = '\0';
565 logevent(vlog);
566 s_write(vstring, strlen(vstring));
567 return 1;
568 }
569
570 /*
571 * Handle the key exchange and user authentication phases.
572 */
573 static int do_ssh_login(unsigned char *in, int inlen, int ispkt)
574 {
575 int i, j, len;
576 unsigned char session_id[16];
577 unsigned char *rsabuf, *keystr1, *keystr2;
578 unsigned char cookie[8];
579 struct RSAKey servkey, hostkey;
580 struct MD5Context md5c;
581 static unsigned long supported_ciphers_mask, supported_auths_mask;
582 int cipher_type;
583
584 extern struct ssh_cipher ssh_3des;
585 extern struct ssh_cipher ssh_des;
586 extern struct ssh_cipher ssh_blowfish;
587
588 crBegin;
589
590 if (!ispkt) crWaitUntil(ispkt);
591
592 if (pktin.type != SSH_SMSG_PUBLIC_KEY)
593 fatalbox("Public key packet not received");
594
595 logevent("Received public keys");
596
597 memcpy(cookie, pktin.body, 8);
598
599 i = makekey(pktin.body+8, &servkey, &keystr1);
600 j = makekey(pktin.body+8+i, &hostkey, &keystr2);
601
602 /*
603 * Hash the host key and print the hash in the log box. Just as
604 * a last resort in case the registry's host key checking is
605 * compromised, we'll allow the user some ability to verify
606 * host keys by eye.
607 */
608 MD5Init(&md5c);
609 MD5Update(&md5c, keystr2, hostkey.bytes);
610 MD5Final(session_id, &md5c);
611 {
612 char logmsg[80];
613 int i;
614 logevent("Host key MD5 is:");
615 strcpy(logmsg, " ");
616 for (i = 0; i < 16; i++)
617 sprintf(logmsg+strlen(logmsg), "%02x", session_id[i]);
618 logevent(logmsg);
619 }
620
621 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
622 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
623
624 MD5Init(&md5c);
625 MD5Update(&md5c, keystr2, hostkey.bytes);
626 MD5Update(&md5c, keystr1, servkey.bytes);
627 MD5Update(&md5c, pktin.body, 8);
628 MD5Final(session_id, &md5c);
629
630 for (i=0; i<32; i++)
631 session_key[i] = random_byte();
632
633 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
634
635 rsabuf = malloc(len);
636 if (!rsabuf)
637 fatalbox("Out of memory");
638
639 /*
640 * Verify the host key.
641 */
642 {
643 /*
644 * First format the key into a string.
645 */
646 int len = rsastr_len(&hostkey);
647 char *keystr = malloc(len);
648 if (!keystr)
649 fatalbox("Out of memory");
650 rsastr_fmt(keystr, &hostkey);
651 verify_ssh_host_key(savedhost, keystr);
652 free(keystr);
653 }
654
655 for (i=0; i<32; i++) {
656 rsabuf[i] = session_key[i];
657 if (i < 16)
658 rsabuf[i] ^= session_id[i];
659 }
660
661 if (hostkey.bytes > servkey.bytes) {
662 rsaencrypt(rsabuf, 32, &servkey);
663 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
664 } else {
665 rsaencrypt(rsabuf, 32, &hostkey);
666 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
667 }
668
669 logevent("Encrypted session key");
670
671 cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
672 cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES :
673 SSH_CIPHER_3DES;
674 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
675 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
676 cipher_type = SSH_CIPHER_3DES;
677 }
678 switch (cipher_type) {
679 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
680 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
681 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
682 }
683
684 send_packet(SSH_CMSG_SESSION_KEY,
685 PKT_CHAR, cipher_type,
686 PKT_DATA, cookie, 8,
687 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
688 PKT_DATA, rsabuf, len,
689 PKT_INT, 0,
690 PKT_END);
691
692 logevent("Trying to enable encryption...");
693
694 free(rsabuf);
695
696 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
697 cipher_type == SSH_CIPHER_DES ? &ssh_des :
698 &ssh_3des;
699 cipher->sesskey(session_key);
700
701 crWaitUntil(ispkt);
702
703 if (pktin.type != SSH_SMSG_SUCCESS)
704 fatalbox("Encryption not successfully enabled");
705
706 logevent("Successfully started encryption");
707
708 fflush(stdout);
709 {
710 static char username[100];
711 static int pos = 0;
712 static char c;
713 if (!IS_SCP && !*cfg.username) {
714 c_write("login as: ", 10);
715 while (pos >= 0) {
716 crWaitUntil(!ispkt);
717 while (inlen--) switch (c = *in++) {
718 case 10: case 13:
719 username[pos] = 0;
720 pos = -1;
721 break;
722 case 8: case 127:
723 if (pos > 0) {
724 c_write("\b \b", 3);
725 pos--;
726 }
727 break;
728 case 21: case 27:
729 while (pos > 0) {
730 c_write("\b \b", 3);
731 pos--;
732 }
733 break;
734 case 3: case 4:
735 random_save_seed();
736 exit(0);
737 break;
738 default:
739 if (((c >= ' ' && c <= '~') ||
740 ((unsigned char)c >= 160)) && pos < 40) {
741 username[pos++] = c;
742 c_write(&c, 1);
743 }
744 break;
745 }
746 }
747 c_write("\r\n", 2);
748 username[strcspn(username, "\n\r")] = '\0';
749 } else {
750 char stuff[200];
751 strncpy(username, cfg.username, 99);
752 username[99] = '\0';
753 if (!IS_SCP) {
754 sprintf(stuff, "Sent username \"%s\".\r\n", username);
755 c_write(stuff, strlen(stuff));
756 }
757 }
758
759 send_packet(SSH_CMSG_USER, PKT_STR, username, PKT_END);
760 {
761 char userlog[20+sizeof(username)];
762 sprintf(userlog, "Sent username \"%s\"", username);
763 logevent(userlog);
764 }
765 }
766
767 crWaitUntil(ispkt);
768
769 while (pktin.type == SSH_SMSG_FAILURE) {
770 static char password[100];
771 static int pos;
772 static char c;
773 static int pwpkt_type;
774
775 /*
776 * Show password prompt, having first obtained it via a TIS
777 * exchange if we're doing TIS authentication.
778 */
779 pwpkt_type = SSH_CMSG_AUTH_PASSWORD;
780
781 if (IS_SCP) {
782 char prompt[200];
783 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
784 ssh_get_password(prompt, password, sizeof(password));
785 } else {
786
787 if (pktin.type == SSH_SMSG_FAILURE &&
788 cfg.try_tis_auth &&
789 (supported_auths_mask & (1<<SSH_AUTH_TIS))) {
790 pwpkt_type = SSH_CMSG_AUTH_TIS_RESPONSE;
791 logevent("Requested TIS authentication");
792 send_packet(SSH_CMSG_AUTH_TIS, PKT_END);
793 crWaitUntil(ispkt);
794 if (pktin.type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
795 logevent("TIS authentication declined");
796 c_write("TIS authentication refused.\r\n", 29);
797 } else {
798 int challengelen = ((pktin.body[0] << 24) |
799 (pktin.body[1] << 16) |
800 (pktin.body[2] << 8) |
801 (pktin.body[3]));
802 logevent("Received TIS challenge");
803 c_write(pktin.body+4, challengelen);
804 }
805 }
806 if (pwpkt_type == SSH_CMSG_AUTH_PASSWORD)
807 c_write("password: ", 10);
808
809 pos = 0;
810 while (pos >= 0) {
811 crWaitUntil(!ispkt);
812 while (inlen--) switch (c = *in++) {
813 case 10: case 13:
814 password[pos] = 0;
815 pos = -1;
816 break;
817 case 8: case 127:
818 if (pos > 0)
819 pos--;
820 break;
821 case 21: case 27:
822 pos = 0;
823 break;
824 case 3: case 4:
825 random_save_seed();
826 exit(0);
827 break;
828 default:
829 if (((c >= ' ' && c <= '~') ||
830 ((unsigned char)c >= 160)) && pos < 40)
831 password[pos++] = c;
832 break;
833 }
834 }
835 c_write("\r\n", 2);
836
837 }
838
839 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
840 logevent("Sent password");
841 memset(password, 0, strlen(password));
842 crWaitUntil(ispkt);
843 if (pktin.type == SSH_SMSG_FAILURE) {
844 c_write("Access denied\r\n", 15);
845 logevent("Authentication refused");
846 } else if (pktin.type == SSH_MSG_DISCONNECT) {
847 logevent("Received disconnect request");
848 crReturn(0);
849 } else if (pktin.type != SSH_SMSG_SUCCESS) {
850 fatalbox("Strange packet received, type %d", pktin.type);
851 }
852 }
853
854 logevent("Authentication successful");
855
856 crFinish(1);
857 }
858
859 static void ssh_protocol(unsigned char *in, int inlen, int ispkt) {
860 crBegin;
861
862 random_init();
863
864 while (!do_ssh_login(in, inlen, ispkt))
865 crReturnV;
866
867 if (!cfg.nopty) {
868 send_packet(SSH_CMSG_REQUEST_PTY,
869 PKT_STR, cfg.termtype,
870 PKT_INT, rows, PKT_INT, cols,
871 PKT_INT, 0, PKT_INT, 0,
872 PKT_CHAR, 0,
873 PKT_END);
874 ssh_state = SSH_STATE_INTERMED;
875 do { crReturnV; } while (!ispkt);
876 if (pktin.type != SSH_SMSG_SUCCESS && pktin.type != SSH_SMSG_FAILURE) {
877 fatalbox("Protocol confusion");
878 } else if (pktin.type == SSH_SMSG_FAILURE) {
879 c_write("Server refused to allocate pty\r\n", 32);
880 }
881 logevent("Allocated pty");
882 }
883
884 send_packet(SSH_CMSG_EXEC_SHELL, PKT_END);
885 logevent("Started session");
886
887 ssh_state = SSH_STATE_SESSION;
888 if (size_needed)
889 ssh_size();
890
891 while (1) {
892 crReturnV;
893 if (ispkt) {
894 if (pktin.type == SSH_SMSG_STDOUT_DATA ||
895 pktin.type == SSH_SMSG_STDERR_DATA) {
896 long len = GET_32BIT(pktin.body);
897 c_write(pktin.body+4, len);
898 } else if (pktin.type == SSH_MSG_DISCONNECT) {
899 ssh_state = SSH_STATE_CLOSED;
900 logevent("Received disconnect request");
901 } else if (pktin.type == SSH_SMSG_SUCCESS) {
902 /* may be from EXEC_SHELL on some servers */
903 } else if (pktin.type == SSH_SMSG_FAILURE) {
904 /* may be from EXEC_SHELL on some servers
905 * if no pty is available or in other odd cases. Ignore */
906 } else if (pktin.type == SSH_SMSG_EXIT_STATUS) {
907 send_packet(SSH_CMSG_EXIT_CONFIRMATION, PKT_END);
908 } else {
909 fatalbox("Strange packet received: type %d", pktin.type);
910 }
911 } else {
912 send_packet(SSH_CMSG_STDIN_DATA,
913 PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
914 }
915 }
916
917 crFinishV;
918 }
919
920 /*
921 * Called to set up the connection. Will arrange for WM_NETEVENT
922 * messages to be passed to the specified window, whose window
923 * procedure should then call telnet_msg().
924 *
925 * Returns an error message, or NULL on success.
926 */
927 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
928 char *p;
929
930 #ifdef MSCRYPTOAPI
931 if(crypto_startup() == 0)
932 return "Microsoft high encryption pack not installed!";
933 #endif
934
935 p = connect_to_host(host, port, realhost);
936 if (p != NULL)
937 return p;
938
939 if (!do_ssh_init())
940 return "Protocol initialisation error";
941
942 if (WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
943 switch (WSAGetLastError()) {
944 case WSAENETDOWN: return "Network is down";
945 default: return "WSAAsyncSelect(): unknown error";
946 }
947
948 return NULL;
949 }
950
951 /*
952 * Process a WM_NETEVENT message. Will return 0 if the connection
953 * has closed, or <0 for a socket error.
954 */
955 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
956 int ret;
957 char buf[256];
958
959 /*
960 * Because reading less than the whole of the available pending
961 * data can generate an FD_READ event, we need to allow for the
962 * possibility that FD_READ may arrive with FD_CLOSE already in
963 * the queue; so it's possible that we can get here even with s
964 * invalid. If so, we return 1 and don't worry about it.
965 */
966 if (s == INVALID_SOCKET)
967 return 1;
968
969 if (WSAGETSELECTERROR(lParam) != 0)
970 return -WSAGETSELECTERROR(lParam);
971
972 switch (WSAGETSELECTEVENT(lParam)) {
973 case FD_READ:
974 case FD_CLOSE:
975 ret = recv(s, buf, sizeof(buf), 0);
976 if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
977 return 1;
978 if (ret < 0) /* any _other_ error */
979 return -10000-WSAGetLastError();
980 if (ret == 0) {
981 s = INVALID_SOCKET;
982 return 0;
983 }
984 ssh_gotdata (buf, ret);
985 return 1;
986 }
987 return 1; /* shouldn't happen, but WTF */
988 }
989
990 /*
991 * Called to send data down the Telnet connection.
992 */
993 static void ssh_send (char *buf, int len) {
994 if (s == INVALID_SOCKET)
995 return;
996
997 ssh_protocol(buf, len, 0);
998 }
999
1000 /*
1001 * Called to set the size of the window from Telnet's POV.
1002 */
1003 static void ssh_size(void) {
1004 switch (ssh_state) {
1005 case SSH_STATE_BEFORE_SIZE:
1006 case SSH_STATE_CLOSED:
1007 break; /* do nothing */
1008 case SSH_STATE_INTERMED:
1009 size_needed = TRUE; /* buffer for later */
1010 break;
1011 case SSH_STATE_SESSION:
1012 if (!cfg.nopty) {
1013 send_packet(SSH_CMSG_WINDOW_SIZE,
1014 PKT_INT, rows, PKT_INT, cols,
1015 PKT_INT, 0, PKT_INT, 0, PKT_END);
1016 }
1017 }
1018 }
1019
1020 /*
1021 * (Send Telnet special codes)
1022 */
1023 static void ssh_special (Telnet_Special code) {
1024 /* do nothing */
1025 }
1026
1027
1028 /*
1029 * Read and decrypt one incoming SSH packet.
1030 * (only used by pSCP)
1031 */
1032 static void get_packet(void)
1033 {
1034 unsigned char buf[4096], *p;
1035 long to_read;
1036 int len;
1037
1038 assert(IS_SCP);
1039
1040 p = NULL;
1041 len = 0;
1042
1043 while ((to_read = s_rdpkt(&p, &len)) > 0) {
1044 if (to_read > sizeof(buf)) to_read = sizeof(buf);
1045 len = s_read(buf, to_read);
1046 if (len != to_read) {
1047 closesocket(s);
1048 s = INVALID_SOCKET;
1049 return;
1050 }
1051 p = buf;
1052 }
1053
1054 assert(len == 0);
1055 }
1056
1057 /*
1058 * Receive a block of data over the SSH link. Block until
1059 * all data is available. Return nr of bytes read (0 if lost connection).
1060 * (only used by pSCP)
1061 */
1062 int ssh_scp_recv(unsigned char *buf, int len)
1063 {
1064 static int pending_input_len = 0;
1065 static unsigned char *pending_input_ptr;
1066 int to_read = len;
1067
1068 assert(IS_SCP);
1069
1070 if (pending_input_len >= to_read) {
1071 memcpy(buf, pending_input_ptr, to_read);
1072 pending_input_ptr += to_read;
1073 pending_input_len -= to_read;
1074 return len;
1075 }
1076
1077 if (pending_input_len > 0) {
1078 memcpy(buf, pending_input_ptr, pending_input_len);
1079 buf += pending_input_len;
1080 to_read -= pending_input_len;
1081 pending_input_len = 0;
1082 }
1083
1084 if (s == INVALID_SOCKET)
1085 return 0;
1086 while (to_read > 0) {
1087 get_packet();
1088 if (s == INVALID_SOCKET)
1089 return 0;
1090 if (pktin.type == SSH_SMSG_STDOUT_DATA) {
1091 int plen = GET_32BIT(pktin.body);
1092 if (plen <= to_read) {
1093 memcpy(buf, pktin.body + 4, plen);
1094 buf += plen;
1095 to_read -= plen;
1096 } else {
1097 memcpy(buf, pktin.body + 4, to_read);
1098 pending_input_len = plen - to_read;
1099 pending_input_ptr = pktin.body + 4 + to_read;
1100 to_read = 0;
1101 }
1102 } else if (pktin.type == SSH_SMSG_STDERR_DATA) {
1103 int plen = GET_32BIT(pktin.body);
1104 fwrite(pktin.body + 4, plen, 1, stderr);
1105 } else if (pktin.type == SSH_MSG_DISCONNECT) {
1106 logevent("Received disconnect request");
1107 } else if (pktin.type == SSH_SMSG_SUCCESS ||
1108 pktin.type == SSH_SMSG_FAILURE) {
1109 /* ignore */
1110 } else if (pktin.type == SSH_SMSG_EXIT_STATUS) {
1111 char logbuf[100];
1112 sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
1113 logevent(logbuf);
1114 send_packet(SSH_CMSG_EXIT_CONFIRMATION, PKT_END);
1115 logevent("Closing connection");
1116 closesocket(s);
1117 s = INVALID_SOCKET;
1118 } else {
1119 fatalbox("Strange packet received: type %d", pktin.type);
1120 }
1121 }
1122
1123 return len;
1124 }
1125
1126 /*
1127 * Send a block of data over the SSH link.
1128 * Block until all data is sent.
1129 * (only used by pSCP)
1130 */
1131 void ssh_scp_send(unsigned char *buf, int len)
1132 {
1133 assert(IS_SCP);
1134 if (s == INVALID_SOCKET)
1135 return;
1136 send_packet(SSH_CMSG_STDIN_DATA,
1137 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
1138 }
1139
1140 /*
1141 * Send an EOF notification to the server.
1142 * (only used by pSCP)
1143 */
1144 void ssh_scp_send_eof(void)
1145 {
1146 assert(IS_SCP);
1147 if (s == INVALID_SOCKET)
1148 return;
1149 send_packet(SSH_CMSG_EOF, PKT_END);
1150 }
1151
1152 /*
1153 * Set up the connection, login on the remote host and
1154 * start execution of a command.
1155 * Returns an error message, or NULL on success.
1156 * (only used by pSCP)
1157 */
1158 char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
1159 {
1160 char buf[160], *p;
1161
1162 assert(IS_SCP);
1163
1164 #ifdef MSCRYPTOAPI
1165 if (crypto_startup() == 0)
1166 return "Microsoft high encryption pack not installed!";
1167 #endif
1168
1169 p = connect_to_host(host, port, realhost);
1170 if (p != NULL)
1171 return p;
1172
1173 random_init();
1174
1175 if (!do_ssh_init())
1176 return "Protocol initialisation error";
1177
1178 /* Exchange keys and login */
1179 do {
1180 get_packet();
1181 if (s == INVALID_SOCKET)
1182 return "Connection closed by remote host";
1183 } while (!do_ssh_login(NULL, 0, 1));
1184
1185 /* Execute command */
1186 sprintf(buf, "Sending command: %.100s", cmd);
1187 logevent(buf);
1188 send_packet(SSH_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
1189
1190 return NULL;
1191 }
1192
1193
1194 Backend ssh_backend = {
1195 ssh_init,
1196 ssh_msg,
1197 ssh_send,
1198 ssh_size,
1199 ssh_special
1200 };
1201