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