Ensure backend netevent handlers are never reentered -
[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 */
59dcd2a8 457 if (pktin.maxlen < packetlen+maclen) {
458 pktin.maxlen = packetlen+maclen;
459 pktin.data = (pktin.data == NULL ? malloc(pktin.maxlen+APIEXTRA) :
460 realloc(pktin.data, pktin.maxlen+APIEXTRA));
e5574168 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;
b8bb811a 1269 static char *commentp;
1270 static int commentlen;
5c58ad2d 1271
1272 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1273 logevent(buf); }
1274 p += 4;
1275 p += ssh1_read_bignum(p, &key.exponent);
1276 p += ssh1_read_bignum(p, &key.modulus);
b8bb811a 1277 commentlen = GET_32BIT(p); p += 4;
1278 commentp = p; p += commentlen;
5c58ad2d 1279 send_packet(SSH1_CMSG_AUTH_RSA,
1280 PKT_BIGNUM, key.modulus, PKT_END);
1281 crWaitUntil(ispkt);
1282 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1283 logevent("Key refused");
1284 continue;
1285 }
1286 logevent("Received RSA challenge");
1287 ssh1_read_bignum(pktin.body, &challenge);
1288 {
1289 char *agentreq, *q, *ret;
1290 int len, retlen;
1291 len = 1 + 4; /* message type, bit count */
1292 len += ssh1_bignum_length(key.exponent);
1293 len += ssh1_bignum_length(key.modulus);
1294 len += ssh1_bignum_length(challenge);
1295 len += 16; /* session id */
1296 len += 4; /* response format */
1297 agentreq = malloc(4 + len);
1298 PUT_32BIT(agentreq, len);
1299 q = agentreq + 4;
1300 *q++ = SSH_AGENTC_RSA_CHALLENGE;
1301 PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1302 q += 4;
1303 q += ssh1_write_bignum(q, key.exponent);
1304 q += ssh1_write_bignum(q, key.modulus);
1305 q += ssh1_write_bignum(q, challenge);
1306 memcpy(q, session_id, 16); q += 16;
1307 PUT_32BIT(q, 1); /* response format */
1308 agent_query(agentreq, len+4, &ret, &retlen);
1309 free(agentreq);
1310 if (ret) {
1311 if (ret[4] == SSH_AGENT_RSA_RESPONSE) {
1312 logevent("Sending Pageant's response");
1313 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1314 PKT_DATA, ret+5, 16, PKT_END);
1315 free(ret);
1316 crWaitUntil(ispkt);
1317 if (pktin.type == SSH1_SMSG_SUCCESS) {
1318 logevent("Pageant's response accepted");
b8bb811a 1319 c_write("Authenticated using RSA key \"",
1320 29);
1321 c_write(commentp, commentlen);
1322 c_write("\" from agent\r\n", 14);
5c58ad2d 1323 authed = TRUE;
1324 } else
1325 logevent("Pageant's response not accepted");
1326 } else {
1327 logevent("Pageant failed to answer challenge");
1328 free(ret);
1329 }
1330 } else {
1331 logevent("No reply received from Pageant");
1332 }
1333 }
1334 freebn(key.exponent);
1335 freebn(key.modulus);
1336 freebn(challenge);
1337 if (authed)
1338 break;
1339 }
1340 }
1341 if (authed)
1342 break;
1343 }
7cca0d81 1344 if (*cfg.keyfile && !tried_publickey)
1345 pwpkt_type = SSH1_CMSG_AUTH_RSA;
fb09bf1c 1346
4017be6d 1347 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD && !FLAG_WINDOWED) {
fb09bf1c 1348 char prompt[200];
1349 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
85ee8208 1350 if (!ssh_get_password(prompt, password, sizeof(password))) {
1351 /*
1352 * get_password failed to get a password (for
1353 * example because one was supplied on the command
1354 * line which has already failed to work).
1355 * Terminate.
1356 */
1357 logevent("No more passwords to try");
1358 ssh_state = SSH_STATE_CLOSED;
1359 crReturn(1);
1360 }
fb09bf1c 1361 } else {
1362
7cca0d81 1363 if (pktin.type == SSH1_SMSG_FAILURE &&
1364 cfg.try_tis_auth &&
1365 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1366 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1367 logevent("Requested TIS authentication");
1368 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1369 crWaitUntil(ispkt);
1370 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1371 logevent("TIS authentication declined");
1372 c_write("TIS authentication refused.\r\n", 29);
1373 } else {
1374 int challengelen = ((pktin.body[0] << 24) |
1375 (pktin.body[1] << 16) |
1376 (pktin.body[2] << 8) |
1377 (pktin.body[3]));
1378 logevent("Received TIS challenge");
1379 c_write(pktin.body+4, challengelen);
1380 }
1381 }
18515c51 1382 if (pktin.type == SSH1_SMSG_FAILURE &&
1383 cfg.try_tis_auth &&
1384 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1385 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1386 logevent("Requested CryptoCard authentication");
1387 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1388 crWaitUntil(ispkt);
1389 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1390 logevent("CryptoCard authentication declined");
1391 c_write("CryptoCard authentication refused.\r\n", 29);
1392 } else {
1393 int challengelen = ((pktin.body[0] << 24) |
1394 (pktin.body[1] << 16) |
1395 (pktin.body[2] << 8) |
1396 (pktin.body[3]));
1397 logevent("Received CryptoCard challenge");
1398 c_write(pktin.body+4, challengelen);
1399 c_write("\r\nResponse : ", 13);
1400 }
1401 }
7cca0d81 1402 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD)
1403 c_write("password: ", 10);
1404 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
4017be6d 1405 if (flags & FLAG_VERBOSE)
1406 c_write("Trying public key authentication.\r\n", 35);
7cca0d81 1407 if (!rsakey_encrypted(cfg.keyfile)) {
4017be6d 1408 if (flags & FLAG_VERBOSE)
1409 c_write("No passphrase required.\r\n", 25);
7cca0d81 1410 goto tryauth;
1411 }
1412 c_write("passphrase: ", 12);
ccbfb941 1413 }
ccbfb941 1414
7cca0d81 1415 pos = 0;
1416 while (pos >= 0) {
1417 crWaitUntil(!ispkt);
1418 while (inlen--) switch (c = *in++) {
1419 case 10: case 13:
1420 password[pos] = 0;
1421 pos = -1;
1422 break;
1423 case 8: case 127:
1424 if (pos > 0)
1425 pos--;
1426 break;
1427 case 21: case 27:
1428 pos = 0;
1429 break;
1430 case 3: case 4:
1431 random_save_seed();
1432 exit(0);
1433 break;
1434 default:
1435 if (((c >= ' ' && c <= '~') ||
1436 ((unsigned char)c >= 160)) && pos < sizeof(password))
1437 password[pos++] = c;
1438 break;
1439 }
1440 }
1441 c_write("\r\n", 2);
fb09bf1c 1442
1443 }
1444
7cca0d81 1445 tryauth:
1446 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1447 /*
1448 * Try public key authentication with the specified
1449 * key file.
1450 */
1451 static struct RSAKey pubkey;
1452 static Bignum challenge, response;
1453 static int i;
1454 static unsigned char buffer[32];
1455
1456 tried_publickey = 1;
1457 i = loadrsakey(cfg.keyfile, &pubkey, password);
1458 if (i == 0) {
1459 c_write("Couldn't load public key from ", 30);
1460 c_write(cfg.keyfile, strlen(cfg.keyfile));
1461 c_write(".\r\n", 3);
1462 continue; /* go and try password */
1463 }
1464 if (i == -1) {
1465 c_write("Wrong passphrase.\r\n", 19);
1466 tried_publickey = 0;
1467 continue; /* try again */
1468 }
1469
1470 /*
1471 * Send a public key attempt.
1472 */
1473 send_packet(SSH1_CMSG_AUTH_RSA,
1474 PKT_BIGNUM, pubkey.modulus, PKT_END);
1475
1476 crWaitUntil(ispkt);
1477 if (pktin.type == SSH1_SMSG_FAILURE) {
4017be6d 1478 if (flags & FLAG_VERBOSE)
1479 c_write("Server refused our public key.\r\n", 32);
7cca0d81 1480 continue; /* go and try password */
1481 }
1482 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE)
1483 fatalbox("Bizarre response to offer of public key");
1484 ssh1_read_bignum(pktin.body, &challenge);
1485 response = rsadecrypt(challenge, &pubkey);
1486 freebn(pubkey.private_exponent); /* burn the evidence */
1487
1488 for (i = 0; i < 32; i += 2) {
1489 buffer[i] = response[16-i/2] >> 8;
1490 buffer[i+1] = response[16-i/2] & 0xFF;
1491 }
1492
1493 MD5Init(&md5c);
1494 MD5Update(&md5c, buffer, 32);
1495 MD5Update(&md5c, session_id, 16);
1496 MD5Final(buffer, &md5c);
1497
1498 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1499 PKT_DATA, buffer, 16, PKT_END);
1500
1501 crWaitUntil(ispkt);
1502 if (pktin.type == SSH1_SMSG_FAILURE) {
4017be6d 1503 if (flags & FLAG_VERBOSE)
1504 c_write("Failed to authenticate with our public key.\r\n",
1505 45);
7cca0d81 1506 continue; /* go and try password */
1507 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1508 fatalbox("Bizarre response to RSA authentication response");
1509 }
1510
1511 break; /* we're through! */
1512 } else {
1513 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1514 }
c5e9c988 1515 logevent("Sent password");
374330e2 1516 memset(password, 0, strlen(password));
fb09bf1c 1517 crWaitUntil(ispkt);
e5574168 1518 if (pktin.type == SSH1_SMSG_FAILURE) {
4017be6d 1519 if (flags & FLAG_VERBOSE)
1520 c_write("Access denied\r\n", 15);
c5e9c988 1521 logevent("Authentication refused");
e5574168 1522 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
fb09bf1c 1523 logevent("Received disconnect request");
85ee8208 1524 ssh_state = SSH_STATE_CLOSED;
1525 crReturn(1);
e5574168 1526 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
374330e2 1527 fatalbox("Strange packet received, type %d", pktin.type);
1528 }
1529 }
1530
c5e9c988 1531 logevent("Authentication successful");
1532
fb09bf1c 1533 crFinish(1);
1534}
1535
e5574168 1536static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
fb09bf1c 1537 crBegin;
1538
1539 random_init();
1540
e5574168 1541 while (!do_ssh1_login(in, inlen, ispkt)) {
fb09bf1c 1542 crReturnV;
85ee8208 1543 }
1544 if (ssh_state == SSH_STATE_CLOSED)
1545 crReturnV;
fb09bf1c 1546
979310f1 1547 if (cfg.agentfwd && agent_exists()) {
dacbd0e8 1548 logevent("Requesting agent forwarding");
1549 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1550 do { crReturnV; } while (!ispkt);
1551 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1552 fatalbox("Protocol confusion");
1553 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1554 logevent("Agent forwarding refused");
1555 } else
1556 logevent("Agent forwarding enabled");
1557 }
1558
fef97f43 1559 if (!cfg.nopty) {
e5574168 1560 send_packet(SSH1_CMSG_REQUEST_PTY,
fb09bf1c 1561 PKT_STR, cfg.termtype,
1562 PKT_INT, rows, PKT_INT, cols,
1563 PKT_INT, 0, PKT_INT, 0,
1564 PKT_CHAR, 0,
1565 PKT_END);
fef97f43 1566 ssh_state = SSH_STATE_INTERMED;
1567 do { crReturnV; } while (!ispkt);
e5574168 1568 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
fef97f43 1569 fatalbox("Protocol confusion");
e5574168 1570 } else if (pktin.type == SSH1_SMSG_FAILURE) {
fef97f43 1571 c_write("Server refused to allocate pty\r\n", 32);
1572 }
c5e9c988 1573 logevent("Allocated pty");
374330e2 1574 }
1575
6abbf9e3 1576 if (*cfg.remote_cmd)
1577 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1578 else
1579 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
c5e9c988 1580 logevent("Started session");
374330e2 1581
1582 ssh_state = SSH_STATE_SESSION;
1583 if (size_needed)
1584 ssh_size();
1585
8ccc75b0 1586 ssh_send_ok = 1;
dacbd0e8 1587 ssh_channels = newtree234(ssh_channelcmp);
374330e2 1588 while (1) {
1589 crReturnV;
1590 if (ispkt) {
e5574168 1591 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1592 pktin.type == SSH1_SMSG_STDERR_DATA) {
fb09bf1c 1593 long len = GET_32BIT(pktin.body);
1594 c_write(pktin.body+4, len);
e5574168 1595 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
21248260 1596 ssh_state = SSH_STATE_CLOSED;
c5e9c988 1597 logevent("Received disconnect request");
dacbd0e8 1598 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
1599 /* Remote side is trying to open a channel to talk to our
1600 * agent. Give them back a local channel number. */
1601 int i = 1;
1602 struct ssh_channel *c;
1603 enum234 e;
1604 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
1605 if (c->localid > i)
1606 break; /* found a free number */
1607 i = c->localid + 1;
1608 }
1609 c = malloc(sizeof(struct ssh_channel));
1610 c->remoteid = GET_32BIT(pktin.body);
1611 c->localid = i;
b8bb811a 1612 c->closes = 0;
dacbd0e8 1613 c->type = SSH1_SMSG_AGENT_OPEN; /* identify channel type */
1614 add234(ssh_channels, c);
1615 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1616 PKT_INT, c->remoteid, PKT_INT, c->localid,
1617 PKT_END);
1618 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
1619 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
1620 /* Remote side closes a channel. */
1621 int i = GET_32BIT(pktin.body);
1622 struct ssh_channel *c;
1623 c = find234(ssh_channels, &i, ssh_channelfind);
1624 if (c) {
1625 int closetype;
1626 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
1627 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
1628 c->closes |= closetype;
1629 if (c->closes == 3) {
1630 del234(ssh_channels, c);
1631 free(c);
1632 }
1633 }
1634 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
1635 /* Data sent down one of our channels. */
1636 int i = GET_32BIT(pktin.body);
1637 int len = GET_32BIT(pktin.body+4);
1638 unsigned char *p = pktin.body+8;
1639 struct ssh_channel *c;
1640 c = find234(ssh_channels, &i, ssh_channelfind);
1641 if (c) {
1642 switch(c->type) {
1643 case SSH1_SMSG_AGENT_OPEN:
1644 /* Data for an agent message. Buffer it. */
1645 while (len > 0) {
1646 if (c->u.a.lensofar < 4) {
1647 int l = min(4 - c->u.a.lensofar, len);
1648 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
1649 p += l; len -= l; c->u.a.lensofar += l;
1650 }
1651 if (c->u.a.lensofar == 4) {
1652 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
1653 c->u.a.message = malloc(c->u.a.totallen);
1654 memcpy(c->u.a.message, c->u.a.msglen, 4);
1655 }
1656 if (c->u.a.lensofar >= 4 && len > 0) {
1657 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
1658 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
1659 p += l; len -= l; c->u.a.lensofar += l;
1660 }
1661 if (c->u.a.lensofar == c->u.a.totallen) {
1662 void *reply, *sentreply;
1663 int replylen;
1664 agent_query(c->u.a.message, c->u.a.totallen,
1665 &reply, &replylen);
1666 if (reply)
1667 sentreply = reply;
1668 else {
1669 /* Fake SSH_AGENT_FAILURE. */
1670 sentreply = "\0\0\0\1\5";
1671 replylen = 5;
1672 }
1673 send_packet(SSH1_MSG_CHANNEL_DATA,
1674 PKT_INT, c->remoteid,
1675 PKT_INT, replylen,
1676 PKT_DATA, sentreply, replylen,
1677 PKT_END);
1678 if (reply)
1679 free(reply);
1680 free(c->u.a.message);
1681 c->u.a.lensofar = 0;
1682 }
1683 }
1684 break;
1685 }
1686 }
e5574168 1687 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
972a41c8 1688 /* may be from EXEC_SHELL on some servers */
e5574168 1689 } else if (pktin.type == SSH1_SMSG_FAILURE) {
972a41c8 1690 /* may be from EXEC_SHELL on some servers
374330e2 1691 * if no pty is available or in other odd cases. Ignore */
e5574168 1692 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1693 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
374330e2 1694 } else {
1695 fatalbox("Strange packet received: type %d", pktin.type);
1696 }
1697 } else {
e5574168 1698 send_packet(SSH1_CMSG_STDIN_DATA,
fb09bf1c 1699 PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
374330e2 1700 }
1701 }
1702
1703 crFinishV;
1704}
1705
1706/*
e5574168 1707 * Utility routine for decoding comma-separated strings in KEXINIT.
1708 */
1709int in_commasep_string(char *needle, char *haystack, int haylen) {
1710 int needlen = strlen(needle);
1711 while (1) {
1712 /*
1713 * Is it at the start of the string?
1714 */
1715 if (haylen >= needlen && /* haystack is long enough */
1716 !memcmp(needle, haystack, needlen) && /* initial match */
1717 (haylen == needlen || haystack[needlen] == ',')
1718 /* either , or EOS follows */
1719 )
1720 return 1;
1721 /*
1722 * If not, search for the next comma and resume after that.
1723 * If no comma found, terminate.
1724 */
1725 while (haylen > 0 && *haystack != ',')
1726 haylen--, haystack++;
1727 if (haylen == 0)
1728 return 0;
1729 haylen--, haystack++; /* skip over comma itself */
1730 }
1731}
1732
1733/*
d39f364a 1734 * SSH2 key creation method.
1735 */
1736void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1737 SHA_State s;
1738 /* First 20 bytes. */
1739 SHA_Init(&s);
1740 sha_mpint(&s, K);
1741 SHA_Bytes(&s, H, 20);
1742 SHA_Bytes(&s, &chr, 1);
1743 SHA_Bytes(&s, H, 20);
1744 SHA_Final(&s, keyspace);
1745 /* Next 20 bytes. */
1746 SHA_Init(&s);
1747 sha_mpint(&s, K);
1748 SHA_Bytes(&s, H, 20);
1749 SHA_Bytes(&s, keyspace, 20);
1750 SHA_Final(&s, keyspace+20);
1751}
1752
1753/*
7cca0d81 1754 * Handle the SSH2 transport layer.
e5574168 1755 */
7cca0d81 1756static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
e5574168 1757{
1758 static int i, len;
1759 static char *str;
1760 static Bignum e, f, K;
1761 static struct ssh_cipher *cscipher_tobe = NULL;
1762 static struct ssh_cipher *sccipher_tobe = NULL;
1763 static struct ssh_mac *csmac_tobe = NULL;
1764 static struct ssh_mac *scmac_tobe = NULL;
1765 static struct ssh_compress *cscomp_tobe = NULL;
1766 static struct ssh_compress *sccomp_tobe = NULL;
7cca0d81 1767 static char *hostkeydata, *sigdata, *keystr;
e5574168 1768 static int hostkeylen, siglen;
1769 static unsigned char exchange_hash[20];
d39f364a 1770 static unsigned char keyspace[40];
e5574168 1771
1772 crBegin;
7cca0d81 1773 random_init();
e5574168 1774
7cca0d81 1775 begin_key_exchange:
e5574168 1776 /*
1777 * Construct and send our key exchange packet.
1778 */
1779 ssh2_pkt_init(SSH2_MSG_KEXINIT);
1780 for (i = 0; i < 16; i++)
1781 ssh2_pkt_addbyte((unsigned char)random_byte());
1782 /* List key exchange algorithms. */
1783 ssh2_pkt_addstring_start();
1784 for (i = 0; i < lenof(kex_algs); i++) {
1785 ssh2_pkt_addstring_str(kex_algs[i]->name);
1786 if (i < lenof(kex_algs)-1)
1787 ssh2_pkt_addstring_str(",");
1788 }
1789 /* List server host key algorithms. */
1790 ssh2_pkt_addstring_start();
1791 for (i = 0; i < lenof(hostkey_algs); i++) {
1792 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1793 if (i < lenof(hostkey_algs)-1)
1794 ssh2_pkt_addstring_str(",");
1795 }
1796 /* List client->server encryption algorithms. */
1797 ssh2_pkt_addstring_start();
1798 for (i = 0; i < lenof(ciphers); i++) {
1799 ssh2_pkt_addstring_str(ciphers[i]->name);
1800 if (i < lenof(ciphers)-1)
1801 ssh2_pkt_addstring_str(",");
1802 }
1803 /* List server->client encryption algorithms. */
1804 ssh2_pkt_addstring_start();
1805 for (i = 0; i < lenof(ciphers); i++) {
1806 ssh2_pkt_addstring_str(ciphers[i]->name);
1807 if (i < lenof(ciphers)-1)
1808 ssh2_pkt_addstring_str(",");
1809 }
1810 /* List client->server MAC algorithms. */
1811 ssh2_pkt_addstring_start();
1812 for (i = 0; i < lenof(macs); i++) {
1813 ssh2_pkt_addstring_str(macs[i]->name);
1814 if (i < lenof(macs)-1)
1815 ssh2_pkt_addstring_str(",");
1816 }
1817 /* List server->client MAC algorithms. */
1818 ssh2_pkt_addstring_start();
1819 for (i = 0; i < lenof(macs); i++) {
1820 ssh2_pkt_addstring_str(macs[i]->name);
1821 if (i < lenof(macs)-1)
1822 ssh2_pkt_addstring_str(",");
1823 }
1824 /* List client->server compression algorithms. */
1825 ssh2_pkt_addstring_start();
1826 for (i = 0; i < lenof(compressions); i++) {
1827 ssh2_pkt_addstring_str(compressions[i]->name);
1828 if (i < lenof(compressions)-1)
1829 ssh2_pkt_addstring_str(",");
1830 }
1831 /* List server->client compression algorithms. */
1832 ssh2_pkt_addstring_start();
1833 for (i = 0; i < lenof(compressions); i++) {
1834 ssh2_pkt_addstring_str(compressions[i]->name);
1835 if (i < lenof(compressions)-1)
1836 ssh2_pkt_addstring_str(",");
1837 }
1838 /* List client->server languages. Empty list. */
1839 ssh2_pkt_addstring_start();
1840 /* List server->client languages. Empty list. */
1841 ssh2_pkt_addstring_start();
1842 /* First KEX packet does _not_ follow, because we're not that brave. */
1843 ssh2_pkt_addbool(FALSE);
1844 /* Reserved. */
1845 ssh2_pkt_adduint32(0);
1846 sha_string(&exhash, pktout.data+5, pktout.length-5);
1847 ssh2_pkt_send();
1848
1849 if (!ispkt) crWaitUntil(ispkt);
1850 sha_string(&exhash, pktin.data+5, pktin.length-5);
1851
1852 /*
1853 * Now examine the other side's KEXINIT to see what we're up
1854 * to.
1855 */
7cca0d81 1856 if (pktin.type != SSH2_MSG_KEXINIT) {
e5574168 1857 fatalbox("expected key exchange packet from server");
7cca0d81 1858 }
e5574168 1859 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1860 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1861 pktin.savedpos += 16; /* skip garbage cookie */
1862 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
1863 for (i = 0; i < lenof(kex_algs); i++) {
1864 if (in_commasep_string(kex_algs[i]->name, str, len)) {
1865 kex = kex_algs[i];
1866 break;
1867 }
1868 }
1869 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
1870 for (i = 0; i < lenof(hostkey_algs); i++) {
1871 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1872 hostkey = hostkey_algs[i];
1873 break;
1874 }
1875 }
1876 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
1877 for (i = 0; i < lenof(ciphers); i++) {
1878 if (in_commasep_string(ciphers[i]->name, str, len)) {
1879 cscipher_tobe = ciphers[i];
1880 break;
1881 }
1882 }
1883 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
1884 for (i = 0; i < lenof(ciphers); i++) {
1885 if (in_commasep_string(ciphers[i]->name, str, len)) {
1886 sccipher_tobe = ciphers[i];
1887 break;
1888 }
1889 }
1890 ssh2_pkt_getstring(&str, &len); /* client->server mac */
1891 for (i = 0; i < lenof(macs); i++) {
1892 if (in_commasep_string(macs[i]->name, str, len)) {
1893 csmac_tobe = macs[i];
1894 break;
1895 }
1896 }
1897 ssh2_pkt_getstring(&str, &len); /* server->client mac */
1898 for (i = 0; i < lenof(macs); i++) {
1899 if (in_commasep_string(macs[i]->name, str, len)) {
1900 scmac_tobe = macs[i];
1901 break;
1902 }
1903 }
1904 ssh2_pkt_getstring(&str, &len); /* client->server compression */
1905 for (i = 0; i < lenof(compressions); i++) {
1906 if (in_commasep_string(compressions[i]->name, str, len)) {
1907 cscomp_tobe = compressions[i];
1908 break;
1909 }
1910 }
1911 ssh2_pkt_getstring(&str, &len); /* server->client compression */
1912 for (i = 0; i < lenof(compressions); i++) {
1913 if (in_commasep_string(compressions[i]->name, str, len)) {
1914 sccomp_tobe = compressions[i];
1915 break;
1916 }
1917 }
e5574168 1918
1919 /*
1920 * Currently we only support Diffie-Hellman and DSS, so let's
1921 * bomb out if those aren't selected.
1922 */
1923 if (kex != &ssh_diffiehellman || hostkey != &ssh_dss)
1924 fatalbox("internal fault: chaos in SSH 2 transport layer");
1925
1926 /*
1927 * Now we begin the fun. Generate and send e for Diffie-Hellman.
1928 */
1929 e = dh_create_e();
e5574168 1930 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
1931 ssh2_pkt_addmp(e);
1932 ssh2_pkt_send();
1933
1934 crWaitUntil(ispkt);
7cca0d81 1935 if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
e5574168 1936 fatalbox("expected key exchange packet from server");
7cca0d81 1937 }
e5574168 1938 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
1939 f = ssh2_pkt_getmp();
e5574168 1940 ssh2_pkt_getstring(&sigdata, &siglen);
1941
1942 K = dh_find_K(f);
e5574168 1943
1944 sha_string(&exhash, hostkeydata, hostkeylen);
1945 sha_mpint(&exhash, e);
1946 sha_mpint(&exhash, f);
1947 sha_mpint(&exhash, K);
1948 SHA_Final(&exhash, exchange_hash);
1949
7cca0d81 1950#if 0
e5574168 1951 debug(("Exchange hash is:\r\n"));
1952 for (i = 0; i < 20; i++)
1953 debug((" %02x", exchange_hash[i]));
1954 debug(("\r\n"));
7cca0d81 1955#endif
1956
1957 hostkey->setkey(hostkeydata, hostkeylen);
1958 if (!hostkey->verifysig(sigdata, siglen, exchange_hash, 20))
1959 fatalbox("Server failed host key check");
e5574168 1960
1961 /*
7cca0d81 1962 * Expect SSH2_MSG_NEWKEYS from server.
d39f364a 1963 */
7cca0d81 1964 crWaitUntil(ispkt);
1965 if (pktin.type != SSH2_MSG_NEWKEYS)
1966 fatalbox("expected new-keys packet from server");
d39f364a 1967
1968 /*
7cca0d81 1969 * Authenticate remote host: verify host key. (We've already
1970 * checked the signature of the exchange hash.)
e5574168 1971 */
7cca0d81 1972 keystr = hostkey->fmtkey();
1973 verify_ssh_host_key(savedhost, keystr);
1974 free(keystr);
d39f364a 1975
1976 /*
7cca0d81 1977 * Send SSH2_MSG_NEWKEYS.
d39f364a 1978 */
1979 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
1980 ssh2_pkt_send();
d39f364a 1981
1982 /*
1983 * Create and initialise session keys.
1984 */
1985 cscipher = cscipher_tobe;
1986 sccipher = sccipher_tobe;
1987 csmac = csmac_tobe;
1988 scmac = scmac_tobe;
1989 cscomp = cscomp_tobe;
1990 sccomp = sccomp_tobe;
1991 /*
1992 * Set IVs after keys.
1993 */
1994 ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
1995 ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
1996 ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
1997 ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
1998 ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
1999 ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
2000
033b4cef 2001 /*
7cca0d81 2002 * Now we're encrypting. Begin returning 1 to the protocol main
2003 * function so that other things can run on top of the
2004 * transport. If we ever see a KEXINIT, we must go back to the
2005 * start.
033b4cef 2006 */
7cca0d81 2007 do {
2008 crReturn(1);
2009 } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
2010 goto begin_key_exchange;
e5574168 2011
2012 crFinish(1);
2013}
2014
7cca0d81 2015/*
6abbf9e3 2016 * SSH2: remote identifier for the main session channel.
2017 */
2018static unsigned long ssh_remote_channel;
2019
2020/*
7cca0d81 2021 * Handle the SSH2 userauth and connection layers.
2022 */
2023static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2024{
7cca0d81 2025 static unsigned long remote_winsize;
2026 static unsigned long remote_maxpkt;
2027
e5574168 2028 crBegin;
2029
7cca0d81 2030 /*
2031 * Request userauth protocol, and await a response to it.
2032 */
2033 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2034 ssh2_pkt_addstring("ssh-userauth");
2035 ssh2_pkt_send();
2036 crWaitUntilV(ispkt);
2037 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT)
2038 fatalbox("Server refused user authentication protocol");
2039
2040 /*
2041 * FIXME: currently we support only password authentication.
2042 * (This places us technically in violation of the SSH2 spec.
2043 * We must fix this.)
2044 */
2045 while (1) {
2046 /*
2047 * Get a username and a password.
2048 */
2049 static char username[100];
2050 static char password[100];
2051 static int pos = 0;
2052 static char c;
e5574168 2053
4017be6d 2054 if ((flags & FLAG_CONNECTION) && !*cfg.username) {
7cca0d81 2055 c_write("login as: ", 10);
2056 while (pos >= 0) {
2057 crWaitUntilV(!ispkt);
2058 while (inlen--) switch (c = *in++) {
2059 case 10: case 13:
2060 username[pos] = 0;
2061 pos = -1;
2062 break;
2063 case 8: case 127:
2064 if (pos > 0) {
2065 c_write("\b \b", 3);
2066 pos--;
2067 }
2068 break;
2069 case 21: case 27:
2070 while (pos > 0) {
2071 c_write("\b \b", 3);
2072 pos--;
2073 }
2074 break;
2075 case 3: case 4:
2076 random_save_seed();
2077 exit(0);
2078 break;
2079 default:
2080 if (((c >= ' ' && c <= '~') ||
2081 ((unsigned char)c >= 160)) && pos < 40) {
2082 username[pos++] = c;
2083 c_write(&c, 1);
2084 }
2085 break;
2086 }
2087 }
2088 c_write("\r\n", 2);
2089 username[strcspn(username, "\n\r")] = '\0';
2090 } else {
2091 char stuff[200];
2092 strncpy(username, cfg.username, 99);
2093 username[99] = '\0';
4017be6d 2094 if (flags & FLAG_VERBOSE) {
7cca0d81 2095 sprintf(stuff, "Using username \"%s\".\r\n", username);
2096 c_write(stuff, strlen(stuff));
2097 }
2098 }
2099
4017be6d 2100 if (!(flags & FLAG_WINDOWED)) {
7cca0d81 2101 char prompt[200];
2102 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
2103 if (!ssh_get_password(prompt, password, sizeof(password))) {
2104 /*
2105 * get_password failed to get a password (for
2106 * example because one was supplied on the command
2107 * line which has already failed to work).
2108 * Terminate.
2109 */
2110 logevent("No more passwords to try");
2111 ssh_state = SSH_STATE_CLOSED;
2112 crReturnV;
2113 }
2114 } else {
2115 c_write("password: ", 10);
2116
2117 pos = 0;
2118 while (pos >= 0) {
2119 crWaitUntilV(!ispkt);
2120 while (inlen--) switch (c = *in++) {
2121 case 10: case 13:
2122 password[pos] = 0;
2123 pos = -1;
2124 break;
2125 case 8: case 127:
2126 if (pos > 0)
2127 pos--;
2128 break;
2129 case 21: case 27:
2130 pos = 0;
2131 break;
2132 case 3: case 4:
2133 random_save_seed();
2134 exit(0);
2135 break;
2136 default:
2137 if (((c >= ' ' && c <= '~') ||
2138 ((unsigned char)c >= 160)) && pos < 40)
2139 password[pos++] = c;
2140 break;
2141 }
2142 }
2143 c_write("\r\n", 2);
2144 }
2145
2146 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2147 ssh2_pkt_addstring(username);
2148 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2149 ssh2_pkt_addstring("password");
2150 ssh2_pkt_addbool(FALSE);
2151 ssh2_pkt_addstring(password);
2152 ssh2_pkt_send();
2153
2154 crWaitUntilV(ispkt);
2155 if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
2156 c_write("Access denied\r\n", 15);
2157 logevent("Authentication refused");
2158 } else
2159 break;
2160 }
2161
2162 /*
2163 * Now we're authenticated for the connection protocol. The
2164 * connection protocol will automatically have started at this
2165 * point; there's no need to send SERVICE_REQUEST.
2166 */
2167
2168 /*
2169 * So now create a channel with a session in it.
2170 */
2171 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
2172 ssh2_pkt_addstring("session");
2173 ssh2_pkt_adduint32(100); /* as good as any */
59dcd2a8 2174 ssh2_pkt_adduint32(0x7FFFFFFFUL); /* very big window which we ignore */
2175 ssh2_pkt_adduint32(0x7FFFFFFFUL); /* very big max pkt size */
7cca0d81 2176 ssh2_pkt_send();
2177 crWaitUntilV(ispkt);
2178 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
2179 fatalbox("Server refused to open a session");
2180 /* FIXME: error data comes back in FAILURE packet */
2181 }
2182 if (ssh2_pkt_getuint32() != 100) {
2183 fatalbox("Server's channel confirmation cited wrong channel");
2184 }
6abbf9e3 2185 ssh_remote_channel = ssh2_pkt_getuint32();
7cca0d81 2186 remote_winsize = ssh2_pkt_getuint32();
2187 remote_maxpkt = ssh2_pkt_getuint32();
2188 logevent("Opened channel for session");
2189
2190 /*
2191 * Now allocate a pty for the session.
2192 */
2193 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6abbf9e3 2194 ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
7cca0d81 2195 ssh2_pkt_addstring("pty-req");
2196 ssh2_pkt_addbool(1); /* want reply */
2197 ssh2_pkt_addstring(cfg.termtype);
2198 ssh2_pkt_adduint32(cols);
2199 ssh2_pkt_adduint32(rows);
2200 ssh2_pkt_adduint32(0); /* pixel width */
2201 ssh2_pkt_adduint32(0); /* pixel height */
2202 ssh2_pkt_addstring_start();
2203 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
2204 ssh2_pkt_send();
2205
2206 do { /* FIXME: pay attention to these */
2207 crWaitUntilV(ispkt);
2208 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2209
2210 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2211 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2212 fatalbox("Server got confused by pty request");
2213 }
2214 c_write("Server refused to allocate pty\r\n", 32);
2215 } else {
2216 logevent("Allocated pty");
2217 }
2218
2219 /*
2220 * Start a shell.
2221 */
2222 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6abbf9e3 2223 ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
7cca0d81 2224 ssh2_pkt_addstring("shell");
2225 ssh2_pkt_addbool(1); /* want reply */
2226 ssh2_pkt_send();
2227 do { /* FIXME: pay attention to these */
2228 crWaitUntilV(ispkt);
2229 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2230 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2231 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2232 fatalbox("Server got confused by shell request");
2233 }
2234 fatalbox("Server refused to start a shell");
2235 } else {
2236 logevent("Started a shell");
2237 }
2238
2239 /*
2240 * Transfer data!
2241 */
8ccc75b0 2242 ssh_send_ok = 1;
7cca0d81 2243 while (1) {
e5574168 2244 crReturnV;
7cca0d81 2245 if (ispkt) {
2246 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
2247 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
2248 char *data;
2249 int length;
2250 if (ssh2_pkt_getuint32() != 100)
2251 continue; /* wrong channel */
2252 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
2253 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
2254 continue; /* extended but not stderr */
2255 ssh2_pkt_getstring(&data, &length);
2256 if (data)
2257 c_write(data, length);
2258 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
2259 ssh_state = SSH_STATE_CLOSED;
2260 logevent("Received disconnect request");
2261 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2262 continue; /* exit status et al; ignore (FIXME?) */
2263 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2264 continue; /* ignore for now (FIXME!) */
2265 } else {
2266 fatalbox("Strange packet received: type %d", pktin.type);
2267 }
2268 } else {
2269 /* FIXME: for now, ignore window size */
2270 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6abbf9e3 2271 ssh2_pkt_adduint32(ssh_remote_channel);
7cca0d81 2272 ssh2_pkt_addstring_start();
2273 ssh2_pkt_addstring_data(in, inlen);
2274 ssh2_pkt_send();
2275 }
e5574168 2276 }
2277
2278 crFinishV;
2279}
2280
2281/*
7cca0d81 2282 * Handle the top-level SSH2 protocol.
2283 */
2284static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2285{
2286 if (do_ssh2_transport(in, inlen, ispkt) == 0)
2287 return;
2288 do_ssh2_authconn(in, inlen, ispkt);
2289}
2290
2291/*
374330e2 2292 * Called to set up the connection. Will arrange for WM_NETEVENT
2293 * messages to be passed to the specified window, whose window
2294 * procedure should then call telnet_msg().
2295 *
2296 * Returns an error message, or NULL on success.
374330e2 2297 */
2298static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
fb09bf1c 2299 char *p;
8f203108 2300
2301#ifdef MSCRYPTOAPI
2302 if(crypto_startup() == 0)
2303 return "Microsoft high encryption pack not installed!";
2304#endif
374330e2 2305
fb09bf1c 2306 p = connect_to_host(host, port, realhost);
2307 if (p != NULL)
2308 return p;
374330e2 2309
2310 if (!do_ssh_init())
2311 return "Protocol initialisation error";
2312
4017be6d 2313 if (hwnd && WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
374330e2 2314 switch (WSAGetLastError()) {
2315 case WSAENETDOWN: return "Network is down";
2316 default: return "WSAAsyncSelect(): unknown error";
2317 }
2318
2319 return NULL;
2320}
2321
2322/*
2323 * Process a WM_NETEVENT message. Will return 0 if the connection
2324 * has closed, or <0 for a socket error.
2325 */
2326static int ssh_msg (WPARAM wParam, LPARAM lParam) {
2327 int ret;
2328 char buf[256];
2329
8ce72d2c 2330 /*
2331 * Because reading less than the whole of the available pending
2332 * data can generate an FD_READ event, we need to allow for the
2333 * possibility that FD_READ may arrive with FD_CLOSE already in
2334 * the queue; so it's possible that we can get here even with s
2335 * invalid. If so, we return 1 and don't worry about it.
2336 */
2337 if (s == INVALID_SOCKET)
2338 return 1;
374330e2 2339
2340 if (WSAGETSELECTERROR(lParam) != 0)
2341 return -WSAGETSELECTERROR(lParam);
2342
2343 switch (WSAGETSELECTEVENT(lParam)) {
2344 case FD_READ:
8ce72d2c 2345 case FD_CLOSE:
374330e2 2346 ret = recv(s, buf, sizeof(buf), 0);
2347 if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
2348 return 1;
2349 if (ret < 0) /* any _other_ error */
2350 return -10000-WSAGetLastError();
2351 if (ret == 0) {
2352 s = INVALID_SOCKET;
8ce72d2c 2353 return 0;
374330e2 2354 }
2355 ssh_gotdata (buf, ret);
85ee8208 2356 if (ssh_state == SSH_STATE_CLOSED) {
2357 closesocket(s);
2358 s = INVALID_SOCKET;
2359 return 0;
2360 }
374330e2 2361 return 1;
374330e2 2362 }
2363 return 1; /* shouldn't happen, but WTF */
2364}
2365
2366/*
2367 * Called to send data down the Telnet connection.
2368 */
2369static void ssh_send (char *buf, int len) {
2370 if (s == INVALID_SOCKET)
2371 return;
2372
2373 ssh_protocol(buf, len, 0);
2374}
2375
2376/*
2377 * Called to set the size of the window from Telnet's POV.
2378 */
2379static void ssh_size(void) {
2380 switch (ssh_state) {
2381 case SSH_STATE_BEFORE_SIZE:
21248260 2382 case SSH_STATE_CLOSED:
374330e2 2383 break; /* do nothing */
2384 case SSH_STATE_INTERMED:
2385 size_needed = TRUE; /* buffer for later */
2386 break;
2387 case SSH_STATE_SESSION:
fef97f43 2388 if (!cfg.nopty) {
e5574168 2389 send_packet(SSH1_CMSG_WINDOW_SIZE,
fb09bf1c 2390 PKT_INT, rows, PKT_INT, cols,
2391 PKT_INT, 0, PKT_INT, 0, PKT_END);
fef97f43 2392 }
374330e2 2393 }
2394}
2395
2396/*
6abbf9e3 2397 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2398 * can send an EOF and collect resulting output (e.g. `plink
2399 * hostname sort').
374330e2 2400 */
2401static void ssh_special (Telnet_Special code) {
6abbf9e3 2402 if (code == TS_EOF) {
2403 if (ssh_version = 1) {
2404 send_packet(SSH1_CMSG_EOF, PKT_END);
2405 } else {
2406 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
2407 ssh2_pkt_adduint32(ssh_remote_channel);
2408 ssh2_pkt_send();
2409 }
2410 } else {
2411 /* do nothing */
2412 }
374330e2 2413}
2414
fb09bf1c 2415
2416/*
2417 * Read and decrypt one incoming SSH packet.
2418 * (only used by pSCP)
2419 */
2420static void get_packet(void)
2421{
2422 unsigned char buf[4096], *p;
2423 long to_read;
2424 int len;
2425
fb09bf1c 2426 p = NULL;
2427 len = 0;
2428
2429 while ((to_read = s_rdpkt(&p, &len)) > 0) {
2430 if (to_read > sizeof(buf)) to_read = sizeof(buf);
2431 len = s_read(buf, to_read);
2432 if (len != to_read) {
2433 closesocket(s);
2434 s = INVALID_SOCKET;
2435 return;
2436 }
2437 p = buf;
2438 }
2439
2440 assert(len == 0);
2441}
2442
2443/*
2444 * Receive a block of data over the SSH link. Block until
2445 * all data is available. Return nr of bytes read (0 if lost connection).
2446 * (only used by pSCP)
2447 */
2448int ssh_scp_recv(unsigned char *buf, int len)
2449{
2450 static int pending_input_len = 0;
2451 static unsigned char *pending_input_ptr;
2452 int to_read = len;
2453
fb09bf1c 2454 if (pending_input_len >= to_read) {
2455 memcpy(buf, pending_input_ptr, to_read);
2456 pending_input_ptr += to_read;
2457 pending_input_len -= to_read;
2458 return len;
2459 }
2460
2461 if (pending_input_len > 0) {
2462 memcpy(buf, pending_input_ptr, pending_input_len);
2463 buf += pending_input_len;
2464 to_read -= pending_input_len;
2465 pending_input_len = 0;
2466 }
2467
2468 if (s == INVALID_SOCKET)
2469 return 0;
2470 while (to_read > 0) {
2471 get_packet();
2472 if (s == INVALID_SOCKET)
2473 return 0;
e5574168 2474 if (pktin.type == SSH1_SMSG_STDOUT_DATA) {
fb09bf1c 2475 int plen = GET_32BIT(pktin.body);
2476 if (plen <= to_read) {
2477 memcpy(buf, pktin.body + 4, plen);
2478 buf += plen;
2479 to_read -= plen;
2480 } else {
2481 memcpy(buf, pktin.body + 4, to_read);
2482 pending_input_len = plen - to_read;
2483 pending_input_ptr = pktin.body + 4 + to_read;
2484 to_read = 0;
2485 }
e5574168 2486 } else if (pktin.type == SSH1_SMSG_STDERR_DATA) {
fb09bf1c 2487 int plen = GET_32BIT(pktin.body);
2488 fwrite(pktin.body + 4, plen, 1, stderr);
e5574168 2489 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
fb09bf1c 2490 logevent("Received disconnect request");
e5574168 2491 } else if (pktin.type == SSH1_SMSG_SUCCESS ||
2492 pktin.type == SSH1_SMSG_FAILURE) {
fb09bf1c 2493 /* ignore */
e5574168 2494 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
fb09bf1c 2495 char logbuf[100];
2496 sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
2497 logevent(logbuf);
e5574168 2498 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
fb09bf1c 2499 logevent("Closing connection");
2500 closesocket(s);
2501 s = INVALID_SOCKET;
2502 } else {
2503 fatalbox("Strange packet received: type %d", pktin.type);
2504 }
2505 }
2506
2507 return len;
2508}
2509
2510/*
2511 * Send a block of data over the SSH link.
2512 * Block until all data is sent.
2513 * (only used by pSCP)
2514 */
2515void ssh_scp_send(unsigned char *buf, int len)
2516{
fb09bf1c 2517 if (s == INVALID_SOCKET)
2518 return;
e5574168 2519 send_packet(SSH1_CMSG_STDIN_DATA,
fb09bf1c 2520 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2521}
2522
2523/*
2524 * Send an EOF notification to the server.
2525 * (only used by pSCP)
2526 */
2527void ssh_scp_send_eof(void)
2528{
fb09bf1c 2529 if (s == INVALID_SOCKET)
2530 return;
e5574168 2531 send_packet(SSH1_CMSG_EOF, PKT_END);
fb09bf1c 2532}
2533
2534/*
2535 * Set up the connection, login on the remote host and
2536 * start execution of a command.
2537 * Returns an error message, or NULL on success.
2538 * (only used by pSCP)
2539 */
2540char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
2541{
2542 char buf[160], *p;
2543
fb09bf1c 2544#ifdef MSCRYPTOAPI
2545 if (crypto_startup() == 0)
2546 return "Microsoft high encryption pack not installed!";
2547#endif
2548
2549 p = connect_to_host(host, port, realhost);
2550 if (p != NULL)
2551 return p;
2552
2553 random_init();
2554
2555 if (!do_ssh_init())
2556 return "Protocol initialisation error";
2557
2558 /* Exchange keys and login */
2559 do {
2560 get_packet();
2561 if (s == INVALID_SOCKET)
2562 return "Connection closed by remote host";
e5574168 2563 } while (!do_ssh1_login(NULL, 0, 1));
85ee8208 2564
2565 if (ssh_state == SSH_STATE_CLOSED) {
2566 closesocket(s);
2567 s = INVALID_SOCKET;
2568 return "Session initialisation error";
2569 }
fb09bf1c 2570
2571 /* Execute command */
2572 sprintf(buf, "Sending command: %.100s", cmd);
2573 logevent(buf);
e5574168 2574 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
fb09bf1c 2575
2576 return NULL;
2577}
2578
8ccc75b0 2579static SOCKET ssh_socket(void) { return s; }
2580
2581static int ssh_sendok(void) { return ssh_send_ok; }
fb09bf1c 2582
374330e2 2583Backend ssh_backend = {
2584 ssh_init,
2585 ssh_msg,
2586 ssh_send,
2587 ssh_size,
4017be6d 2588 ssh_special,
8ccc75b0 2589 ssh_socket,
2590 ssh_sendok
374330e2 2591};