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