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