Oops - remove diagnostics :-)
[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); \
4017be6d 19 if (!(flags & FLAG_CONNECTION) && (flags & FLAG_VERBOSE)) \
fb09bf1c 20 fprintf(stderr, "%s\n", s); }
21
e5574168 22#define SSH1_MSG_DISCONNECT 1
23#define SSH1_SMSG_PUBLIC_KEY 2
24#define SSH1_CMSG_SESSION_KEY 3
25#define SSH1_CMSG_USER 4
7cca0d81 26#define SSH1_CMSG_AUTH_RSA 6
27#define SSH1_SMSG_AUTH_RSA_CHALLENGE 7
28#define SSH1_CMSG_AUTH_RSA_RESPONSE 8
e5574168 29#define SSH1_CMSG_AUTH_PASSWORD 9
30#define SSH1_CMSG_REQUEST_PTY 10
31#define SSH1_CMSG_WINDOW_SIZE 11
32#define SSH1_CMSG_EXEC_SHELL 12
33#define SSH1_CMSG_EXEC_CMD 13
34#define SSH1_SMSG_SUCCESS 14
35#define SSH1_SMSG_FAILURE 15
36#define SSH1_CMSG_STDIN_DATA 16
37#define SSH1_SMSG_STDOUT_DATA 17
38#define SSH1_SMSG_STDERR_DATA 18
39#define SSH1_CMSG_EOF 19
40#define SSH1_SMSG_EXIT_STATUS 20
41#define SSH1_CMSG_EXIT_CONFIRMATION 33
42#define SSH1_MSG_IGNORE 32
43#define SSH1_MSG_DEBUG 36
44#define SSH1_CMSG_AUTH_TIS 39
45#define SSH1_SMSG_AUTH_TIS_CHALLENGE 40
46#define SSH1_CMSG_AUTH_TIS_RESPONSE 41
47
48#define SSH1_AUTH_TIS 5
49
50#define SSH2_MSG_DISCONNECT 1
51#define SSH2_MSG_IGNORE 2
52#define SSH2_MSG_UNIMPLEMENTED 3
53#define SSH2_MSG_DEBUG 4
54#define SSH2_MSG_SERVICE_REQUEST 5
55#define SSH2_MSG_SERVICE_ACCEPT 6
56#define SSH2_MSG_KEXINIT 20
57#define SSH2_MSG_NEWKEYS 21
58#define SSH2_MSG_KEXDH_INIT 30
59#define SSH2_MSG_KEXDH_REPLY 31
7cca0d81 60#define SSH2_MSG_USERAUTH_REQUEST 50
61#define SSH2_MSG_USERAUTH_FAILURE 51
62#define SSH2_MSG_USERAUTH_SUCCESS 52
63#define SSH2_MSG_USERAUTH_BANNER 53
64#define SSH2_MSG_USERAUTH_PK_OK 60
65#define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60
66#define SSH2_MSG_GLOBAL_REQUEST 80
67#define SSH2_MSG_REQUEST_SUCCESS 81
68#define SSH2_MSG_REQUEST_FAILURE 82
69#define SSH2_MSG_CHANNEL_OPEN 90
70#define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91
71#define SSH2_MSG_CHANNEL_OPEN_FAILURE 92
72#define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93
73#define SSH2_MSG_CHANNEL_DATA 94
74#define SSH2_MSG_CHANNEL_EXTENDED_DATA 95
75#define SSH2_MSG_CHANNEL_EOF 96
76#define SSH2_MSG_CHANNEL_CLOSE 97
77#define SSH2_MSG_CHANNEL_REQUEST 98
78#define SSH2_MSG_CHANNEL_SUCCESS 99
79#define SSH2_MSG_CHANNEL_FAILURE 100
80
81#define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1
82#define SSH2_OPEN_CONNECT_FAILED 2
83#define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3
84#define SSH2_OPEN_RESOURCE_SHORTAGE 4
85#define SSH2_EXTENDED_DATA_STDERR 1
fb09bf1c 86
87#define GET_32BIT(cp) \
88 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
89 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
90 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
91 ((unsigned long)(unsigned char)(cp)[3]))
92
93#define PUT_32BIT(cp, value) { \
94 (cp)[0] = (unsigned char)((value) >> 24); \
95 (cp)[1] = (unsigned char)((value) >> 16); \
96 (cp)[2] = (unsigned char)((value) >> 8); \
97 (cp)[3] = (unsigned char)(value); }
98
7cca0d81 99enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
972a41c8 100
374330e2 101/* Coroutine mechanics for the sillier bits of the code */
102#define crBegin1 static int crLine = 0;
103#define crBegin2 switch(crLine) { case 0:;
104#define crBegin crBegin1; crBegin2;
105#define crFinish(z) } crLine = 0; return (z)
106#define crFinishV } crLine = 0; return
107#define crReturn(z) \
108 do {\
109 crLine=__LINE__; return (z); case __LINE__:;\
110 } while (0)
111#define crReturnV \
112 do {\
113 crLine=__LINE__; return; case __LINE__:;\
114 } while (0)
115#define crStop(z) do{ crLine = 0; return (z); }while(0)
116#define crStopV do{ crLine = 0; return; }while(0)
fb09bf1c 117#define crWaitUntil(c) do { crReturn(0); } while (!(c))
7cca0d81 118#define crWaitUntilV(c) do { crReturnV; } while (!(c))
374330e2 119
e5574168 120extern struct ssh_cipher ssh_3des;
033b4cef 121extern struct ssh_cipher ssh_3des_ssh2;
e5574168 122extern struct ssh_cipher ssh_des;
123extern struct ssh_cipher ssh_blowfish;
124
125/* for ssh 2; we miss out single-DES because it isn't supported */
033b4cef 126struct ssh_cipher *ciphers[] = { &ssh_3des_ssh2, &ssh_blowfish };
e5574168 127
128extern struct ssh_kex ssh_diffiehellman;
129struct ssh_kex *kex_algs[] = { &ssh_diffiehellman };
130
131extern struct ssh_hostkey ssh_dss;
132struct ssh_hostkey *hostkey_algs[] = { &ssh_dss };
133
134extern struct ssh_mac ssh_sha1;
135
136SHA_State exhash;
137
d39f364a 138static void nullmac_key(unsigned char *key) { }
e5574168 139static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
140static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
141struct ssh_mac ssh_mac_none = {
d39f364a 142 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
e5574168 143};
144struct ssh_mac *macs[] = { &ssh_sha1, &ssh_mac_none };
145
146struct ssh_compress ssh_comp_none = {
147 "none"
148};
149struct ssh_compress *compressions[] = { &ssh_comp_none };
150
374330e2 151static SOCKET s = INVALID_SOCKET;
152
153static unsigned char session_key[32];
154static struct ssh_cipher *cipher = NULL;
e5574168 155static struct ssh_cipher *cscipher = NULL;
156static struct ssh_cipher *sccipher = NULL;
157static struct ssh_mac *csmac = NULL;
158static struct ssh_mac *scmac = NULL;
159static struct ssh_compress *cscomp = NULL;
160static struct ssh_compress *sccomp = NULL;
161static struct ssh_kex *kex = NULL;
162static struct ssh_hostkey *hostkey = NULL;
85ee8208 163int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
374330e2 164
165static char *savedhost;
8ccc75b0 166static int ssh_send_ok;
374330e2 167
168static enum {
169 SSH_STATE_BEFORE_SIZE,
170 SSH_STATE_INTERMED,
21248260 171 SSH_STATE_SESSION,
172 SSH_STATE_CLOSED
374330e2 173} ssh_state = SSH_STATE_BEFORE_SIZE;
174
175static int size_needed = FALSE;
176
177static void s_write (char *buf, int len) {
178 while (len > 0) {
179 int i = send (s, buf, len, 0);
4017be6d 180 noise_ultralight(i);
181 if (i <= 0)
182 fatalbox("Lost connection while sending");
374330e2 183 if (i > 0)
184 len -= i, buf += i;
185 }
186}
187
188static int s_read (char *buf, int len) {
189 int ret = 0;
190 while (len > 0) {
191 int i = recv (s, buf, len, 0);
4017be6d 192 noise_ultralight(i);
374330e2 193 if (i > 0)
194 len -= i, buf += i, ret += i;
195 else
196 return i;
197 }
198 return ret;
199}
200
201static void c_write (char *buf, int len) {
4017be6d 202 if (!(flags & FLAG_CONNECTION)) {
203 int i;
204 for (i = 0; i < len; i++)
205 if (buf[i] != '\r')
206 fputc(buf[i], stderr);
fb09bf1c 207 return;
208 }
c9def1b8 209 while (len--)
210 c_write1(*buf++);
374330e2 211}
212
213struct Packet {
214 long length;
215 int type;
374330e2 216 unsigned char *data;
217 unsigned char *body;
e5574168 218 long savedpos;
374330e2 219 long maxlen;
220};
221
fb09bf1c 222static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
223static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
374330e2 224
6abbf9e3 225static int ssh_version;
e5574168 226static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
227static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
228static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
374330e2 229static void ssh_size(void);
230
e5574168 231static int (*s_rdpkt)(unsigned char **data, int *datalen);
fb09bf1c 232
233/*
234 * Collect incoming data in the incoming packet buffer.
e5574168 235 * Decipher and verify the packet when it is completely read.
236 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
fb09bf1c 237 * Update the *data and *datalen variables.
238 * Return the additional nr of bytes needed, or 0 when
239 * a complete packet is available.
240 */
e5574168 241static int ssh1_rdpkt(unsigned char **data, int *datalen)
fb09bf1c 242{
243 static long len, pad, biglen, to_read;
572f871e 244 static unsigned long realcrc, gotcrc;
fb09bf1c 245 static unsigned char *p;
246 static int i;
374330e2 247
248 crBegin;
374330e2 249
fb09bf1c 250next_packet:
37508af4 251
fb09bf1c 252 pktin.type = 0;
253 pktin.length = 0;
374330e2 254
fb09bf1c 255 for (i = len = 0; i < 4; i++) {
256 while ((*datalen) == 0)
257 crReturn(4-i);
258 len = (len << 8) + **data;
259 (*data)++, (*datalen)--;
260 }
374330e2 261
fb09bf1c 262#ifdef FWHACK
263 if (len == 0x52656d6f) { /* "Remo"te server has closed ... */
264 len = 0x300; /* big enough to carry to end */
265 }
266#endif
374330e2 267
fb09bf1c 268 pad = 8 - (len % 8);
269 biglen = len + pad;
270 pktin.length = len - 5;
271
272 if (pktin.maxlen < biglen) {
273 pktin.maxlen = biglen;
e5574168 274 pktin.data = (pktin.data == NULL ? malloc(biglen+APIEXTRA) :
275 realloc(pktin.data, biglen+APIEXTRA));
fb09bf1c 276 if (!pktin.data)
277 fatalbox("Out of memory");
278 }
374330e2 279
fb09bf1c 280 to_read = biglen;
281 p = pktin.data;
282 while (to_read > 0) {
283 static int chunk;
284 chunk = to_read;
285 while ((*datalen) == 0)
286 crReturn(to_read);
287 if (chunk > (*datalen))
288 chunk = (*datalen);
289 memcpy(p, *data, chunk);
290 *data += chunk;
291 *datalen -= chunk;
292 p += chunk;
293 to_read -= chunk;
294 }
374330e2 295
fb09bf1c 296 if (cipher)
297 cipher->decrypt(pktin.data, biglen);
374330e2 298
fb09bf1c 299 pktin.type = pktin.data[pad];
300 pktin.body = pktin.data + pad + 1;
374330e2 301
fb09bf1c 302 realcrc = crc32(pktin.data, biglen-4);
303 gotcrc = GET_32BIT(pktin.data+biglen-4);
304 if (gotcrc != realcrc) {
305 fatalbox("Incorrect CRC received on packet");
306 }
572f871e 307
e5574168 308 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
309 pktin.type == SSH1_SMSG_STDERR_DATA ||
310 pktin.type == SSH1_MSG_DEBUG ||
311 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE) {
fb09bf1c 312 long strlen = GET_32BIT(pktin.body);
313 if (strlen + 4 != pktin.length)
314 fatalbox("Received data packet with bogus string length");
315 }
316
e5574168 317 if (pktin.type == SSH1_MSG_DEBUG) {
fb09bf1c 318 /* log debug message */
319 char buf[80];
320 int strlen = GET_32BIT(pktin.body);
321 strcpy(buf, "Remote: ");
322 if (strlen > 70) strlen = 70;
323 memcpy(buf+8, pktin.body+4, strlen);
324 buf[8+strlen] = '\0';
325 logevent(buf);
326 goto next_packet;
e5574168 327 } else if (pktin.type == SSH1_MSG_IGNORE) {
fb09bf1c 328 /* do nothing */
329 goto next_packet;
330 }
331
332 crFinish(0);
333}
334
e5574168 335static int ssh2_rdpkt(unsigned char **data, int *datalen)
336{
337 static long len, pad, payload, packetlen, maclen;
338 static int i;
339 static int cipherblk;
340 static unsigned long incoming_sequence = 0;
341
342 crBegin;
343
344next_packet:
345
346 pktin.type = 0;
347 pktin.length = 0;
348
349 if (cipher)
350 cipherblk = cipher->blksize;
351 else
352 cipherblk = 8;
353 if (cipherblk < 8)
354 cipherblk = 8;
355
356 if (pktin.maxlen < cipherblk) {
357 pktin.maxlen = cipherblk;
358 pktin.data = (pktin.data == NULL ? malloc(cipherblk+APIEXTRA) :
359 realloc(pktin.data, cipherblk+APIEXTRA));
360 if (!pktin.data)
361 fatalbox("Out of memory");
362 }
363
364 /*
365 * Acquire and decrypt the first block of the packet. This will
366 * contain the length and padding details.
367 */
368 for (i = len = 0; i < cipherblk; i++) {
369 while ((*datalen) == 0)
370 crReturn(cipherblk-i);
371 pktin.data[i] = *(*data)++;
372 (*datalen)--;
373 }
374#ifdef FWHACK
375 if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
376 /* FIXME */
377 }
378#endif
379 if (sccipher)
380 sccipher->decrypt(pktin.data, cipherblk);
381
382 /*
383 * Now get the length and padding figures.
384 */
385 len = GET_32BIT(pktin.data);
386 pad = pktin.data[4];
387
388 /*
389 * This enables us to deduce the payload length.
390 */
391 payload = len - pad - 1;
392
393 pktin.length = payload + 5;
394
395 /*
396 * So now we can work out the total packet length.
397 */
398 packetlen = len + 4;
399 maclen = scmac ? scmac->len : 0;
400
401 /*
402 * Adjust memory allocation if packet is too big.
403 */
404 if (pktin.maxlen < packetlen) {
405 pktin.maxlen = packetlen;
406 pktin.data = (pktin.data == NULL ? malloc(packetlen+APIEXTRA) :
407 realloc(pktin.data, packetlen+APIEXTRA));
408 if (!pktin.data)
409 fatalbox("Out of memory");
410 }
411
412 /*
413 * Read and decrypt the remainder of the packet.
414 */
415 for (i = cipherblk; i < packetlen + maclen; i++) {
416 while ((*datalen) == 0)
417 crReturn(packetlen + maclen - i);
418 pktin.data[i] = *(*data)++;
419 (*datalen)--;
420 }
421 /* Decrypt everything _except_ the MAC. */
422 if (sccipher)
423 sccipher->decrypt(pktin.data + cipherblk, packetlen - cipherblk);
424
7cca0d81 425#if 0
d39f364a 426 debug(("Got packet len=%d pad=%d\r\n", len, pad));
427 for (i = 0; i < packetlen; i++)
428 debug((" %02x", (unsigned char)pktin.data[i]));
429 debug(("\r\n"));
7cca0d81 430#endif
d39f364a 431
e5574168 432 /*
433 * Check the MAC.
434 */
033b4cef 435 if (scmac && !scmac->verify(pktin.data, len+4, incoming_sequence))
e5574168 436 fatalbox("Incorrect MAC received on packet");
033b4cef 437 incoming_sequence++; /* whether or not we MACed */
e5574168 438
439 pktin.savedpos = 6;
440 pktin.type = pktin.data[5];
e5574168 441
7cca0d81 442 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
443 goto next_packet; /* FIXME: print DEBUG message */
e5574168 444
445 crFinish(0);
446}
447
fb09bf1c 448static void ssh_gotdata(unsigned char *data, int datalen)
449{
450 while (datalen > 0) {
85ee8208 451 if ( s_rdpkt(&data, &datalen) == 0 ) {
374330e2 452 ssh_protocol(NULL, 0, 1);
85ee8208 453 if (ssh_state == SSH_STATE_CLOSED) {
454 return;
455 }
456 }
374330e2 457 }
374330e2 458}
459
fb09bf1c 460
374330e2 461static void s_wrpkt_start(int type, int len) {
462 int pad, biglen;
463
464 len += 5; /* type and CRC */
465 pad = 8 - (len%8);
466 biglen = len + pad;
467
468 pktout.length = len-5;
469 if (pktout.maxlen < biglen) {
470 pktout.maxlen = biglen;
8f203108 471#ifdef MSCRYPTOAPI
fb09bf1c 472 /* Allocate enough buffer space for extra block
8f203108 473 * for MS CryptEncrypt() */
fb09bf1c 474 pktout.data = (pktout.data == NULL ? malloc(biglen+12) :
475 realloc(pktout.data, biglen+12));
8f203108 476#else
c1f5f956 477 pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
478 realloc(pktout.data, biglen+4));
8f203108 479#endif
374330e2 480 if (!pktout.data)
481 fatalbox("Out of memory");
482 }
483
484 pktout.type = type;
485 pktout.body = pktout.data+4+pad+1;
486}
487
488static void s_wrpkt(void) {
489 int pad, len, biglen, i;
490 unsigned long crc;
491
492 len = pktout.length + 5; /* type and CRC */
493 pad = 8 - (len%8);
494 biglen = len + pad;
495
496 pktout.body[-1] = pktout.type;
497 for (i=0; i<pad; i++)
498 pktout.data[i+4] = random_byte();
499 crc = crc32(pktout.data+4, biglen-4);
fb09bf1c 500 PUT_32BIT(pktout.data+biglen, crc);
501 PUT_32BIT(pktout.data, len);
374330e2 502
503 if (cipher)
504 cipher->encrypt(pktout.data+4, biglen);
505
506 s_write(pktout.data, biglen+4);
507}
508
fb09bf1c 509/*
510 * Construct a packet with the specified contents and
511 * send it to the server.
512 */
513static void send_packet(int pkttype, ...)
514{
515 va_list args;
516 unsigned char *p, *argp, argchar;
517 unsigned long argint;
518 int pktlen, argtype, arglen;
7cca0d81 519 Bignum bn;
520 int i;
fb09bf1c 521
522 pktlen = 0;
523 va_start(args, pkttype);
524 while ((argtype = va_arg(args, int)) != PKT_END) {
525 switch (argtype) {
526 case PKT_INT:
527 (void) va_arg(args, int);
528 pktlen += 4;
529 break;
530 case PKT_CHAR:
531 (void) va_arg(args, char);
532 pktlen++;
533 break;
534 case PKT_DATA:
535 (void) va_arg(args, unsigned char *);
536 arglen = va_arg(args, int);
537 pktlen += arglen;
538 break;
539 case PKT_STR:
540 argp = va_arg(args, unsigned char *);
541 arglen = strlen(argp);
542 pktlen += 4 + arglen;
543 break;
7cca0d81 544 case PKT_BIGNUM:
545 bn = va_arg(args, Bignum);
546 i = 16 * bn[0] - 1;
547 while ( i > 0 && (bn[i/16+1] >> (i%16)) == 0 )
548 i--;
549 pktlen += 2 + (i+7)/8;
550 break;
fb09bf1c 551 default:
552 assert(0);
553 }
554 }
555 va_end(args);
556
557 s_wrpkt_start(pkttype, pktlen);
558 p = pktout.body;
559
560 va_start(args, pkttype);
561 while ((argtype = va_arg(args, int)) != PKT_END) {
562 switch (argtype) {
563 case PKT_INT:
564 argint = va_arg(args, int);
565 PUT_32BIT(p, argint);
566 p += 4;
567 break;
568 case PKT_CHAR:
569 argchar = va_arg(args, unsigned char);
570 *p = argchar;
571 p++;
572 break;
573 case PKT_DATA:
574 argp = va_arg(args, unsigned char *);
575 arglen = va_arg(args, int);
576 memcpy(p, argp, arglen);
577 p += arglen;
578 break;
579 case PKT_STR:
580 argp = va_arg(args, unsigned char *);
581 arglen = strlen(argp);
582 PUT_32BIT(p, arglen);
583 memcpy(p + 4, argp, arglen);
584 p += 4 + arglen;
585 break;
7cca0d81 586 case PKT_BIGNUM:
587 bn = va_arg(args, Bignum);
588 i = 16 * bn[0] - 1;
589 while ( i > 0 && (bn[i/16+1] >> (i%16)) == 0 )
590 i--;
591 *p++ = (i >> 8) & 0xFF;
592 *p++ = i & 0xFF;
593 i = (i + 7) / 8;
594 while (i-- > 0) {
595 if (i % 2)
596 *p++ = bn[i/2+1] >> 8;
597 else
598 *p++ = bn[i/2+1] & 0xFF;
599 }
600 break;
fb09bf1c 601 }
602 }
603 va_end(args);
604
605 s_wrpkt();
606}
607
608
609/*
610 * Connect to specified host and port.
611 * Returns an error message, or NULL on success.
612 * Also places the canonical host name into `realhost'.
613 */
614static char *connect_to_host(char *host, int port, char **realhost)
615{
616 SOCKADDR_IN addr;
617 struct hostent *h;
618 unsigned long a;
619#ifdef FWHACK
620 char *FWhost;
621 int FWport;
622#endif
623
624 savedhost = malloc(1+strlen(host));
625 if (!savedhost)
626 fatalbox("Out of memory");
627 strcpy(savedhost, host);
628
629 if (port < 0)
630 port = 22; /* default ssh port */
631
632#ifdef FWHACK
633 FWhost = host;
634 FWport = port;
635 host = FWSTR;
636 port = 23;
637#endif
638
639 /*
640 * Try to find host.
641 */
642 if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
643 if ( (h = gethostbyname(host)) == NULL)
644 switch (WSAGetLastError()) {
645 case WSAENETDOWN: return "Network is down";
646 case WSAHOST_NOT_FOUND: case WSANO_DATA:
647 return "Host does not exist";
648 case WSATRY_AGAIN: return "Host not found";
649 default: return "gethostbyname: unknown error";
650 }
651 memcpy (&a, h->h_addr, sizeof(a));
652 *realhost = h->h_name;
653 } else
654 *realhost = host;
655#ifdef FWHACK
656 *realhost = FWhost;
657#endif
658 a = ntohl(a);
659
660 /*
661 * Open socket.
662 */
663 s = socket(AF_INET, SOCK_STREAM, 0);
664 if (s == INVALID_SOCKET)
665 switch (WSAGetLastError()) {
666 case WSAENETDOWN: return "Network is down";
667 case WSAEAFNOSUPPORT: return "TCP/IP support not present";
668 default: return "socket(): unknown error";
669 }
670
671 /*
672 * Bind to local address.
673 */
674 addr.sin_family = AF_INET;
675 addr.sin_addr.s_addr = htonl(INADDR_ANY);
676 addr.sin_port = htons(0);
677 if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
678 switch (WSAGetLastError()) {
679 case WSAENETDOWN: return "Network is down";
680 default: return "bind(): unknown error";
681 }
682
683 /*
684 * Connect to remote address.
685 */
686 addr.sin_addr.s_addr = htonl(a);
687 addr.sin_port = htons((short)port);
688 if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
689 switch (WSAGetLastError()) {
690 case WSAENETDOWN: return "Network is down";
691 case WSAECONNREFUSED: return "Connection refused";
692 case WSAENETUNREACH: return "Network is unreachable";
693 case WSAEHOSTUNREACH: return "No route to host";
694 default: return "connect(): unknown error";
695 }
696
697#ifdef FWHACK
698 send(s, "connect ", 8, 0);
699 send(s, FWhost, strlen(FWhost), 0);
700 {
701 char buf[20];
702 sprintf(buf, " %d\n", FWport);
703 send (s, buf, strlen(buf), 0);
704 }
705#endif
706
707 return NULL;
708}
709
9697bfd2 710static int ssh_versioncmp(char *a, char *b) {
711 char *ae, *be;
712 unsigned long av, bv;
713
43aa02a7 714 av = strtoul(a, &ae, 10);
715 bv = strtoul(b, &be, 10);
9697bfd2 716 if (av != bv) return (av < bv ? -1 : +1);
717 if (*ae == '.') ae++;
718 if (*be == '.') be++;
43aa02a7 719 av = strtoul(ae, &ae, 10);
720 bv = strtoul(be, &be, 10);
9697bfd2 721 if (av != bv) return (av < bv ? -1 : +1);
722 return 0;
723}
724
e5574168 725
726/*
727 * Utility routine for putting an SSH-protocol `string' into a SHA
728 * state.
729 */
730#include <stdio.h>
731void sha_string(SHA_State *s, void *str, int len) {
732 unsigned char lenblk[4];
e5574168 733 PUT_32BIT(lenblk, len);
e5574168 734 SHA_Bytes(s, lenblk, 4);
e5574168 735 SHA_Bytes(s, str, len);
736}
737
7cca0d81 738/*
739 * SSH2 packet construction functions.
740 */
741void ssh2_pkt_adddata(void *data, int len) {
742 pktout.length += len;
743 if (pktout.maxlen < pktout.length) {
744 pktout.maxlen = pktout.length + 256;
745 pktout.data = (pktout.data == NULL ? malloc(pktout.maxlen+APIEXTRA) :
746 realloc(pktout.data, pktout.maxlen+APIEXTRA));
747 if (!pktout.data)
748 fatalbox("Out of memory");
749 }
750 memcpy(pktout.data+pktout.length-len, data, len);
751}
752void ssh2_pkt_addbyte(unsigned char byte) {
753 ssh2_pkt_adddata(&byte, 1);
754}
755void ssh2_pkt_init(int pkt_type) {
756 pktout.length = 5;
757 ssh2_pkt_addbyte((unsigned char)pkt_type);
758}
759void ssh2_pkt_addbool(unsigned char value) {
760 ssh2_pkt_adddata(&value, 1);
761}
762void ssh2_pkt_adduint32(unsigned long value) {
763 unsigned char x[4];
764 PUT_32BIT(x, value);
765 ssh2_pkt_adddata(x, 4);
766}
767void ssh2_pkt_addstring_start(void) {
768 ssh2_pkt_adduint32(0);
769 pktout.savedpos = pktout.length;
770}
771void ssh2_pkt_addstring_str(char *data) {
772 ssh2_pkt_adddata(data, strlen(data));
773 PUT_32BIT(pktout.data + pktout.savedpos - 4,
774 pktout.length - pktout.savedpos);
775}
776void ssh2_pkt_addstring_data(char *data, int len) {
777 ssh2_pkt_adddata(data, len);
778 PUT_32BIT(pktout.data + pktout.savedpos - 4,
779 pktout.length - pktout.savedpos);
780}
781void ssh2_pkt_addstring(char *data) {
782 ssh2_pkt_addstring_start();
783 ssh2_pkt_addstring_str(data);
784}
785char *ssh2_mpint_fmt(Bignum b, int *len) {
786 unsigned char *p;
787 int i, n = b[0];
788 p = malloc(n * 2 + 1);
789 if (!p)
790 fatalbox("out of memory");
791 p[0] = 0;
792 for (i = 0; i < n; i++) {
793 p[i*2+1] = (b[n-i] >> 8) & 0xFF;
794 p[i*2+2] = (b[n-i] ) & 0xFF;
795 }
796 i = 0;
797 while (p[i] == 0 && (p[i+1] & 0x80) == 0)
798 i++;
799 memmove(p, p+i, n*2+1-i);
800 *len = n*2+1-i;
801 return p;
802}
803void ssh2_pkt_addmp(Bignum b) {
804 unsigned char *p;
805 int len;
806 p = ssh2_mpint_fmt(b, &len);
807 ssh2_pkt_addstring_start();
808 ssh2_pkt_addstring_data(p, len);
809 free(p);
810}
811void ssh2_pkt_send(void) {
812 int cipherblk, maclen, padding, i;
813 static unsigned long outgoing_sequence = 0;
814
815 /*
816 * Add padding. At least four bytes, and must also bring total
817 * length (minus MAC) up to a multiple of the block size.
818 */
819 cipherblk = cipher ? cipher->blksize : 8; /* block size */
820 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
821 padding = 4;
822 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
823 pktout.data[4] = padding;
824 for (i = 0; i < padding; i++)
825 pktout.data[pktout.length + i] = random_byte();
826 PUT_32BIT(pktout.data, pktout.length + padding - 4);
827 if (csmac)
828 csmac->generate(pktout.data, pktout.length + padding,
829 outgoing_sequence);
830 outgoing_sequence++; /* whether or not we MACed */
831
832#if 0
833 debug(("Sending packet len=%d\r\n", pktout.length+padding));
834 for (i = 0; i < pktout.length+padding; i++)
835 debug((" %02x", (unsigned char)pktout.data[i]));
836 debug(("\r\n"));
837#endif
838
839 if (cscipher)
840 cscipher->encrypt(pktout.data, pktout.length + padding);
841 maclen = csmac ? csmac->len : 0;
842
843 s_write(pktout.data, pktout.length + padding + maclen);
844}
845
846#if 0
847void bndebug(char *string, Bignum b) {
848 unsigned char *p;
849 int i, len;
850 p = ssh2_mpint_fmt(b, &len);
851 debug(("%s", string));
852 for (i = 0; i < len; i++)
853 debug((" %02x", p[i]));
854 debug(("\r\n"));
855 free(p);
856}
857#endif
858
859void sha_mpint(SHA_State *s, Bignum b) {
860 unsigned char *p;
861 int len;
862 p = ssh2_mpint_fmt(b, &len);
863 sha_string(s, p, len);
864 free(p);
865}
866
867/*
868 * SSH2 packet decode functions.
869 */
870unsigned long ssh2_pkt_getuint32(void) {
871 unsigned long value;
872 if (pktin.length - pktin.savedpos < 4)
873 return 0; /* arrgh, no way to decline (FIXME?) */
874 value = GET_32BIT(pktin.data+pktin.savedpos);
875 pktin.savedpos += 4;
876 return value;
877}
878void ssh2_pkt_getstring(char **p, int *length) {
879 *p = NULL;
880 if (pktin.length - pktin.savedpos < 4)
881 return;
882 *length = GET_32BIT(pktin.data+pktin.savedpos);
883 pktin.savedpos += 4;
884 if (pktin.length - pktin.savedpos < *length)
885 return;
886 *p = pktin.data+pktin.savedpos;
887 pktin.savedpos += *length;
888}
889Bignum ssh2_pkt_getmp(void) {
890 char *p;
891 int i, j, length;
892 Bignum b;
893
894 ssh2_pkt_getstring(&p, &length);
895 if (!p)
896 return NULL;
897 if (p[0] & 0x80)
898 fatalbox("internal error: Can't handle negative mpints");
899 b = newbn((length+1)/2);
900 for (i = 0; i < length; i++) {
901 j = length - 1 - i;
902 if (j & 1)
903 b[j/2+1] |= ((unsigned char)p[i]) << 8;
904 else
905 b[j/2+1] |= ((unsigned char)p[i]);
906 }
907 return b;
908}
909
374330e2 910static int do_ssh_init(void) {
c5e9c988 911 char c, *vsp;
374330e2 912 char version[10];
c5e9c988 913 char vstring[80];
914 char vlog[sizeof(vstring)+20];
374330e2 915 int i;
916
917#ifdef FWHACK
918 i = 0;
919 while (s_read(&c, 1) == 1) {
920 if (c == 'S' && i < 2) i++;
921 else if (c == 'S' && i == 2) i = 2;
922 else if (c == 'H' && i == 2) break;
923 else i = 0;
924 }
925#else
926 if (s_read(&c,1) != 1 || c != 'S') return 0;
927 if (s_read(&c,1) != 1 || c != 'S') return 0;
928 if (s_read(&c,1) != 1 || c != 'H') return 0;
929#endif
c5e9c988 930 strcpy(vstring, "SSH-");
931 vsp = vstring+4;
374330e2 932 if (s_read(&c,1) != 1 || c != '-') return 0;
933 i = 0;
934 while (1) {
935 if (s_read(&c,1) != 1)
936 return 0;
c5e9c988 937 if (vsp < vstring+sizeof(vstring)-1)
938 *vsp++ = c;
374330e2 939 if (i >= 0) {
940 if (c == '-') {
941 version[i] = '\0';
942 i = -1;
943 } else if (i < sizeof(version)-1)
944 version[i++] = c;
945 }
946 else if (c == '\n')
947 break;
948 }
949
c5e9c988 950 *vsp = 0;
951 sprintf(vlog, "Server version: %s", vstring);
952 vlog[strcspn(vlog, "\r\n")] = '\0';
953 logevent(vlog);
954
7cca0d81 955 if (ssh_versioncmp(version, "2.0" /* FIXME: "1.99" */ ) >= 0) {
e5574168 956 /*
957 * This is a v2 server. Begin v2 protocol.
958 */
959 char *verstring = "SSH-2.0-PuTTY";
960 SHA_Init(&exhash);
961 /*
962 * Hash our version string and their version string.
963 */
964 sha_string(&exhash, verstring, strlen(verstring));
965 sha_string(&exhash, vstring, strcspn(vstring, "\r\n"));
966 sprintf(vstring, "%s\n", verstring);
967 sprintf(vlog, "We claim version: %s", verstring);
968 logevent(vlog);
969 logevent("Using SSH protocol version 2");
970 s_write(vstring, strlen(vstring));
971 ssh_protocol = ssh2_protocol;
6abbf9e3 972 ssh_version = 2;
e5574168 973 s_rdpkt = ssh2_rdpkt;
974 } else {
975 /*
976 * This is a v1 server. Begin v1 protocol.
977 */
978 sprintf(vstring, "SSH-%s-PuTTY\n",
979 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
980 sprintf(vlog, "We claim version: %s", vstring);
981 vlog[strcspn(vlog, "\r\n")] = '\0';
982 logevent(vlog);
983 logevent("Using SSH protocol version 1");
984 s_write(vstring, strlen(vstring));
985 ssh_protocol = ssh1_protocol;
6abbf9e3 986 ssh_version = 1;
e5574168 987 s_rdpkt = ssh1_rdpkt;
988 }
8ccc75b0 989 ssh_send_ok = 0;
fef97f43 990 return 1;
374330e2 991}
992
fb09bf1c 993/*
994 * Handle the key exchange and user authentication phases.
995 */
e5574168 996static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
fb09bf1c 997{
374330e2 998 int i, j, len;
374330e2 999 unsigned char *rsabuf, *keystr1, *keystr2;
1000 unsigned char cookie[8];
1001 struct RSAKey servkey, hostkey;
1002 struct MD5Context md5c;
ccbfb941 1003 static unsigned long supported_ciphers_mask, supported_auths_mask;
7cca0d81 1004 static int tried_publickey;
1005 static unsigned char session_id[16];
bea1ef5f 1006 int cipher_type;
374330e2 1007
374330e2 1008 crBegin;
1009
fb09bf1c 1010 if (!ispkt) crWaitUntil(ispkt);
374330e2 1011
e5574168 1012 if (pktin.type != SSH1_SMSG_PUBLIC_KEY)
374330e2 1013 fatalbox("Public key packet not received");
1014
c5e9c988 1015 logevent("Received public keys");
374330e2 1016
c5e9c988 1017 memcpy(cookie, pktin.body, 8);
374330e2 1018
7cca0d81 1019 i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1020 j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
374330e2 1021
c5e9c988 1022 /*
1023 * Hash the host key and print the hash in the log box. Just as
1024 * a last resort in case the registry's host key checking is
1025 * compromised, we'll allow the user some ability to verify
1026 * host keys by eye.
1027 */
1028 MD5Init(&md5c);
1029 MD5Update(&md5c, keystr2, hostkey.bytes);
1030 MD5Final(session_id, &md5c);
1031 {
1032 char logmsg[80];
1033 int i;
1034 logevent("Host key MD5 is:");
1035 strcpy(logmsg, " ");
1036 for (i = 0; i < 16; i++)
1037 sprintf(logmsg+strlen(logmsg), "%02x", session_id[i]);
1038 logevent(logmsg);
1039 }
1040
fb09bf1c 1041 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1042 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
bea1ef5f 1043
c5e9c988 1044 MD5Init(&md5c);
374330e2 1045 MD5Update(&md5c, keystr2, hostkey.bytes);
1046 MD5Update(&md5c, keystr1, servkey.bytes);
1047 MD5Update(&md5c, pktin.body, 8);
374330e2 1048 MD5Final(session_id, &md5c);
1049
1050 for (i=0; i<32; i++)
1051 session_key[i] = random_byte();
1052
1053 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1054
1055 rsabuf = malloc(len);
1056 if (!rsabuf)
1057 fatalbox("Out of memory");
1058
89ee5268 1059 /*
1060 * Verify the host key.
1061 */
1062 {
1063 /*
1064 * First format the key into a string.
1065 */
1066 int len = rsastr_len(&hostkey);
1067 char *keystr = malloc(len);
1068 if (!keystr)
1069 fatalbox("Out of memory");
1070 rsastr_fmt(keystr, &hostkey);
1071 verify_ssh_host_key(savedhost, keystr);
1072 free(keystr);
1073 }
374330e2 1074
1075 for (i=0; i<32; i++) {
1076 rsabuf[i] = session_key[i];
1077 if (i < 16)
1078 rsabuf[i] ^= session_id[i];
1079 }
1080
1081 if (hostkey.bytes > servkey.bytes) {
1082 rsaencrypt(rsabuf, 32, &servkey);
1083 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1084 } else {
1085 rsaencrypt(rsabuf, 32, &hostkey);
1086 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1087 }
1088
c5e9c988 1089 logevent("Encrypted session key");
1090
bea1ef5f 1091 cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
9697bfd2 1092 cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES :
bea1ef5f 1093 SSH_CIPHER_3DES;
1094 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1095 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1096 cipher_type = SSH_CIPHER_3DES;
1097 }
c5e9c988 1098 switch (cipher_type) {
1099 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1100 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1101 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1102 }
bea1ef5f 1103
e5574168 1104 send_packet(SSH1_CMSG_SESSION_KEY,
fb09bf1c 1105 PKT_CHAR, cipher_type,
1106 PKT_DATA, cookie, 8,
1107 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1108 PKT_DATA, rsabuf, len,
1109 PKT_INT, 0,
1110 PKT_END);
1111
c5e9c988 1112 logevent("Trying to enable encryption...");
374330e2 1113
1114 free(rsabuf);
1115
bea1ef5f 1116 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
9697bfd2 1117 cipher_type == SSH_CIPHER_DES ? &ssh_des :
bea1ef5f 1118 &ssh_3des;
374330e2 1119 cipher->sesskey(session_key);
1120
fb09bf1c 1121 crWaitUntil(ispkt);
374330e2 1122
e5574168 1123 if (pktin.type != SSH1_SMSG_SUCCESS)
374330e2 1124 fatalbox("Encryption not successfully enabled");
1125
c5e9c988 1126 logevent("Successfully started encryption");
1127
374330e2 1128 fflush(stdout);
1129 {
1130 static char username[100];
1131 static int pos = 0;
1132 static char c;
4017be6d 1133 if (!(flags & FLAG_CONNECTION) && !*cfg.username) {
374330e2 1134 c_write("login as: ", 10);
1135 while (pos >= 0) {
fb09bf1c 1136 crWaitUntil(!ispkt);
374330e2 1137 while (inlen--) switch (c = *in++) {
1138 case 10: case 13:
1139 username[pos] = 0;
1140 pos = -1;
1141 break;
1142 case 8: case 127:
1143 if (pos > 0) {
1144 c_write("\b \b", 3);
1145 pos--;
1146 }
1147 break;
1148 case 21: case 27:
1149 while (pos > 0) {
1150 c_write("\b \b", 3);
1151 pos--;
1152 }
1153 break;
1154 case 3: case 4:
1155 random_save_seed();
1156 exit(0);
1157 break;
1158 default:
40d24aa6 1159 if (((c >= ' ' && c <= '~') ||
1160 ((unsigned char)c >= 160)) && pos < 40) {
374330e2 1161 username[pos++] = c;
1162 c_write(&c, 1);
1163 }
1164 break;
1165 }
1166 }
1167 c_write("\r\n", 2);
1168 username[strcspn(username, "\n\r")] = '\0';
1169 } else {
1170 char stuff[200];
1171 strncpy(username, cfg.username, 99);
1172 username[99] = '\0';
4017be6d 1173 if (flags & FLAG_VERBOSE) {
fb09bf1c 1174 sprintf(stuff, "Sent username \"%s\".\r\n", username);
4017be6d 1175 c_write(stuff, strlen(stuff));
fb09bf1c 1176 }
374330e2 1177 }
fb09bf1c 1178
e5574168 1179 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
c5e9c988 1180 {
1181 char userlog[20+sizeof(username)];
1182 sprintf(userlog, "Sent username \"%s\"", username);
1183 logevent(userlog);
1184 }
374330e2 1185 }
1186
fb09bf1c 1187 crWaitUntil(ispkt);
374330e2 1188
7cca0d81 1189 tried_publickey = 0;
1190
e5574168 1191 while (pktin.type == SSH1_SMSG_FAILURE) {
374330e2 1192 static char password[100];
1193 static int pos;
1194 static char c;
ccbfb941 1195 static int pwpkt_type;
ccbfb941 1196 /*
1197 * Show password prompt, having first obtained it via a TIS
1198 * exchange if we're doing TIS authentication.
1199 */
e5574168 1200 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
7cca0d81 1201 if (*cfg.keyfile && !tried_publickey)
1202 pwpkt_type = SSH1_CMSG_AUTH_RSA;
fb09bf1c 1203
4017be6d 1204 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD && !FLAG_WINDOWED) {
fb09bf1c 1205 char prompt[200];
1206 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
85ee8208 1207 if (!ssh_get_password(prompt, password, sizeof(password))) {
1208 /*
1209 * get_password failed to get a password (for
1210 * example because one was supplied on the command
1211 * line which has already failed to work).
1212 * Terminate.
1213 */
1214 logevent("No more passwords to try");
1215 ssh_state = SSH_STATE_CLOSED;
1216 crReturn(1);
1217 }
fb09bf1c 1218 } else {
1219
7cca0d81 1220 if (pktin.type == SSH1_SMSG_FAILURE &&
1221 cfg.try_tis_auth &&
1222 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1223 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1224 logevent("Requested TIS authentication");
1225 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1226 crWaitUntil(ispkt);
1227 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1228 logevent("TIS authentication declined");
1229 c_write("TIS authentication refused.\r\n", 29);
1230 } else {
1231 int challengelen = ((pktin.body[0] << 24) |
1232 (pktin.body[1] << 16) |
1233 (pktin.body[2] << 8) |
1234 (pktin.body[3]));
1235 logevent("Received TIS challenge");
1236 c_write(pktin.body+4, challengelen);
1237 }
1238 }
1239 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD)
1240 c_write("password: ", 10);
1241 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
4017be6d 1242 if (flags & FLAG_VERBOSE)
1243 c_write("Trying public key authentication.\r\n", 35);
7cca0d81 1244 if (!rsakey_encrypted(cfg.keyfile)) {
4017be6d 1245 if (flags & FLAG_VERBOSE)
1246 c_write("No passphrase required.\r\n", 25);
7cca0d81 1247 goto tryauth;
1248 }
1249 c_write("passphrase: ", 12);
ccbfb941 1250 }
ccbfb941 1251
7cca0d81 1252 pos = 0;
1253 while (pos >= 0) {
1254 crWaitUntil(!ispkt);
1255 while (inlen--) switch (c = *in++) {
1256 case 10: case 13:
1257 password[pos] = 0;
1258 pos = -1;
1259 break;
1260 case 8: case 127:
1261 if (pos > 0)
1262 pos--;
1263 break;
1264 case 21: case 27:
1265 pos = 0;
1266 break;
1267 case 3: case 4:
1268 random_save_seed();
1269 exit(0);
1270 break;
1271 default:
1272 if (((c >= ' ' && c <= '~') ||
1273 ((unsigned char)c >= 160)) && pos < sizeof(password))
1274 password[pos++] = c;
1275 break;
1276 }
1277 }
1278 c_write("\r\n", 2);
fb09bf1c 1279
1280 }
1281
7cca0d81 1282 tryauth:
1283 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1284 /*
1285 * Try public key authentication with the specified
1286 * key file.
1287 */
1288 static struct RSAKey pubkey;
1289 static Bignum challenge, response;
1290 static int i;
1291 static unsigned char buffer[32];
1292
1293 tried_publickey = 1;
1294 i = loadrsakey(cfg.keyfile, &pubkey, password);
1295 if (i == 0) {
1296 c_write("Couldn't load public key from ", 30);
1297 c_write(cfg.keyfile, strlen(cfg.keyfile));
1298 c_write(".\r\n", 3);
1299 continue; /* go and try password */
1300 }
1301 if (i == -1) {
1302 c_write("Wrong passphrase.\r\n", 19);
1303 tried_publickey = 0;
1304 continue; /* try again */
1305 }
1306
1307 /*
1308 * Send a public key attempt.
1309 */
1310 send_packet(SSH1_CMSG_AUTH_RSA,
1311 PKT_BIGNUM, pubkey.modulus, PKT_END);
1312
1313 crWaitUntil(ispkt);
1314 if (pktin.type == SSH1_SMSG_FAILURE) {
4017be6d 1315 if (flags & FLAG_VERBOSE)
1316 c_write("Server refused our public key.\r\n", 32);
7cca0d81 1317 continue; /* go and try password */
1318 }
1319 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE)
1320 fatalbox("Bizarre response to offer of public key");
1321 ssh1_read_bignum(pktin.body, &challenge);
1322 response = rsadecrypt(challenge, &pubkey);
1323 freebn(pubkey.private_exponent); /* burn the evidence */
1324
1325 for (i = 0; i < 32; i += 2) {
1326 buffer[i] = response[16-i/2] >> 8;
1327 buffer[i+1] = response[16-i/2] & 0xFF;
1328 }
1329
1330 MD5Init(&md5c);
1331 MD5Update(&md5c, buffer, 32);
1332 MD5Update(&md5c, session_id, 16);
1333 MD5Final(buffer, &md5c);
1334
1335 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1336 PKT_DATA, buffer, 16, PKT_END);
1337
1338 crWaitUntil(ispkt);
1339 if (pktin.type == SSH1_SMSG_FAILURE) {
4017be6d 1340 if (flags & FLAG_VERBOSE)
1341 c_write("Failed to authenticate with our public key.\r\n",
1342 45);
7cca0d81 1343 continue; /* go and try password */
1344 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1345 fatalbox("Bizarre response to RSA authentication response");
1346 }
1347
1348 break; /* we're through! */
1349 } else {
1350 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1351 }
c5e9c988 1352 logevent("Sent password");
374330e2 1353 memset(password, 0, strlen(password));
fb09bf1c 1354 crWaitUntil(ispkt);
e5574168 1355 if (pktin.type == SSH1_SMSG_FAILURE) {
4017be6d 1356 if (flags & FLAG_VERBOSE)
1357 c_write("Access denied\r\n", 15);
c5e9c988 1358 logevent("Authentication refused");
e5574168 1359 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
fb09bf1c 1360 logevent("Received disconnect request");
85ee8208 1361 ssh_state = SSH_STATE_CLOSED;
1362 crReturn(1);
e5574168 1363 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
374330e2 1364 fatalbox("Strange packet received, type %d", pktin.type);
1365 }
1366 }
1367
c5e9c988 1368 logevent("Authentication successful");
1369
fb09bf1c 1370 crFinish(1);
1371}
1372
e5574168 1373static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
fb09bf1c 1374 crBegin;
1375
1376 random_init();
1377
e5574168 1378 while (!do_ssh1_login(in, inlen, ispkt)) {
fb09bf1c 1379 crReturnV;
85ee8208 1380 }
1381 if (ssh_state == SSH_STATE_CLOSED)
1382 crReturnV;
fb09bf1c 1383
fef97f43 1384 if (!cfg.nopty) {
e5574168 1385 send_packet(SSH1_CMSG_REQUEST_PTY,
fb09bf1c 1386 PKT_STR, cfg.termtype,
1387 PKT_INT, rows, PKT_INT, cols,
1388 PKT_INT, 0, PKT_INT, 0,
1389 PKT_CHAR, 0,
1390 PKT_END);
fef97f43 1391 ssh_state = SSH_STATE_INTERMED;
1392 do { crReturnV; } while (!ispkt);
e5574168 1393 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
fef97f43 1394 fatalbox("Protocol confusion");
e5574168 1395 } else if (pktin.type == SSH1_SMSG_FAILURE) {
fef97f43 1396 c_write("Server refused to allocate pty\r\n", 32);
1397 }
c5e9c988 1398 logevent("Allocated pty");
374330e2 1399 }
1400
6abbf9e3 1401 if (*cfg.remote_cmd)
1402 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1403 else
1404 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
c5e9c988 1405 logevent("Started session");
374330e2 1406
1407 ssh_state = SSH_STATE_SESSION;
1408 if (size_needed)
1409 ssh_size();
1410
8ccc75b0 1411 ssh_send_ok = 1;
374330e2 1412 while (1) {
1413 crReturnV;
1414 if (ispkt) {
e5574168 1415 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1416 pktin.type == SSH1_SMSG_STDERR_DATA) {
fb09bf1c 1417 long len = GET_32BIT(pktin.body);
1418 c_write(pktin.body+4, len);
e5574168 1419 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
21248260 1420 ssh_state = SSH_STATE_CLOSED;
c5e9c988 1421 logevent("Received disconnect request");
e5574168 1422 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
972a41c8 1423 /* may be from EXEC_SHELL on some servers */
e5574168 1424 } else if (pktin.type == SSH1_SMSG_FAILURE) {
972a41c8 1425 /* may be from EXEC_SHELL on some servers
374330e2 1426 * if no pty is available or in other odd cases. Ignore */
e5574168 1427 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1428 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
374330e2 1429 } else {
1430 fatalbox("Strange packet received: type %d", pktin.type);
1431 }
1432 } else {
e5574168 1433 send_packet(SSH1_CMSG_STDIN_DATA,
fb09bf1c 1434 PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
374330e2 1435 }
1436 }
1437
1438 crFinishV;
1439}
1440
1441/*
e5574168 1442 * Utility routine for decoding comma-separated strings in KEXINIT.
1443 */
1444int in_commasep_string(char *needle, char *haystack, int haylen) {
1445 int needlen = strlen(needle);
1446 while (1) {
1447 /*
1448 * Is it at the start of the string?
1449 */
1450 if (haylen >= needlen && /* haystack is long enough */
1451 !memcmp(needle, haystack, needlen) && /* initial match */
1452 (haylen == needlen || haystack[needlen] == ',')
1453 /* either , or EOS follows */
1454 )
1455 return 1;
1456 /*
1457 * If not, search for the next comma and resume after that.
1458 * If no comma found, terminate.
1459 */
1460 while (haylen > 0 && *haystack != ',')
1461 haylen--, haystack++;
1462 if (haylen == 0)
1463 return 0;
1464 haylen--, haystack++; /* skip over comma itself */
1465 }
1466}
1467
1468/*
d39f364a 1469 * SSH2 key creation method.
1470 */
1471void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1472 SHA_State s;
1473 /* First 20 bytes. */
1474 SHA_Init(&s);
1475 sha_mpint(&s, K);
1476 SHA_Bytes(&s, H, 20);
1477 SHA_Bytes(&s, &chr, 1);
1478 SHA_Bytes(&s, H, 20);
1479 SHA_Final(&s, keyspace);
1480 /* Next 20 bytes. */
1481 SHA_Init(&s);
1482 sha_mpint(&s, K);
1483 SHA_Bytes(&s, H, 20);
1484 SHA_Bytes(&s, keyspace, 20);
1485 SHA_Final(&s, keyspace+20);
1486}
1487
1488/*
7cca0d81 1489 * Handle the SSH2 transport layer.
e5574168 1490 */
7cca0d81 1491static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
e5574168 1492{
1493 static int i, len;
1494 static char *str;
1495 static Bignum e, f, K;
1496 static struct ssh_cipher *cscipher_tobe = NULL;
1497 static struct ssh_cipher *sccipher_tobe = NULL;
1498 static struct ssh_mac *csmac_tobe = NULL;
1499 static struct ssh_mac *scmac_tobe = NULL;
1500 static struct ssh_compress *cscomp_tobe = NULL;
1501 static struct ssh_compress *sccomp_tobe = NULL;
7cca0d81 1502 static char *hostkeydata, *sigdata, *keystr;
e5574168 1503 static int hostkeylen, siglen;
1504 static unsigned char exchange_hash[20];
d39f364a 1505 static unsigned char keyspace[40];
e5574168 1506
1507 crBegin;
7cca0d81 1508 random_init();
e5574168 1509
7cca0d81 1510 begin_key_exchange:
e5574168 1511 /*
1512 * Construct and send our key exchange packet.
1513 */
1514 ssh2_pkt_init(SSH2_MSG_KEXINIT);
1515 for (i = 0; i < 16; i++)
1516 ssh2_pkt_addbyte((unsigned char)random_byte());
1517 /* List key exchange algorithms. */
1518 ssh2_pkt_addstring_start();
1519 for (i = 0; i < lenof(kex_algs); i++) {
1520 ssh2_pkt_addstring_str(kex_algs[i]->name);
1521 if (i < lenof(kex_algs)-1)
1522 ssh2_pkt_addstring_str(",");
1523 }
1524 /* List server host key algorithms. */
1525 ssh2_pkt_addstring_start();
1526 for (i = 0; i < lenof(hostkey_algs); i++) {
1527 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1528 if (i < lenof(hostkey_algs)-1)
1529 ssh2_pkt_addstring_str(",");
1530 }
1531 /* List client->server encryption algorithms. */
1532 ssh2_pkt_addstring_start();
1533 for (i = 0; i < lenof(ciphers); i++) {
1534 ssh2_pkt_addstring_str(ciphers[i]->name);
1535 if (i < lenof(ciphers)-1)
1536 ssh2_pkt_addstring_str(",");
1537 }
1538 /* List server->client encryption algorithms. */
1539 ssh2_pkt_addstring_start();
1540 for (i = 0; i < lenof(ciphers); i++) {
1541 ssh2_pkt_addstring_str(ciphers[i]->name);
1542 if (i < lenof(ciphers)-1)
1543 ssh2_pkt_addstring_str(",");
1544 }
1545 /* List client->server MAC algorithms. */
1546 ssh2_pkt_addstring_start();
1547 for (i = 0; i < lenof(macs); i++) {
1548 ssh2_pkt_addstring_str(macs[i]->name);
1549 if (i < lenof(macs)-1)
1550 ssh2_pkt_addstring_str(",");
1551 }
1552 /* List server->client MAC algorithms. */
1553 ssh2_pkt_addstring_start();
1554 for (i = 0; i < lenof(macs); i++) {
1555 ssh2_pkt_addstring_str(macs[i]->name);
1556 if (i < lenof(macs)-1)
1557 ssh2_pkt_addstring_str(",");
1558 }
1559 /* List client->server compression algorithms. */
1560 ssh2_pkt_addstring_start();
1561 for (i = 0; i < lenof(compressions); i++) {
1562 ssh2_pkt_addstring_str(compressions[i]->name);
1563 if (i < lenof(compressions)-1)
1564 ssh2_pkt_addstring_str(",");
1565 }
1566 /* List server->client compression algorithms. */
1567 ssh2_pkt_addstring_start();
1568 for (i = 0; i < lenof(compressions); i++) {
1569 ssh2_pkt_addstring_str(compressions[i]->name);
1570 if (i < lenof(compressions)-1)
1571 ssh2_pkt_addstring_str(",");
1572 }
1573 /* List client->server languages. Empty list. */
1574 ssh2_pkt_addstring_start();
1575 /* List server->client languages. Empty list. */
1576 ssh2_pkt_addstring_start();
1577 /* First KEX packet does _not_ follow, because we're not that brave. */
1578 ssh2_pkt_addbool(FALSE);
1579 /* Reserved. */
1580 ssh2_pkt_adduint32(0);
1581 sha_string(&exhash, pktout.data+5, pktout.length-5);
1582 ssh2_pkt_send();
1583
1584 if (!ispkt) crWaitUntil(ispkt);
1585 sha_string(&exhash, pktin.data+5, pktin.length-5);
1586
1587 /*
1588 * Now examine the other side's KEXINIT to see what we're up
1589 * to.
1590 */
7cca0d81 1591 if (pktin.type != SSH2_MSG_KEXINIT) {
e5574168 1592 fatalbox("expected key exchange packet from server");
7cca0d81 1593 }
e5574168 1594 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1595 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1596 pktin.savedpos += 16; /* skip garbage cookie */
1597 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
1598 for (i = 0; i < lenof(kex_algs); i++) {
1599 if (in_commasep_string(kex_algs[i]->name, str, len)) {
1600 kex = kex_algs[i];
1601 break;
1602 }
1603 }
1604 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
1605 for (i = 0; i < lenof(hostkey_algs); i++) {
1606 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1607 hostkey = hostkey_algs[i];
1608 break;
1609 }
1610 }
1611 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
1612 for (i = 0; i < lenof(ciphers); i++) {
1613 if (in_commasep_string(ciphers[i]->name, str, len)) {
1614 cscipher_tobe = ciphers[i];
1615 break;
1616 }
1617 }
1618 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
1619 for (i = 0; i < lenof(ciphers); i++) {
1620 if (in_commasep_string(ciphers[i]->name, str, len)) {
1621 sccipher_tobe = ciphers[i];
1622 break;
1623 }
1624 }
1625 ssh2_pkt_getstring(&str, &len); /* client->server mac */
1626 for (i = 0; i < lenof(macs); i++) {
1627 if (in_commasep_string(macs[i]->name, str, len)) {
1628 csmac_tobe = macs[i];
1629 break;
1630 }
1631 }
1632 ssh2_pkt_getstring(&str, &len); /* server->client mac */
1633 for (i = 0; i < lenof(macs); i++) {
1634 if (in_commasep_string(macs[i]->name, str, len)) {
1635 scmac_tobe = macs[i];
1636 break;
1637 }
1638 }
1639 ssh2_pkt_getstring(&str, &len); /* client->server compression */
1640 for (i = 0; i < lenof(compressions); i++) {
1641 if (in_commasep_string(compressions[i]->name, str, len)) {
1642 cscomp_tobe = compressions[i];
1643 break;
1644 }
1645 }
1646 ssh2_pkt_getstring(&str, &len); /* server->client compression */
1647 for (i = 0; i < lenof(compressions); i++) {
1648 if (in_commasep_string(compressions[i]->name, str, len)) {
1649 sccomp_tobe = compressions[i];
1650 break;
1651 }
1652 }
e5574168 1653
1654 /*
1655 * Currently we only support Diffie-Hellman and DSS, so let's
1656 * bomb out if those aren't selected.
1657 */
1658 if (kex != &ssh_diffiehellman || hostkey != &ssh_dss)
1659 fatalbox("internal fault: chaos in SSH 2 transport layer");
1660
1661 /*
1662 * Now we begin the fun. Generate and send e for Diffie-Hellman.
1663 */
1664 e = dh_create_e();
e5574168 1665 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
1666 ssh2_pkt_addmp(e);
1667 ssh2_pkt_send();
1668
1669 crWaitUntil(ispkt);
7cca0d81 1670 if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
e5574168 1671 fatalbox("expected key exchange packet from server");
7cca0d81 1672 }
e5574168 1673 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
1674 f = ssh2_pkt_getmp();
e5574168 1675 ssh2_pkt_getstring(&sigdata, &siglen);
1676
1677 K = dh_find_K(f);
e5574168 1678
1679 sha_string(&exhash, hostkeydata, hostkeylen);
1680 sha_mpint(&exhash, e);
1681 sha_mpint(&exhash, f);
1682 sha_mpint(&exhash, K);
1683 SHA_Final(&exhash, exchange_hash);
1684
7cca0d81 1685#if 0
e5574168 1686 debug(("Exchange hash is:\r\n"));
1687 for (i = 0; i < 20; i++)
1688 debug((" %02x", exchange_hash[i]));
1689 debug(("\r\n"));
7cca0d81 1690#endif
1691
1692 hostkey->setkey(hostkeydata, hostkeylen);
1693 if (!hostkey->verifysig(sigdata, siglen, exchange_hash, 20))
1694 fatalbox("Server failed host key check");
e5574168 1695
1696 /*
7cca0d81 1697 * Expect SSH2_MSG_NEWKEYS from server.
d39f364a 1698 */
7cca0d81 1699 crWaitUntil(ispkt);
1700 if (pktin.type != SSH2_MSG_NEWKEYS)
1701 fatalbox("expected new-keys packet from server");
d39f364a 1702
1703 /*
7cca0d81 1704 * Authenticate remote host: verify host key. (We've already
1705 * checked the signature of the exchange hash.)
e5574168 1706 */
7cca0d81 1707 keystr = hostkey->fmtkey();
1708 verify_ssh_host_key(savedhost, keystr);
1709 free(keystr);
d39f364a 1710
1711 /*
7cca0d81 1712 * Send SSH2_MSG_NEWKEYS.
d39f364a 1713 */
1714 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
1715 ssh2_pkt_send();
d39f364a 1716
1717 /*
1718 * Create and initialise session keys.
1719 */
1720 cscipher = cscipher_tobe;
1721 sccipher = sccipher_tobe;
1722 csmac = csmac_tobe;
1723 scmac = scmac_tobe;
1724 cscomp = cscomp_tobe;
1725 sccomp = sccomp_tobe;
1726 /*
1727 * Set IVs after keys.
1728 */
1729 ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
1730 ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
1731 ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
1732 ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
1733 ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
1734 ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
1735
033b4cef 1736 /*
7cca0d81 1737 * Now we're encrypting. Begin returning 1 to the protocol main
1738 * function so that other things can run on top of the
1739 * transport. If we ever see a KEXINIT, we must go back to the
1740 * start.
033b4cef 1741 */
7cca0d81 1742 do {
1743 crReturn(1);
1744 } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
1745 goto begin_key_exchange;
e5574168 1746
1747 crFinish(1);
1748}
1749
7cca0d81 1750/*
6abbf9e3 1751 * SSH2: remote identifier for the main session channel.
1752 */
1753static unsigned long ssh_remote_channel;
1754
1755/*
7cca0d81 1756 * Handle the SSH2 userauth and connection layers.
1757 */
1758static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
1759{
7cca0d81 1760 static unsigned long remote_winsize;
1761 static unsigned long remote_maxpkt;
1762
e5574168 1763 crBegin;
1764
7cca0d81 1765 /*
1766 * Request userauth protocol, and await a response to it.
1767 */
1768 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
1769 ssh2_pkt_addstring("ssh-userauth");
1770 ssh2_pkt_send();
1771 crWaitUntilV(ispkt);
1772 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT)
1773 fatalbox("Server refused user authentication protocol");
1774
1775 /*
1776 * FIXME: currently we support only password authentication.
1777 * (This places us technically in violation of the SSH2 spec.
1778 * We must fix this.)
1779 */
1780 while (1) {
1781 /*
1782 * Get a username and a password.
1783 */
1784 static char username[100];
1785 static char password[100];
1786 static int pos = 0;
1787 static char c;
e5574168 1788
4017be6d 1789 if ((flags & FLAG_CONNECTION) && !*cfg.username) {
7cca0d81 1790 c_write("login as: ", 10);
1791 while (pos >= 0) {
1792 crWaitUntilV(!ispkt);
1793 while (inlen--) switch (c = *in++) {
1794 case 10: case 13:
1795 username[pos] = 0;
1796 pos = -1;
1797 break;
1798 case 8: case 127:
1799 if (pos > 0) {
1800 c_write("\b \b", 3);
1801 pos--;
1802 }
1803 break;
1804 case 21: case 27:
1805 while (pos > 0) {
1806 c_write("\b \b", 3);
1807 pos--;
1808 }
1809 break;
1810 case 3: case 4:
1811 random_save_seed();
1812 exit(0);
1813 break;
1814 default:
1815 if (((c >= ' ' && c <= '~') ||
1816 ((unsigned char)c >= 160)) && pos < 40) {
1817 username[pos++] = c;
1818 c_write(&c, 1);
1819 }
1820 break;
1821 }
1822 }
1823 c_write("\r\n", 2);
1824 username[strcspn(username, "\n\r")] = '\0';
1825 } else {
1826 char stuff[200];
1827 strncpy(username, cfg.username, 99);
1828 username[99] = '\0';
4017be6d 1829 if (flags & FLAG_VERBOSE) {
7cca0d81 1830 sprintf(stuff, "Using username \"%s\".\r\n", username);
1831 c_write(stuff, strlen(stuff));
1832 }
1833 }
1834
4017be6d 1835 if (!(flags & FLAG_WINDOWED)) {
7cca0d81 1836 char prompt[200];
1837 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
1838 if (!ssh_get_password(prompt, password, sizeof(password))) {
1839 /*
1840 * get_password failed to get a password (for
1841 * example because one was supplied on the command
1842 * line which has already failed to work).
1843 * Terminate.
1844 */
1845 logevent("No more passwords to try");
1846 ssh_state = SSH_STATE_CLOSED;
1847 crReturnV;
1848 }
1849 } else {
1850 c_write("password: ", 10);
1851
1852 pos = 0;
1853 while (pos >= 0) {
1854 crWaitUntilV(!ispkt);
1855 while (inlen--) switch (c = *in++) {
1856 case 10: case 13:
1857 password[pos] = 0;
1858 pos = -1;
1859 break;
1860 case 8: case 127:
1861 if (pos > 0)
1862 pos--;
1863 break;
1864 case 21: case 27:
1865 pos = 0;
1866 break;
1867 case 3: case 4:
1868 random_save_seed();
1869 exit(0);
1870 break;
1871 default:
1872 if (((c >= ' ' && c <= '~') ||
1873 ((unsigned char)c >= 160)) && pos < 40)
1874 password[pos++] = c;
1875 break;
1876 }
1877 }
1878 c_write("\r\n", 2);
1879 }
1880
1881 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
1882 ssh2_pkt_addstring(username);
1883 ssh2_pkt_addstring("ssh-connection"); /* service requested */
1884 ssh2_pkt_addstring("password");
1885 ssh2_pkt_addbool(FALSE);
1886 ssh2_pkt_addstring(password);
1887 ssh2_pkt_send();
1888
1889 crWaitUntilV(ispkt);
1890 if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
1891 c_write("Access denied\r\n", 15);
1892 logevent("Authentication refused");
1893 } else
1894 break;
1895 }
1896
1897 /*
1898 * Now we're authenticated for the connection protocol. The
1899 * connection protocol will automatically have started at this
1900 * point; there's no need to send SERVICE_REQUEST.
1901 */
1902
1903 /*
1904 * So now create a channel with a session in it.
1905 */
1906 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
1907 ssh2_pkt_addstring("session");
1908 ssh2_pkt_adduint32(100); /* as good as any */
1909 ssh2_pkt_adduint32(0xFFFFFFFFUL); /* very big window which we ignore */
1910 ssh2_pkt_adduint32(0xFFFFFFFFUL); /* very big max pkt size */
1911 ssh2_pkt_send();
1912 crWaitUntilV(ispkt);
1913 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
1914 fatalbox("Server refused to open a session");
1915 /* FIXME: error data comes back in FAILURE packet */
1916 }
1917 if (ssh2_pkt_getuint32() != 100) {
1918 fatalbox("Server's channel confirmation cited wrong channel");
1919 }
6abbf9e3 1920 ssh_remote_channel = ssh2_pkt_getuint32();
7cca0d81 1921 remote_winsize = ssh2_pkt_getuint32();
1922 remote_maxpkt = ssh2_pkt_getuint32();
1923 logevent("Opened channel for session");
1924
1925 /*
1926 * Now allocate a pty for the session.
1927 */
1928 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6abbf9e3 1929 ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
7cca0d81 1930 ssh2_pkt_addstring("pty-req");
1931 ssh2_pkt_addbool(1); /* want reply */
1932 ssh2_pkt_addstring(cfg.termtype);
1933 ssh2_pkt_adduint32(cols);
1934 ssh2_pkt_adduint32(rows);
1935 ssh2_pkt_adduint32(0); /* pixel width */
1936 ssh2_pkt_adduint32(0); /* pixel height */
1937 ssh2_pkt_addstring_start();
1938 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
1939 ssh2_pkt_send();
1940
1941 do { /* FIXME: pay attention to these */
1942 crWaitUntilV(ispkt);
1943 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1944
1945 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
1946 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
1947 fatalbox("Server got confused by pty request");
1948 }
1949 c_write("Server refused to allocate pty\r\n", 32);
1950 } else {
1951 logevent("Allocated pty");
1952 }
1953
1954 /*
1955 * Start a shell.
1956 */
1957 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6abbf9e3 1958 ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
7cca0d81 1959 ssh2_pkt_addstring("shell");
1960 ssh2_pkt_addbool(1); /* want reply */
1961 ssh2_pkt_send();
1962 do { /* FIXME: pay attention to these */
1963 crWaitUntilV(ispkt);
1964 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1965 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
1966 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
1967 fatalbox("Server got confused by shell request");
1968 }
1969 fatalbox("Server refused to start a shell");
1970 } else {
1971 logevent("Started a shell");
1972 }
1973
1974 /*
1975 * Transfer data!
1976 */
8ccc75b0 1977 ssh_send_ok = 1;
7cca0d81 1978 while (1) {
e5574168 1979 crReturnV;
7cca0d81 1980 if (ispkt) {
1981 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
1982 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1983 char *data;
1984 int length;
1985 if (ssh2_pkt_getuint32() != 100)
1986 continue; /* wrong channel */
1987 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
1988 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
1989 continue; /* extended but not stderr */
1990 ssh2_pkt_getstring(&data, &length);
1991 if (data)
1992 c_write(data, length);
1993 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
1994 ssh_state = SSH_STATE_CLOSED;
1995 logevent("Received disconnect request");
1996 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
1997 continue; /* exit status et al; ignore (FIXME?) */
1998 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
1999 continue; /* ignore for now (FIXME!) */
2000 } else {
2001 fatalbox("Strange packet received: type %d", pktin.type);
2002 }
2003 } else {
2004 /* FIXME: for now, ignore window size */
2005 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6abbf9e3 2006 ssh2_pkt_adduint32(ssh_remote_channel);
7cca0d81 2007 ssh2_pkt_addstring_start();
2008 ssh2_pkt_addstring_data(in, inlen);
2009 ssh2_pkt_send();
2010 }
e5574168 2011 }
2012
2013 crFinishV;
2014}
2015
2016/*
7cca0d81 2017 * Handle the top-level SSH2 protocol.
2018 */
2019static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2020{
2021 if (do_ssh2_transport(in, inlen, ispkt) == 0)
2022 return;
2023 do_ssh2_authconn(in, inlen, ispkt);
2024}
2025
2026/*
374330e2 2027 * Called to set up the connection. Will arrange for WM_NETEVENT
2028 * messages to be passed to the specified window, whose window
2029 * procedure should then call telnet_msg().
2030 *
2031 * Returns an error message, or NULL on success.
374330e2 2032 */
2033static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
fb09bf1c 2034 char *p;
8f203108 2035
2036#ifdef MSCRYPTOAPI
2037 if(crypto_startup() == 0)
2038 return "Microsoft high encryption pack not installed!";
2039#endif
374330e2 2040
fb09bf1c 2041 p = connect_to_host(host, port, realhost);
2042 if (p != NULL)
2043 return p;
374330e2 2044
2045 if (!do_ssh_init())
2046 return "Protocol initialisation error";
2047
4017be6d 2048 if (hwnd && WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
374330e2 2049 switch (WSAGetLastError()) {
2050 case WSAENETDOWN: return "Network is down";
2051 default: return "WSAAsyncSelect(): unknown error";
2052 }
2053
2054 return NULL;
2055}
2056
2057/*
2058 * Process a WM_NETEVENT message. Will return 0 if the connection
2059 * has closed, or <0 for a socket error.
2060 */
2061static int ssh_msg (WPARAM wParam, LPARAM lParam) {
2062 int ret;
2063 char buf[256];
2064
8ce72d2c 2065 /*
2066 * Because reading less than the whole of the available pending
2067 * data can generate an FD_READ event, we need to allow for the
2068 * possibility that FD_READ may arrive with FD_CLOSE already in
2069 * the queue; so it's possible that we can get here even with s
2070 * invalid. If so, we return 1 and don't worry about it.
2071 */
2072 if (s == INVALID_SOCKET)
2073 return 1;
374330e2 2074
2075 if (WSAGETSELECTERROR(lParam) != 0)
2076 return -WSAGETSELECTERROR(lParam);
2077
2078 switch (WSAGETSELECTEVENT(lParam)) {
2079 case FD_READ:
8ce72d2c 2080 case FD_CLOSE:
374330e2 2081 ret = recv(s, buf, sizeof(buf), 0);
2082 if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
2083 return 1;
2084 if (ret < 0) /* any _other_ error */
2085 return -10000-WSAGetLastError();
2086 if (ret == 0) {
2087 s = INVALID_SOCKET;
8ce72d2c 2088 return 0;
374330e2 2089 }
2090 ssh_gotdata (buf, ret);
85ee8208 2091 if (ssh_state == SSH_STATE_CLOSED) {
2092 closesocket(s);
2093 s = INVALID_SOCKET;
2094 return 0;
2095 }
374330e2 2096 return 1;
374330e2 2097 }
2098 return 1; /* shouldn't happen, but WTF */
2099}
2100
2101/*
2102 * Called to send data down the Telnet connection.
2103 */
2104static void ssh_send (char *buf, int len) {
2105 if (s == INVALID_SOCKET)
2106 return;
2107
2108 ssh_protocol(buf, len, 0);
2109}
2110
2111/*
2112 * Called to set the size of the window from Telnet's POV.
2113 */
2114static void ssh_size(void) {
2115 switch (ssh_state) {
2116 case SSH_STATE_BEFORE_SIZE:
21248260 2117 case SSH_STATE_CLOSED:
374330e2 2118 break; /* do nothing */
2119 case SSH_STATE_INTERMED:
2120 size_needed = TRUE; /* buffer for later */
2121 break;
2122 case SSH_STATE_SESSION:
fef97f43 2123 if (!cfg.nopty) {
e5574168 2124 send_packet(SSH1_CMSG_WINDOW_SIZE,
fb09bf1c 2125 PKT_INT, rows, PKT_INT, cols,
2126 PKT_INT, 0, PKT_INT, 0, PKT_END);
fef97f43 2127 }
374330e2 2128 }
2129}
2130
2131/*
6abbf9e3 2132 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2133 * can send an EOF and collect resulting output (e.g. `plink
2134 * hostname sort').
374330e2 2135 */
2136static void ssh_special (Telnet_Special code) {
6abbf9e3 2137 if (code == TS_EOF) {
2138 if (ssh_version = 1) {
2139 send_packet(SSH1_CMSG_EOF, PKT_END);
2140 } else {
2141 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
2142 ssh2_pkt_adduint32(ssh_remote_channel);
2143 ssh2_pkt_send();
2144 }
2145 } else {
2146 /* do nothing */
2147 }
374330e2 2148}
2149
fb09bf1c 2150
2151/*
2152 * Read and decrypt one incoming SSH packet.
2153 * (only used by pSCP)
2154 */
2155static void get_packet(void)
2156{
2157 unsigned char buf[4096], *p;
2158 long to_read;
2159 int len;
2160
fb09bf1c 2161 p = NULL;
2162 len = 0;
2163
2164 while ((to_read = s_rdpkt(&p, &len)) > 0) {
2165 if (to_read > sizeof(buf)) to_read = sizeof(buf);
2166 len = s_read(buf, to_read);
2167 if (len != to_read) {
2168 closesocket(s);
2169 s = INVALID_SOCKET;
2170 return;
2171 }
2172 p = buf;
2173 }
2174
2175 assert(len == 0);
2176}
2177
2178/*
2179 * Receive a block of data over the SSH link. Block until
2180 * all data is available. Return nr of bytes read (0 if lost connection).
2181 * (only used by pSCP)
2182 */
2183int ssh_scp_recv(unsigned char *buf, int len)
2184{
2185 static int pending_input_len = 0;
2186 static unsigned char *pending_input_ptr;
2187 int to_read = len;
2188
fb09bf1c 2189 if (pending_input_len >= to_read) {
2190 memcpy(buf, pending_input_ptr, to_read);
2191 pending_input_ptr += to_read;
2192 pending_input_len -= to_read;
2193 return len;
2194 }
2195
2196 if (pending_input_len > 0) {
2197 memcpy(buf, pending_input_ptr, pending_input_len);
2198 buf += pending_input_len;
2199 to_read -= pending_input_len;
2200 pending_input_len = 0;
2201 }
2202
2203 if (s == INVALID_SOCKET)
2204 return 0;
2205 while (to_read > 0) {
2206 get_packet();
2207 if (s == INVALID_SOCKET)
2208 return 0;
e5574168 2209 if (pktin.type == SSH1_SMSG_STDOUT_DATA) {
fb09bf1c 2210 int plen = GET_32BIT(pktin.body);
2211 if (plen <= to_read) {
2212 memcpy(buf, pktin.body + 4, plen);
2213 buf += plen;
2214 to_read -= plen;
2215 } else {
2216 memcpy(buf, pktin.body + 4, to_read);
2217 pending_input_len = plen - to_read;
2218 pending_input_ptr = pktin.body + 4 + to_read;
2219 to_read = 0;
2220 }
e5574168 2221 } else if (pktin.type == SSH1_SMSG_STDERR_DATA) {
fb09bf1c 2222 int plen = GET_32BIT(pktin.body);
2223 fwrite(pktin.body + 4, plen, 1, stderr);
e5574168 2224 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
fb09bf1c 2225 logevent("Received disconnect request");
e5574168 2226 } else if (pktin.type == SSH1_SMSG_SUCCESS ||
2227 pktin.type == SSH1_SMSG_FAILURE) {
fb09bf1c 2228 /* ignore */
e5574168 2229 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
fb09bf1c 2230 char logbuf[100];
2231 sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
2232 logevent(logbuf);
e5574168 2233 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
fb09bf1c 2234 logevent("Closing connection");
2235 closesocket(s);
2236 s = INVALID_SOCKET;
2237 } else {
2238 fatalbox("Strange packet received: type %d", pktin.type);
2239 }
2240 }
2241
2242 return len;
2243}
2244
2245/*
2246 * Send a block of data over the SSH link.
2247 * Block until all data is sent.
2248 * (only used by pSCP)
2249 */
2250void ssh_scp_send(unsigned char *buf, int len)
2251{
fb09bf1c 2252 if (s == INVALID_SOCKET)
2253 return;
e5574168 2254 send_packet(SSH1_CMSG_STDIN_DATA,
fb09bf1c 2255 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2256}
2257
2258/*
2259 * Send an EOF notification to the server.
2260 * (only used by pSCP)
2261 */
2262void ssh_scp_send_eof(void)
2263{
fb09bf1c 2264 if (s == INVALID_SOCKET)
2265 return;
e5574168 2266 send_packet(SSH1_CMSG_EOF, PKT_END);
fb09bf1c 2267}
2268
2269/*
2270 * Set up the connection, login on the remote host and
2271 * start execution of a command.
2272 * Returns an error message, or NULL on success.
2273 * (only used by pSCP)
2274 */
2275char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
2276{
2277 char buf[160], *p;
2278
fb09bf1c 2279#ifdef MSCRYPTOAPI
2280 if (crypto_startup() == 0)
2281 return "Microsoft high encryption pack not installed!";
2282#endif
2283
2284 p = connect_to_host(host, port, realhost);
2285 if (p != NULL)
2286 return p;
2287
2288 random_init();
2289
2290 if (!do_ssh_init())
2291 return "Protocol initialisation error";
2292
2293 /* Exchange keys and login */
2294 do {
2295 get_packet();
2296 if (s == INVALID_SOCKET)
2297 return "Connection closed by remote host";
e5574168 2298 } while (!do_ssh1_login(NULL, 0, 1));
85ee8208 2299
2300 if (ssh_state == SSH_STATE_CLOSED) {
2301 closesocket(s);
2302 s = INVALID_SOCKET;
2303 return "Session initialisation error";
2304 }
fb09bf1c 2305
2306 /* Execute command */
2307 sprintf(buf, "Sending command: %.100s", cmd);
2308 logevent(buf);
e5574168 2309 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
fb09bf1c 2310
2311 return NULL;
2312}
2313
8ccc75b0 2314static SOCKET ssh_socket(void) { return s; }
2315
2316static int ssh_sendok(void) { return ssh_send_ok; }
fb09bf1c 2317
374330e2 2318Backend ssh_backend = {
2319 ssh_init,
2320 ssh_msg,
2321 ssh_send,
2322 ssh_size,
4017be6d 2323 ssh_special,
8ccc75b0 2324 ssh_socket,
2325 ssh_sendok
374330e2 2326};