Introduce the ability to distinguish remote SSH implementations by
[u/mdw/putty] / ssh.c
CommitLineData
8df7a775 1#include <windows.h>
374330e2 2#include <stdio.h>
3#include <stdlib.h>
fb09bf1c 4#include <stdarg.h>
5#include <assert.h>
374330e2 6
7#include "putty.h"
dacbd0e8 8#include "tree234.h"
fb09bf1c 9#include "ssh.h"
374330e2 10
11#ifndef FALSE
12#define FALSE 0
13#endif
14#ifndef TRUE
15#define TRUE 1
16#endif
17
fb09bf1c 18#define logevent(s) { logevent(s); \
67779be7 19 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
fb09bf1c 20 fprintf(stderr, "%s\n", s); }
21
3cd52910 22#define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
4a8fc3c4 23 (s ? sk_close(s), s = NULL : 0), \
3cd52910 24 connection_fatal msg )
8d5de777 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 */
9c964e85 50#define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
51#define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
52#define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
d211621f 53#define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
54#define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
d211621f 55#define SSH1_MSG_IGNORE 32 /* 0x20 */
9c964e85 56#define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
57#define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
58#define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
d211621f 59#define SSH1_MSG_DEBUG 36 /* 0x24 */
4ba9b64b 60#define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
d211621f 61#define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
62#define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
63#define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
64#define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
65#define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
66#define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
67
68#define SSH1_AUTH_TIS 5 /* 0x5 */
69#define SSH1_AUTH_CCARD 16 /* 0x10 */
70
d211621f 71#define SSH2_MSG_DISCONNECT 1 /* 0x1 */
72#define SSH2_MSG_IGNORE 2 /* 0x2 */
73#define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
74#define SSH2_MSG_DEBUG 4 /* 0x4 */
75#define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
76#define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
77#define SSH2_MSG_KEXINIT 20 /* 0x14 */
78#define SSH2_MSG_NEWKEYS 21 /* 0x15 */
79#define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
80#define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
a92dd380 81#define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
82#define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
83#define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
84#define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
d211621f 85#define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
86#define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
87#define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
88#define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
89#define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
90#define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
91#define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
92#define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
93#define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
94#define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
95#define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
96#define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
97#define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
98#define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
99#define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
100#define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
101#define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
102#define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
103#define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
104#define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
105
9005f3ba 106#define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
107#define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
108#define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
109#define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
110#define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
111#define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
112#define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
113#define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
114#define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
115#define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
116#define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
117
d211621f 118#define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
119#define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
120#define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
121#define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
122
123#define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
fb09bf1c 124
7d503c31 125/*
126 * Various remote-bug flags.
127 */
128#define BUG_CHOKES_ON_SSH1_IGNORE 1
129#define BUG_SSH2_HMAC 2
130
fb09bf1c 131#define GET_32BIT(cp) \
132 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
133 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
134 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
135 ((unsigned long)(unsigned char)(cp)[3]))
136
137#define PUT_32BIT(cp, value) { \
138 (cp)[0] = (unsigned char)((value) >> 24); \
139 (cp)[1] = (unsigned char)((value) >> 16); \
140 (cp)[2] = (unsigned char)((value) >> 8); \
141 (cp)[3] = (unsigned char)(value); }
142
7cca0d81 143enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
972a41c8 144
374330e2 145/* Coroutine mechanics for the sillier bits of the code */
146#define crBegin1 static int crLine = 0;
147#define crBegin2 switch(crLine) { case 0:;
148#define crBegin crBegin1; crBegin2;
149#define crFinish(z) } crLine = 0; return (z)
150#define crFinishV } crLine = 0; return
151#define crReturn(z) \
152 do {\
153 crLine=__LINE__; return (z); case __LINE__:;\
154 } while (0)
155#define crReturnV \
156 do {\
157 crLine=__LINE__; return; case __LINE__:;\
158 } while (0)
159#define crStop(z) do{ crLine = 0; return (z); }while(0)
160#define crStopV do{ crLine = 0; return; }while(0)
fb09bf1c 161#define crWaitUntil(c) do { crReturn(0); } while (!(c))
7cca0d81 162#define crWaitUntilV(c) do { crReturnV; } while (!(c))
374330e2 163
0c6c9a70 164extern char *x11_init (Socket *, char *, void *);
9c964e85 165extern void x11_close (Socket);
166extern void x11_send (Socket , char *, int);
167extern void x11_invent_auth(char *, int, char *, int);
168
5e8358ad 169/*
170 * Ciphers for SSH2. We miss out single-DES because it isn't
171 * supported; also 3DES and Blowfish are both done differently from
172 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
173 * endianness and different-sized keys.)
5e8358ad 174 */
0a3f1d48 175const static struct ssh2_ciphers *ciphers[] = {
176 &ssh2_aes,
177 &ssh2_blowfish,
178 &ssh2_3des,
8479e33c 179};
e5574168 180
a92dd380 181const static struct ssh_kex *kex_algs[] = {
182#ifdef DO_DIFFIE_HELLMAN_GEX
183 &ssh_diffiehellman_gex,
184#endif
185 &ssh_diffiehellman };
e5574168 186
85cc02bb 187const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
e5574168 188
d39f364a 189static void nullmac_key(unsigned char *key) { }
e5574168 190static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
191static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
57476f6b 192const static struct ssh_mac ssh_mac_none = {
d39f364a 193 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
e5574168 194};
8b2715b2 195const static struct ssh_mac *macs[] = {
196 &ssh_sha1, &ssh_md5, &ssh_mac_none };
197const static struct ssh_mac *buggymacs[] = {
198 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none };
e5574168 199
4ba9b64b 200static void ssh_comp_none_init(void) { }
201static int ssh_comp_none_block(unsigned char *block, int len,
202 unsigned char **outblock, int *outlen) {
203 return 0;
204}
57476f6b 205const static struct ssh_compress ssh_comp_none = {
4ba9b64b 206 "none",
207 ssh_comp_none_init, ssh_comp_none_block,
208 ssh_comp_none_init, ssh_comp_none_block
e5574168 209};
4ba9b64b 210extern const struct ssh_compress ssh_zlib;
211const static struct ssh_compress *compressions[] = {
212 &ssh_zlib, &ssh_comp_none };
374330e2 213
783415f8 214enum { /* channel types */
215 CHAN_MAINSESSION,
216 CHAN_X11,
217 CHAN_AGENT,
218};
219
dacbd0e8 220/*
221 * 2-3-4 tree storing channels.
222 */
223struct ssh_channel {
d211621f 224 unsigned remoteid, localid;
dacbd0e8 225 int type;
226 int closes;
783415f8 227 struct ssh2_data_channel {
228 unsigned char *outbuffer;
229 unsigned outbuflen, outbufsize;
230 unsigned remwindow, remmaxpkt;
231 } v2;
dacbd0e8 232 union {
233 struct ssh_agent_channel {
234 unsigned char *message;
235 unsigned char msglen[4];
236 int lensofar, totallen;
237 } a;
9c964e85 238 struct ssh_x11_channel {
239 Socket s;
783415f8 240 } x11;
dacbd0e8 241 } u;
242};
57476f6b 243
244struct Packet {
245 long length;
246 int type;
247 unsigned char *data;
248 unsigned char *body;
249 long savedpos;
250 long maxlen;
251};
252
0db56f73 253static SHA_State exhash, exhashbase;
57476f6b 254
8df7a775 255static Socket s = NULL;
57476f6b 256
257static unsigned char session_key[32];
4ba9b64b 258static int ssh1_compressing;
db7d555c 259static int ssh_agentfwd_enabled;
9c964e85 260static int ssh_X11_fwd_enabled;
7d503c31 261static int ssh_remote_bugs;
57476f6b 262static const struct ssh_cipher *cipher = NULL;
0a3f1d48 263static const struct ssh2_cipher *cscipher = NULL;
264static const struct ssh2_cipher *sccipher = NULL;
57476f6b 265static const struct ssh_mac *csmac = NULL;
266static const struct ssh_mac *scmac = NULL;
267static const struct ssh_compress *cscomp = NULL;
268static const struct ssh_compress *sccomp = NULL;
269static const struct ssh_kex *kex = NULL;
e055a386 270static const struct ssh_signkey *hostkey = NULL;
65a22376 271static unsigned char ssh2_session_id[20];
57476f6b 272int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
273
274static char *savedhost;
275static int savedport;
276static int ssh_send_ok;
0965bee0 277static int ssh_echoing, ssh_editing;
57476f6b 278
dacbd0e8 279static tree234 *ssh_channels; /* indexed by local id */
57476f6b 280static struct ssh_channel *mainchan; /* primary session channel */
281
282static enum {
3687d221 283 SSH_STATE_PREPACKET,
57476f6b 284 SSH_STATE_BEFORE_SIZE,
285 SSH_STATE_INTERMED,
286 SSH_STATE_SESSION,
287 SSH_STATE_CLOSED
3687d221 288} ssh_state = SSH_STATE_PREPACKET;
57476f6b 289
3687d221 290static int size_needed = FALSE, eof_needed = FALSE;
57476f6b 291
292static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
293static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
b185170a 294static unsigned char *deferred_send_data = NULL;
295static int deferred_len = 0, deferred_size = 0;
57476f6b 296
297static int ssh_version;
298static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
299static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
300static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
301static void ssh_size(void);
3687d221 302static void ssh_special (Telnet_Special);
783415f8 303static void ssh2_try_send(struct ssh_channel *c);
304static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
57476f6b 305
306static int (*s_rdpkt)(unsigned char **data, int *datalen);
307
308static struct rdpkt1_state_tag {
309 long len, pad, biglen, to_read;
310 unsigned long realcrc, gotcrc;
311 unsigned char *p;
312 int i;
313 int chunk;
314} rdpkt1_state;
315
960e736a 316static struct rdpkt2_state_tag {
317 long len, pad, payload, packetlen, maclen;
318 int i;
319 int cipherblk;
320 unsigned long incoming_sequence;
321} rdpkt2_state;
322
dacbd0e8 323static int ssh_channelcmp(void *av, void *bv) {
324 struct ssh_channel *a = (struct ssh_channel *)av;
325 struct ssh_channel *b = (struct ssh_channel *)bv;
326 if (a->localid < b->localid) return -1;
327 if (a->localid > b->localid) return +1;
328 return 0;
329}
330static int ssh_channelfind(void *av, void *bv) {
d211621f 331 unsigned *a = (unsigned *)av;
dacbd0e8 332 struct ssh_channel *b = (struct ssh_channel *)bv;
333 if (*a < b->localid) return -1;
334 if (*a > b->localid) return +1;
335 return 0;
336}
337
374330e2 338static void c_write (char *buf, int len) {
67779be7 339 if ((flags & FLAG_STDERR)) {
4017be6d 340 int i;
341 for (i = 0; i < len; i++)
342 if (buf[i] != '\r')
343 fputc(buf[i], stderr);
fb09bf1c 344 return;
345 }
fe50e814 346 from_backend(1, buf, len);
3bdaf79d 347}
348
1408a877 349static void c_write_str (char *buf) {
350 c_write(buf, strlen(buf));
351}
352
fb09bf1c 353/*
354 * Collect incoming data in the incoming packet buffer.
e5574168 355 * Decipher and verify the packet when it is completely read.
356 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
fb09bf1c 357 * Update the *data and *datalen variables.
358 * Return the additional nr of bytes needed, or 0 when
359 * a complete packet is available.
360 */
e5574168 361static int ssh1_rdpkt(unsigned char **data, int *datalen)
fb09bf1c 362{
57476f6b 363 struct rdpkt1_state_tag *st = &rdpkt1_state;
374330e2 364
365 crBegin;
374330e2 366
fb09bf1c 367next_packet:
37508af4 368
fb09bf1c 369 pktin.type = 0;
370 pktin.length = 0;
374330e2 371
57476f6b 372 for (st->i = st->len = 0; st->i < 4; st->i++) {
fb09bf1c 373 while ((*datalen) == 0)
57476f6b 374 crReturn(4-st->i);
375 st->len = (st->len << 8) + **data;
fb09bf1c 376 (*data)++, (*datalen)--;
377 }
374330e2 378
fb09bf1c 379#ifdef FWHACK
57476f6b 380 if (st->len == 0x52656d6f) { /* "Remo"te server has closed ... */
381 st->len = 0x300; /* big enough to carry to end */
fb09bf1c 382 }
383#endif
374330e2 384
57476f6b 385 st->pad = 8 - (st->len % 8);
386 st->biglen = st->len + st->pad;
387 pktin.length = st->len - 5;
fb09bf1c 388
57476f6b 389 if (pktin.maxlen < st->biglen) {
390 pktin.maxlen = st->biglen;
dcbde236 391 pktin.data = (pktin.data == NULL ? smalloc(st->biglen+APIEXTRA) :
392 srealloc(pktin.data, st->biglen+APIEXTRA));
fb09bf1c 393 if (!pktin.data)
394 fatalbox("Out of memory");
395 }
374330e2 396
57476f6b 397 st->to_read = st->biglen;
398 st->p = pktin.data;
399 while (st->to_read > 0) {
400 st->chunk = st->to_read;
fb09bf1c 401 while ((*datalen) == 0)
57476f6b 402 crReturn(st->to_read);
403 if (st->chunk > (*datalen))
404 st->chunk = (*datalen);
405 memcpy(st->p, *data, st->chunk);
406 *data += st->chunk;
407 *datalen -= st->chunk;
408 st->p += st->chunk;
409 st->to_read -= st->chunk;
fb09bf1c 410 }
374330e2 411
fb09bf1c 412 if (cipher)
57476f6b 413 cipher->decrypt(pktin.data, st->biglen);
698a5108 414#if 0
415 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
416 for (st->i = 0; st->i < st->biglen; st->i++)
417 debug((" %02x", (unsigned char)pktin.data[st->i]));
418 debug(("\r\n"));
419#endif
374330e2 420
57476f6b 421 st->realcrc = crc32(pktin.data, st->biglen-4);
422 st->gotcrc = GET_32BIT(pktin.data+st->biglen-4);
423 if (st->gotcrc != st->realcrc) {
8d5de777 424 bombout(("Incorrect CRC received on packet"));
425 crReturn(0);
fb09bf1c 426 }
572f871e 427
4ba9b64b 428 pktin.body = pktin.data + st->pad + 1;
429
430 if (ssh1_compressing) {
431 unsigned char *decompblk;
432 int decomplen;
433#if 0
434 int i;
435 debug(("Packet payload pre-decompression:\n"));
436 for (i = -1; i < pktin.length; i++)
437 debug((" %02x", (unsigned char)pktin.body[i]));
438 debug(("\r\n"));
439#endif
440 zlib_decompress_block(pktin.body-1, pktin.length+1,
441 &decompblk, &decomplen);
442
443 if (pktin.maxlen < st->pad + decomplen) {
444 pktin.maxlen = st->pad + decomplen;
dcbde236 445 pktin.data = srealloc(pktin.data, pktin.maxlen+APIEXTRA);
58298665 446 pktin.body = pktin.data + st->pad + 1;
4ba9b64b 447 if (!pktin.data)
448 fatalbox("Out of memory");
449 }
450
451 memcpy(pktin.body-1, decompblk, decomplen);
dcbde236 452 sfree(decompblk);
4ba9b64b 453 pktin.length = decomplen-1;
454#if 0
455 debug(("Packet payload post-decompression:\n"));
456 for (i = -1; i < pktin.length; i++)
457 debug((" %02x", (unsigned char)pktin.body[i]));
458 debug(("\r\n"));
459#endif
460 }
461
e5574168 462 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
463 pktin.type == SSH1_SMSG_STDERR_DATA ||
464 pktin.type == SSH1_MSG_DEBUG ||
18515c51 465 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
466 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
fb09bf1c 467 long strlen = GET_32BIT(pktin.body);
8d5de777 468 if (strlen + 4 != pktin.length) {
469 bombout(("Received data packet with bogus string length"));
470 crReturn(0);
471 }
fb09bf1c 472 }
473
4ba9b64b 474 pktin.type = pktin.body[-1];
475
e5574168 476 if (pktin.type == SSH1_MSG_DEBUG) {
fb09bf1c 477 /* log debug message */
478 char buf[80];
479 int strlen = GET_32BIT(pktin.body);
480 strcpy(buf, "Remote: ");
481 if (strlen > 70) strlen = 70;
482 memcpy(buf+8, pktin.body+4, strlen);
483 buf[8+strlen] = '\0';
484 logevent(buf);
485 goto next_packet;
e5574168 486 } else if (pktin.type == SSH1_MSG_IGNORE) {
fb09bf1c 487 /* do nothing */
488 goto next_packet;
489 }
490
491 crFinish(0);
492}
493
e5574168 494static int ssh2_rdpkt(unsigned char **data, int *datalen)
495{
960e736a 496 struct rdpkt2_state_tag *st = &rdpkt2_state;
e5574168 497
498 crBegin;
499
500next_packet:
e5574168 501 pktin.type = 0;
502 pktin.length = 0;
960e736a 503 if (sccipher)
504 st->cipherblk = sccipher->blksize;
e5574168 505 else
960e736a 506 st->cipherblk = 8;
507 if (st->cipherblk < 8)
508 st->cipherblk = 8;
509
510 if (pktin.maxlen < st->cipherblk) {
511 pktin.maxlen = st->cipherblk;
dcbde236 512 pktin.data = (pktin.data == NULL ? smalloc(st->cipherblk+APIEXTRA) :
513 srealloc(pktin.data, st->cipherblk+APIEXTRA));
e5574168 514 if (!pktin.data)
515 fatalbox("Out of memory");
516 }
517
518 /*
519 * Acquire and decrypt the first block of the packet. This will
520 * contain the length and padding details.
521 */
960e736a 522 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
e5574168 523 while ((*datalen) == 0)
960e736a 524 crReturn(st->cipherblk-st->i);
525 pktin.data[st->i] = *(*data)++;
e5574168 526 (*datalen)--;
527 }
528#ifdef FWHACK
529 if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
530 /* FIXME */
531 }
532#endif
533 if (sccipher)
960e736a 534 sccipher->decrypt(pktin.data, st->cipherblk);
e5574168 535
536 /*
537 * Now get the length and padding figures.
538 */
960e736a 539 st->len = GET_32BIT(pktin.data);
540 st->pad = pktin.data[4];
e5574168 541
542 /*
543 * This enables us to deduce the payload length.
544 */
960e736a 545 st->payload = st->len - st->pad - 1;
e5574168 546
960e736a 547 pktin.length = st->payload + 5;
e5574168 548
549 /*
550 * So now we can work out the total packet length.
551 */
960e736a 552 st->packetlen = st->len + 4;
553 st->maclen = scmac ? scmac->len : 0;
e5574168 554
555 /*
556 * Adjust memory allocation if packet is too big.
557 */
960e736a 558 if (pktin.maxlen < st->packetlen+st->maclen) {
559 pktin.maxlen = st->packetlen+st->maclen;
dcbde236 560 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
561 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
e5574168 562 if (!pktin.data)
563 fatalbox("Out of memory");
564 }
565
566 /*
567 * Read and decrypt the remainder of the packet.
568 */
960e736a 569 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen; st->i++) {
e5574168 570 while ((*datalen) == 0)
960e736a 571 crReturn(st->packetlen + st->maclen - st->i);
572 pktin.data[st->i] = *(*data)++;
e5574168 573 (*datalen)--;
574 }
575 /* Decrypt everything _except_ the MAC. */
576 if (sccipher)
960e736a 577 sccipher->decrypt(pktin.data + st->cipherblk,
578 st->packetlen - st->cipherblk);
e5574168 579
7cca0d81 580#if 0
960e736a 581 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
582 for (st->i = 0; st->i < st->packetlen; st->i++)
583 debug((" %02x", (unsigned char)pktin.data[st->i]));
d39f364a 584 debug(("\r\n"));
7cca0d81 585#endif
d39f364a 586
e5574168 587 /*
588 * Check the MAC.
589 */
960e736a 590 if (scmac && !scmac->verify(pktin.data, st->len+4, st->incoming_sequence)) {
8d5de777 591 bombout(("Incorrect MAC received on packet"));
592 crReturn(0);
593 }
960e736a 594 st->incoming_sequence++; /* whether or not we MACed */
e5574168 595
4ba9b64b 596 /*
597 * Decompress packet payload.
598 */
599 {
600 unsigned char *newpayload;
601 int newlen;
602 if (sccomp && sccomp->decompress(pktin.data+5, pktin.length-5,
603 &newpayload, &newlen)) {
604 if (pktin.maxlen < newlen+5) {
605 pktin.maxlen = newlen+5;
dcbde236 606 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
607 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
4ba9b64b 608 if (!pktin.data)
609 fatalbox("Out of memory");
610 }
611 pktin.length = 5 + newlen;
612 memcpy(pktin.data+5, newpayload, newlen);
613#if 0
614 debug(("Post-decompression payload:\r\n"));
615 for (st->i = 0; st->i < newlen; st->i++)
616 debug((" %02x", (unsigned char)pktin.data[5+st->i]));
617 debug(("\r\n"));
618#endif
619
dcbde236 620 sfree(newpayload);
4ba9b64b 621 }
622 }
623
e5574168 624 pktin.savedpos = 6;
625 pktin.type = pktin.data[5];
e5574168 626
7cca0d81 627 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
628 goto next_packet; /* FIXME: print DEBUG message */
e5574168 629
630 crFinish(0);
631}
632
4ba9b64b 633static void ssh1_pktout_size(int len) {
374330e2 634 int pad, biglen;
635
636 len += 5; /* type and CRC */
637 pad = 8 - (len%8);
638 biglen = len + pad;
639
640 pktout.length = len-5;
641 if (pktout.maxlen < biglen) {
642 pktout.maxlen = biglen;
8f203108 643#ifdef MSCRYPTOAPI
fb09bf1c 644 /* Allocate enough buffer space for extra block
8f203108 645 * for MS CryptEncrypt() */
dcbde236 646 pktout.data = (pktout.data == NULL ? smalloc(biglen+12) :
647 srealloc(pktout.data, biglen+12));
8f203108 648#else
dcbde236 649 pktout.data = (pktout.data == NULL ? smalloc(biglen+4) :
650 srealloc(pktout.data, biglen+4));
8f203108 651#endif
374330e2 652 if (!pktout.data)
653 fatalbox("Out of memory");
654 }
4ba9b64b 655 pktout.body = pktout.data+4+pad+1;
656}
374330e2 657
4ba9b64b 658static void s_wrpkt_start(int type, int len) {
659 ssh1_pktout_size(len);
374330e2 660 pktout.type = type;
374330e2 661}
662
39065bed 663static int s_wrpkt_prepare(void) {
374330e2 664 int pad, len, biglen, i;
665 unsigned long crc;
666
4ba9b64b 667 pktout.body[-1] = pktout.type;
668
7d503c31 669#if 0
670 debug(("Packet payload pre-compression:\n"));
671 for (i = -1; i < pktout.length; i++)
672 debug((" %02x", (unsigned char)pktout.body[i]));
673 debug(("\r\n"));
674#endif
675
4ba9b64b 676 if (ssh1_compressing) {
677 unsigned char *compblk;
678 int complen;
4ba9b64b 679 zlib_compress_block(pktout.body-1, pktout.length+1,
680 &compblk, &complen);
681 ssh1_pktout_size(complen-1);
682 memcpy(pktout.body-1, compblk, complen);
dcbde236 683 sfree(compblk);
4ba9b64b 684#if 0
685 debug(("Packet payload post-compression:\n"));
686 for (i = -1; i < pktout.length; i++)
687 debug((" %02x", (unsigned char)pktout.body[i]));
688 debug(("\r\n"));
689#endif
690 }
691
374330e2 692 len = pktout.length + 5; /* type and CRC */
693 pad = 8 - (len%8);
694 biglen = len + pad;
695
374330e2 696 for (i=0; i<pad; i++)
697 pktout.data[i+4] = random_byte();
698 crc = crc32(pktout.data+4, biglen-4);
fb09bf1c 699 PUT_32BIT(pktout.data+biglen, crc);
700 PUT_32BIT(pktout.data, len);
374330e2 701
698a5108 702#if 0
703 debug(("Sending packet len=%d\r\n", biglen+4));
704 for (i = 0; i < biglen+4; i++)
705 debug((" %02x", (unsigned char)pktout.data[i]));
706 debug(("\r\n"));
707#endif
374330e2 708 if (cipher)
709 cipher->encrypt(pktout.data+4, biglen);
710
39065bed 711 return biglen+4;
712}
713
714static void s_wrpkt(void) {
715 int len;
716 len = s_wrpkt_prepare();
717 sk_write(s, pktout.data, len);
718}
719
720static void s_wrpkt_defer(void) {
721 int len;
722 len = s_wrpkt_prepare();
723 if (deferred_len + len > deferred_size) {
724 deferred_size = deferred_len + len + 128;
725 deferred_send_data = srealloc(deferred_send_data, deferred_size);
726 }
727 memcpy(deferred_send_data+deferred_len, pktout.data, len);
728 deferred_len += len;
374330e2 729}
730
fb09bf1c 731/*
39065bed 732 * Construct a packet with the specified contents.
fb09bf1c 733 */
39065bed 734static void construct_packet(int pkttype, va_list ap1, va_list ap2)
fb09bf1c 735{
fb09bf1c 736 unsigned char *p, *argp, argchar;
737 unsigned long argint;
738 int pktlen, argtype, arglen;
7cca0d81 739 Bignum bn;
fb09bf1c 740
741 pktlen = 0;
39065bed 742 while ((argtype = va_arg(ap1, int)) != PKT_END) {
fb09bf1c 743 switch (argtype) {
744 case PKT_INT:
39065bed 745 (void) va_arg(ap1, int);
fb09bf1c 746 pktlen += 4;
747 break;
748 case PKT_CHAR:
39065bed 749 (void) va_arg(ap1, char);
fb09bf1c 750 pktlen++;
751 break;
752 case PKT_DATA:
39065bed 753 (void) va_arg(ap1, unsigned char *);
754 arglen = va_arg(ap1, int);
fb09bf1c 755 pktlen += arglen;
756 break;
757 case PKT_STR:
39065bed 758 argp = va_arg(ap1, unsigned char *);
fb09bf1c 759 arglen = strlen(argp);
760 pktlen += 4 + arglen;
761 break;
7cca0d81 762 case PKT_BIGNUM:
39065bed 763 bn = va_arg(ap1, Bignum);
5c58ad2d 764 pktlen += ssh1_bignum_length(bn);
7cca0d81 765 break;
fb09bf1c 766 default:
767 assert(0);
768 }
769 }
fb09bf1c 770
771 s_wrpkt_start(pkttype, pktlen);
772 p = pktout.body;
773
39065bed 774 while ((argtype = va_arg(ap2, int)) != PKT_END) {
fb09bf1c 775 switch (argtype) {
776 case PKT_INT:
39065bed 777 argint = va_arg(ap2, int);
fb09bf1c 778 PUT_32BIT(p, argint);
779 p += 4;
780 break;
781 case PKT_CHAR:
39065bed 782 argchar = va_arg(ap2, unsigned char);
fb09bf1c 783 *p = argchar;
784 p++;
785 break;
786 case PKT_DATA:
39065bed 787 argp = va_arg(ap2, unsigned char *);
788 arglen = va_arg(ap2, int);
fb09bf1c 789 memcpy(p, argp, arglen);
790 p += arglen;
791 break;
792 case PKT_STR:
39065bed 793 argp = va_arg(ap2, unsigned char *);
fb09bf1c 794 arglen = strlen(argp);
795 PUT_32BIT(p, arglen);
796 memcpy(p + 4, argp, arglen);
797 p += 4 + arglen;
798 break;
7cca0d81 799 case PKT_BIGNUM:
39065bed 800 bn = va_arg(ap2, Bignum);
5c58ad2d 801 p += ssh1_write_bignum(p, bn);
7cca0d81 802 break;
fb09bf1c 803 }
804 }
39065bed 805}
fb09bf1c 806
39065bed 807static void send_packet(int pkttype, ...) {
808 va_list ap1, ap2;
809 va_start(ap1, pkttype);
810 va_start(ap2, pkttype);
811 construct_packet(pkttype, ap1, ap2);
fb09bf1c 812 s_wrpkt();
813}
814
39065bed 815static void defer_packet(int pkttype, ...) {
816 va_list ap1, ap2;
817 va_start(ap1, pkttype);
818 va_start(ap2, pkttype);
819 construct_packet(pkttype, ap1, ap2);
820 s_wrpkt_defer();
821}
822
9697bfd2 823static int ssh_versioncmp(char *a, char *b) {
824 char *ae, *be;
825 unsigned long av, bv;
826
43aa02a7 827 av = strtoul(a, &ae, 10);
828 bv = strtoul(b, &be, 10);
9697bfd2 829 if (av != bv) return (av < bv ? -1 : +1);
830 if (*ae == '.') ae++;
831 if (*be == '.') be++;
43aa02a7 832 av = strtoul(ae, &ae, 10);
833 bv = strtoul(be, &be, 10);
9697bfd2 834 if (av != bv) return (av < bv ? -1 : +1);
835 return 0;
836}
837
e5574168 838
839/*
a92dd380 840 * Utility routines for putting an SSH-protocol `string' and
841 * `uint32' into a SHA state.
e5574168 842 */
843#include <stdio.h>
75cab814 844static void sha_string(SHA_State *s, void *str, int len) {
e5574168 845 unsigned char lenblk[4];
e5574168 846 PUT_32BIT(lenblk, len);
e5574168 847 SHA_Bytes(s, lenblk, 4);
e5574168 848 SHA_Bytes(s, str, len);
849}
850
a92dd380 851static void sha_uint32(SHA_State *s, unsigned i) {
852 unsigned char intblk[4];
853 PUT_32BIT(intblk, i);
854 SHA_Bytes(s, intblk, 4);
855}
856
7cca0d81 857/*
858 * SSH2 packet construction functions.
859 */
783415f8 860static void ssh2_pkt_ensure(int length) {
861 if (pktout.maxlen < length) {
862 pktout.maxlen = length + 256;
dcbde236 863 pktout.data = (pktout.data == NULL ? smalloc(pktout.maxlen+APIEXTRA) :
864 srealloc(pktout.data, pktout.maxlen+APIEXTRA));
7cca0d81 865 if (!pktout.data)
866 fatalbox("Out of memory");
867 }
783415f8 868}
869static void ssh2_pkt_adddata(void *data, int len) {
870 pktout.length += len;
871 ssh2_pkt_ensure(pktout.length);
7cca0d81 872 memcpy(pktout.data+pktout.length-len, data, len);
873}
75cab814 874static void ssh2_pkt_addbyte(unsigned char byte) {
7cca0d81 875 ssh2_pkt_adddata(&byte, 1);
876}
75cab814 877static void ssh2_pkt_init(int pkt_type) {
7cca0d81 878 pktout.length = 5;
879 ssh2_pkt_addbyte((unsigned char)pkt_type);
880}
75cab814 881static void ssh2_pkt_addbool(unsigned char value) {
7cca0d81 882 ssh2_pkt_adddata(&value, 1);
883}
75cab814 884static void ssh2_pkt_adduint32(unsigned long value) {
7cca0d81 885 unsigned char x[4];
886 PUT_32BIT(x, value);
887 ssh2_pkt_adddata(x, 4);
888}
75cab814 889static void ssh2_pkt_addstring_start(void) {
7cca0d81 890 ssh2_pkt_adduint32(0);
891 pktout.savedpos = pktout.length;
892}
75cab814 893static void ssh2_pkt_addstring_str(char *data) {
7cca0d81 894 ssh2_pkt_adddata(data, strlen(data));
895 PUT_32BIT(pktout.data + pktout.savedpos - 4,
896 pktout.length - pktout.savedpos);
897}
75cab814 898static void ssh2_pkt_addstring_data(char *data, int len) {
7cca0d81 899 ssh2_pkt_adddata(data, len);
900 PUT_32BIT(pktout.data + pktout.savedpos - 4,
901 pktout.length - pktout.savedpos);
902}
75cab814 903static void ssh2_pkt_addstring(char *data) {
7cca0d81 904 ssh2_pkt_addstring_start();
905 ssh2_pkt_addstring_str(data);
906}
75cab814 907static char *ssh2_mpint_fmt(Bignum b, int *len) {
7cca0d81 908 unsigned char *p;
3709bfe9 909 int i, n = (ssh1_bignum_bitcount(b)+7)/8;
910 p = smalloc(n + 1);
7cca0d81 911 if (!p)
912 fatalbox("out of memory");
913 p[0] = 0;
3709bfe9 914 for (i = 1; i <= n; i++)
915 p[i] = bignum_byte(b, n-i);
7cca0d81 916 i = 0;
3709bfe9 917 while (i <= n && p[i] == 0 && (p[i+1] & 0x80) == 0)
7cca0d81 918 i++;
3709bfe9 919 memmove(p, p+i, n+1-i);
920 *len = n+1-i;
7cca0d81 921 return p;
922}
75cab814 923static void ssh2_pkt_addmp(Bignum b) {
7cca0d81 924 unsigned char *p;
925 int len;
926 p = ssh2_mpint_fmt(b, &len);
927 ssh2_pkt_addstring_start();
928 ssh2_pkt_addstring_data(p, len);
dcbde236 929 sfree(p);
7cca0d81 930}
b185170a 931
932/*
933 * Construct an SSH2 final-form packet: compress it, encrypt it,
934 * put the MAC on it. Final packet, ready to be sent, is stored in
935 * pktout.data. Total length is returned.
936 */
937static int ssh2_pkt_construct(void) {
7cca0d81 938 int cipherblk, maclen, padding, i;
939 static unsigned long outgoing_sequence = 0;
940
941 /*
4ba9b64b 942 * Compress packet payload.
943 */
944#if 0
945 debug(("Pre-compression payload:\r\n"));
946 for (i = 5; i < pktout.length; i++)
947 debug((" %02x", (unsigned char)pktout.data[i]));
948 debug(("\r\n"));
949#endif
950 {
951 unsigned char *newpayload;
952 int newlen;
953 if (cscomp && cscomp->compress(pktout.data+5, pktout.length-5,
954 &newpayload, &newlen)) {
955 pktout.length = 5;
956 ssh2_pkt_adddata(newpayload, newlen);
dcbde236 957 sfree(newpayload);
4ba9b64b 958 }
959 }
960
961 /*
7cca0d81 962 * Add padding. At least four bytes, and must also bring total
963 * length (minus MAC) up to a multiple of the block size.
964 */
8479e33c 965 cipherblk = cscipher ? cscipher->blksize : 8; /* block size */
7cca0d81 966 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
967 padding = 4;
968 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
783415f8 969 maclen = csmac ? csmac->len : 0;
970 ssh2_pkt_ensure(pktout.length + padding + maclen);
7cca0d81 971 pktout.data[4] = padding;
972 for (i = 0; i < padding; i++)
973 pktout.data[pktout.length + i] = random_byte();
974 PUT_32BIT(pktout.data, pktout.length + padding - 4);
975 if (csmac)
976 csmac->generate(pktout.data, pktout.length + padding,
977 outgoing_sequence);
978 outgoing_sequence++; /* whether or not we MACed */
979
980#if 0
981 debug(("Sending packet len=%d\r\n", pktout.length+padding));
982 for (i = 0; i < pktout.length+padding; i++)
983 debug((" %02x", (unsigned char)pktout.data[i]));
984 debug(("\r\n"));
985#endif
986
987 if (cscipher)
988 cscipher->encrypt(pktout.data, pktout.length + padding);
7cca0d81 989
b185170a 990 /* Ready-to-send packet starts at pktout.data. We return length. */
991 return pktout.length + padding + maclen;
992}
993
994/*
995 * Construct and send an SSH2 packet immediately.
996 */
997static void ssh2_pkt_send(void) {
998 int len = ssh2_pkt_construct();
999 sk_write(s, pktout.data, len);
1000}
1001
1002/*
1003 * Construct an SSH2 packet and add it to a deferred data block.
1004 * Useful for sending multiple packets in a single sk_write() call,
1005 * to prevent a traffic-analysing listener from being able to work
1006 * out the length of any particular packet (such as the password
1007 * packet).
1008 *
1009 * Note that because SSH2 sequence-numbers its packets, this can
1010 * NOT be used as an m4-style `defer' allowing packets to be
1011 * constructed in one order and sent in another.
1012 */
1013static void ssh2_pkt_defer(void) {
1014 int len = ssh2_pkt_construct();
1015 if (deferred_len + len > deferred_size) {
1016 deferred_size = deferred_len + len + 128;
1017 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1018 }
1019 memcpy(deferred_send_data+deferred_len, pktout.data, len);
1020 deferred_len += len;
1021}
1022
1023/*
1024 * Send the whole deferred data block constructed by
39065bed 1025 * ssh2_pkt_defer() or SSH1's defer_packet().
b185170a 1026 */
39065bed 1027static void ssh_pkt_defersend(void) {
b185170a 1028 sk_write(s, deferred_send_data, deferred_len);
1029 deferred_len = deferred_size = 0;
1030 sfree(deferred_send_data);
1031 deferred_send_data = NULL;
7cca0d81 1032}
1033
1034#if 0
1035void bndebug(char *string, Bignum b) {
1036 unsigned char *p;
1037 int i, len;
1038 p = ssh2_mpint_fmt(b, &len);
1039 debug(("%s", string));
1040 for (i = 0; i < len; i++)
1041 debug((" %02x", p[i]));
1042 debug(("\r\n"));
dcbde236 1043 sfree(p);
7cca0d81 1044}
1045#endif
1046
75cab814 1047static void sha_mpint(SHA_State *s, Bignum b) {
7cca0d81 1048 unsigned char *p;
1049 int len;
1050 p = ssh2_mpint_fmt(b, &len);
1051 sha_string(s, p, len);
dcbde236 1052 sfree(p);
7cca0d81 1053}
1054
1055/*
1056 * SSH2 packet decode functions.
1057 */
75cab814 1058static unsigned long ssh2_pkt_getuint32(void) {
7cca0d81 1059 unsigned long value;
1060 if (pktin.length - pktin.savedpos < 4)
1061 return 0; /* arrgh, no way to decline (FIXME?) */
1062 value = GET_32BIT(pktin.data+pktin.savedpos);
1063 pktin.savedpos += 4;
1064 return value;
1065}
65a22376 1066static int ssh2_pkt_getbool(void) {
1067 unsigned long value;
1068 if (pktin.length - pktin.savedpos < 1)
1069 return 0; /* arrgh, no way to decline (FIXME?) */
1070 value = pktin.data[pktin.savedpos] != 0;
1071 pktin.savedpos++;
1072 return value;
1073}
75cab814 1074static void ssh2_pkt_getstring(char **p, int *length) {
7cca0d81 1075 *p = NULL;
1076 if (pktin.length - pktin.savedpos < 4)
1077 return;
1078 *length = GET_32BIT(pktin.data+pktin.savedpos);
1079 pktin.savedpos += 4;
1080 if (pktin.length - pktin.savedpos < *length)
1081 return;
1082 *p = pktin.data+pktin.savedpos;
1083 pktin.savedpos += *length;
1084}
75cab814 1085static Bignum ssh2_pkt_getmp(void) {
7cca0d81 1086 char *p;
3709bfe9 1087 int length;
7cca0d81 1088 Bignum b;
1089
1090 ssh2_pkt_getstring(&p, &length);
1091 if (!p)
1092 return NULL;
8d5de777 1093 if (p[0] & 0x80) {
1094 bombout(("internal error: Can't handle negative mpints"));
1095 return NULL;
1096 }
3709bfe9 1097 b = bignum_from_bytes(p, length);
7cca0d81 1098 return b;
1099}
1100
7d503c31 1101/*
1102 * Examine the remote side's version string and compare it against
1103 * a list of known buggy implementations.
1104 */
1105static void ssh_detect_bugs(char *vstring) {
1106 char *imp; /* pointer to implementation part */
1107 imp = vstring;
1108 imp += strcspn(imp, "-");
1109 imp += strcspn(imp, "-");
1110
1111 ssh_remote_bugs = 0;
1112
1113 if (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1114 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1115 !strcmp(imp, "1.2.22")) {
1116 /*
1117 * These versions don't support SSH1_MSG_IGNORE, so we have
1118 * to use a different defence against password length
1119 * sniffing.
1120 */
1121 ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1122 logevent("We believe remote version has SSH1 ignore bug");
1123 }
1124
1125 if (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1126 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1127 !strncmp(imp, "2.1 ", 4)) {
1128 /*
1129 * These versions have the HMAC bug.
1130 */
1131 ssh_remote_bugs |= BUG_SSH2_HMAC;
1132 logevent("We believe remote version has SSH2 HMAC bug");
1133 }
1134}
1135
8df7a775 1136static int do_ssh_init(unsigned char c) {
1137 static char *vsp;
1138 static char version[10];
1139 static char vstring[80];
1140 static char vlog[sizeof(vstring)+20];
1141 static int i;
374330e2 1142
8df7a775 1143 crBegin;
1144
1145 /* Search for the string "SSH-" in the input. */
374330e2 1146 i = 0;
8df7a775 1147 while (1) {
1148 static const int transS[] = { 1, 2, 2, 1 };
1149 static const int transH[] = { 0, 0, 3, 0 };
1150 static const int transminus[] = { 0, 0, 0, -1 };
1151 if (c == 'S') i = transS[i];
1152 else if (c == 'H') i = transH[i];
1153 else if (c == '-') i = transminus[i];
374330e2 1154 else i = 0;
8df7a775 1155 if (i < 0)
1156 break;
1157 crReturn(1); /* get another character */
374330e2 1158 }
8df7a775 1159
c5e9c988 1160 strcpy(vstring, "SSH-");
1161 vsp = vstring+4;
374330e2 1162 i = 0;
1163 while (1) {
8df7a775 1164 crReturn(1); /* get another char */
c5e9c988 1165 if (vsp < vstring+sizeof(vstring)-1)
1166 *vsp++ = c;
374330e2 1167 if (i >= 0) {
1168 if (c == '-') {
1169 version[i] = '\0';
1170 i = -1;
1171 } else if (i < sizeof(version)-1)
1172 version[i++] = c;
1173 }
1174 else if (c == '\n')
1175 break;
1176 }
1177
db7d555c 1178 ssh_agentfwd_enabled = FALSE;
960e736a 1179 rdpkt2_state.incoming_sequence = 0;
1180
c5e9c988 1181 *vsp = 0;
1182 sprintf(vlog, "Server version: %s", vstring);
7d503c31 1183 ssh_detect_bugs(vstring);
c5e9c988 1184 vlog[strcspn(vlog, "\r\n")] = '\0';
1185 logevent(vlog);
1186
adf799dd 1187 /*
1188 * Server version "1.99" means we can choose whether we use v1
1189 * or v2 protocol. Choice is based on cfg.sshprot.
1190 */
1191 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
e5574168 1192 /*
1193 * This is a v2 server. Begin v2 protocol.
1194 */
1195 char *verstring = "SSH-2.0-PuTTY";
0db56f73 1196 SHA_Init(&exhashbase);
e5574168 1197 /*
1198 * Hash our version string and their version string.
1199 */
0db56f73 1200 sha_string(&exhashbase, verstring, strlen(verstring));
1201 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
e5574168 1202 sprintf(vstring, "%s\n", verstring);
1203 sprintf(vlog, "We claim version: %s", verstring);
1204 logevent(vlog);
1205 logevent("Using SSH protocol version 2");
8df7a775 1206 sk_write(s, vstring, strlen(vstring));
e5574168 1207 ssh_protocol = ssh2_protocol;
6abbf9e3 1208 ssh_version = 2;
e5574168 1209 s_rdpkt = ssh2_rdpkt;
1210 } else {
1211 /*
1212 * This is a v1 server. Begin v1 protocol.
1213 */
1214 sprintf(vstring, "SSH-%s-PuTTY\n",
1215 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1216 sprintf(vlog, "We claim version: %s", vstring);
1217 vlog[strcspn(vlog, "\r\n")] = '\0';
1218 logevent(vlog);
1219 logevent("Using SSH protocol version 1");
8df7a775 1220 sk_write(s, vstring, strlen(vstring));
e5574168 1221 ssh_protocol = ssh1_protocol;
6abbf9e3 1222 ssh_version = 1;
e5574168 1223 s_rdpkt = ssh1_rdpkt;
1224 }
3687d221 1225 ssh_state = SSH_STATE_BEFORE_SIZE;
8df7a775 1226
1227 crFinish(0);
1228}
1229
1230static void ssh_gotdata(unsigned char *data, int datalen)
1231{
1232 crBegin;
1233
1234 /*
1235 * To begin with, feed the characters one by one to the
1236 * protocol initialisation / selection function do_ssh_init().
1237 * When that returns 0, we're done with the initial greeting
1238 * exchange and can move on to packet discipline.
1239 */
1240 while (1) {
1241 int ret;
1242 if (datalen == 0)
1243 crReturnV; /* more data please */
1244 ret = do_ssh_init(*data);
1245 data++; datalen--;
1246 if (ret == 0)
1247 break;
1248 }
1249
1250 /*
1251 * We emerge from that loop when the initial negotiation is
1252 * over and we have selected an s_rdpkt function. Now pass
1253 * everything to s_rdpkt, and then pass the resulting packets
1254 * to the proper protocol handler.
1255 */
1256 if (datalen == 0)
1257 crReturnV;
1258 while (1) {
1259 while (datalen > 0) {
1260 if ( s_rdpkt(&data, &datalen) == 0 ) {
1261 ssh_protocol(NULL, 0, 1);
1262 if (ssh_state == SSH_STATE_CLOSED) {
1263 return;
1264 }
1265 }
1266 }
1267 crReturnV;
1268 }
1269 crFinishV;
1270}
1271
340cf649 1272static int ssh_receive(Socket skt, int urgent, char *data, int len) {
2c94fd1c 1273 if (urgent==3) {
1274 /* A socket error has occurred. */
7dbb9f56 1275 ssh_state = SSH_STATE_CLOSED;
b47b2198 1276 sk_close(s);
7dbb9f56 1277 s = NULL;
2c94fd1c 1278 connection_fatal(data);
b47b2198 1279 return 0;
1280 } else if (!len) {
8df7a775 1281 /* Connection has closed. */
6abb6cd7 1282 ssh_state = SSH_STATE_CLOSED;
8df7a775 1283 sk_close(s);
1284 s = NULL;
1285 return 0;
1286 }
1287 ssh_gotdata (data, len);
3257deae 1288 if (ssh_state == SSH_STATE_CLOSED) {
1289 if (s) {
1290 sk_close(s);
1291 s = NULL;
1292 }
1293 return 0;
1294 }
fef97f43 1295 return 1;
374330e2 1296}
1297
fb09bf1c 1298/*
8df7a775 1299 * Connect to specified host and port.
1300 * Returns an error message, or NULL on success.
1301 * Also places the canonical host name into `realhost'.
1302 */
1303static char *connect_to_host(char *host, int port, char **realhost)
1304{
1305 SockAddr addr;
1306 char *err;
1307#ifdef FWHACK
1308 char *FWhost;
1309 int FWport;
1310#endif
1311
dcbde236 1312 savedhost = smalloc(1+strlen(host));
8df7a775 1313 if (!savedhost)
1314 fatalbox("Out of memory");
1315 strcpy(savedhost, host);
1316
1317 if (port < 0)
1318 port = 22; /* default ssh port */
1319 savedport = port;
1320
1321#ifdef FWHACK
1322 FWhost = host;
1323 FWport = port;
1324 host = FWSTR;
1325 port = 23;
1326#endif
1327
1328 /*
1329 * Try to find host.
1330 */
1331 addr = sk_namelookup(host, realhost);
1332 if ( (err = sk_addr_error(addr)) )
1333 return err;
1334
1335#ifdef FWHACK
1336 *realhost = FWhost;
1337#endif
1338
1339 /*
1340 * Open socket.
1341 */
4b1e8acc 1342 s = sk_new(addr, port, 0, 1, ssh_receive);
8df7a775 1343 if ( (err = sk_socket_error(s)) )
1344 return err;
1345
1346#ifdef FWHACK
1347 sk_write(s, "connect ", 8);
1348 sk_write(s, FWhost, strlen(FWhost));
1349 {
1350 char buf[20];
1351 sprintf(buf, " %d\n", FWport);
1352 sk_write(s, buf, strlen(buf));
1353 }
1354#endif
1355
1356 return NULL;
1357}
1358
1359/*
fb09bf1c 1360 * Handle the key exchange and user authentication phases.
1361 */
e5574168 1362static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
fb09bf1c 1363{
374330e2 1364 int i, j, len;
374330e2 1365 unsigned char *rsabuf, *keystr1, *keystr2;
1366 unsigned char cookie[8];
1367 struct RSAKey servkey, hostkey;
1368 struct MD5Context md5c;
ccbfb941 1369 static unsigned long supported_ciphers_mask, supported_auths_mask;
7cca0d81 1370 static int tried_publickey;
1371 static unsigned char session_id[16];
bea1ef5f 1372 int cipher_type;
b585ec46 1373 static char username[100];
374330e2 1374
374330e2 1375 crBegin;
1376
fb09bf1c 1377 if (!ispkt) crWaitUntil(ispkt);
374330e2 1378
8d5de777 1379 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1380 bombout(("Public key packet not received"));
1381 crReturn(0);
1382 }
374330e2 1383
c5e9c988 1384 logevent("Received public keys");
374330e2 1385
c5e9c988 1386 memcpy(cookie, pktin.body, 8);
374330e2 1387
7cca0d81 1388 i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1389 j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
374330e2 1390
c5e9c988 1391 /*
1c2a93c4 1392 * Log the host key fingerprint.
c5e9c988 1393 */
c5e9c988 1394 {
1395 char logmsg[80];
1c2a93c4 1396 logevent("Host key fingerprint is:");
c5e9c988 1397 strcpy(logmsg, " ");
1c2a93c4 1398 hostkey.comment = NULL;
1399 rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
1400 &hostkey);
c5e9c988 1401 logevent(logmsg);
1402 }
1403
fb09bf1c 1404 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1405 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
bea1ef5f 1406
c5e9c988 1407 MD5Init(&md5c);
374330e2 1408 MD5Update(&md5c, keystr2, hostkey.bytes);
1409 MD5Update(&md5c, keystr1, servkey.bytes);
1410 MD5Update(&md5c, pktin.body, 8);
374330e2 1411 MD5Final(session_id, &md5c);
1412
1413 for (i=0; i<32; i++)
1414 session_key[i] = random_byte();
1415
1416 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1417
dcbde236 1418 rsabuf = smalloc(len);
374330e2 1419 if (!rsabuf)
1420 fatalbox("Out of memory");
1421
89ee5268 1422 /*
1423 * Verify the host key.
1424 */
1425 {
1426 /*
1427 * First format the key into a string.
1428 */
1429 int len = rsastr_len(&hostkey);
d5859615 1430 char fingerprint[100];
dcbde236 1431 char *keystr = smalloc(len);
89ee5268 1432 if (!keystr)
1433 fatalbox("Out of memory");
1434 rsastr_fmt(keystr, &hostkey);
d5859615 1435 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
d4857987 1436 verify_ssh_host_key(savedhost, savedport, "rsa", keystr, fingerprint);
dcbde236 1437 sfree(keystr);
89ee5268 1438 }
374330e2 1439
1440 for (i=0; i<32; i++) {
1441 rsabuf[i] = session_key[i];
1442 if (i < 16)
1443 rsabuf[i] ^= session_id[i];
1444 }
1445
1446 if (hostkey.bytes > servkey.bytes) {
1447 rsaencrypt(rsabuf, 32, &servkey);
1448 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1449 } else {
1450 rsaencrypt(rsabuf, 32, &hostkey);
1451 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1452 }
1453
c5e9c988 1454 logevent("Encrypted session key");
1455
0a3f1d48 1456 switch (cfg.cipher) {
1457 case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH; break;
1458 case CIPHER_DES: cipher_type = SSH_CIPHER_DES; break;
1459 case CIPHER_3DES: cipher_type = SSH_CIPHER_3DES; break;
1460 case CIPHER_AES:
1408a877 1461 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
0a3f1d48 1462 cipher_type = SSH_CIPHER_3DES;
1463 break;
1464 }
bea1ef5f 1465 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1408a877 1466 c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
bea1ef5f 1467 cipher_type = SSH_CIPHER_3DES;
1468 }
c5e9c988 1469 switch (cipher_type) {
1470 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1471 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1472 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1473 }
bea1ef5f 1474
e5574168 1475 send_packet(SSH1_CMSG_SESSION_KEY,
fb09bf1c 1476 PKT_CHAR, cipher_type,
1477 PKT_DATA, cookie, 8,
1478 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1479 PKT_DATA, rsabuf, len,
1480 PKT_INT, 0,
1481 PKT_END);
1482
c5e9c988 1483 logevent("Trying to enable encryption...");
374330e2 1484
dcbde236 1485 sfree(rsabuf);
374330e2 1486
5e8358ad 1487 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
9697bfd2 1488 cipher_type == SSH_CIPHER_DES ? &ssh_des :
bea1ef5f 1489 &ssh_3des;
374330e2 1490 cipher->sesskey(session_key);
1491
fb09bf1c 1492 crWaitUntil(ispkt);
374330e2 1493
8d5de777 1494 if (pktin.type != SSH1_SMSG_SUCCESS) {
1495 bombout(("Encryption not successfully enabled"));
1496 crReturn(0);
1497 }
374330e2 1498
c5e9c988 1499 logevent("Successfully started encryption");
1500
374330e2 1501 fflush(stdout);
1502 {
374330e2 1503 static int pos = 0;
1504 static char c;
67779be7 1505 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1408a877 1506 c_write_str("login as: ");
67779be7 1507 ssh_send_ok = 1;
374330e2 1508 while (pos >= 0) {
fb09bf1c 1509 crWaitUntil(!ispkt);
374330e2 1510 while (inlen--) switch (c = *in++) {
1511 case 10: case 13:
1512 username[pos] = 0;
1513 pos = -1;
1514 break;
1515 case 8: case 127:
1516 if (pos > 0) {
1408a877 1517 c_write_str("\b \b");
374330e2 1518 pos--;
1519 }
1520 break;
1521 case 21: case 27:
1522 while (pos > 0) {
1408a877 1523 c_write_str("\b \b");
374330e2 1524 pos--;
1525 }
1526 break;
1527 case 3: case 4:
1528 random_save_seed();
1529 exit(0);
1530 break;
1531 default:
40d24aa6 1532 if (((c >= ' ' && c <= '~') ||
1533 ((unsigned char)c >= 160)) && pos < 40) {
374330e2 1534 username[pos++] = c;
1535 c_write(&c, 1);
1536 }
1537 break;
1538 }
1539 }
1408a877 1540 c_write_str("\r\n");
374330e2 1541 username[strcspn(username, "\n\r")] = '\0';
1542 } else {
374330e2 1543 strncpy(username, cfg.username, 99);
1544 username[99] = '\0';
374330e2 1545 }
fb09bf1c 1546
e5574168 1547 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
c5e9c988 1548 {
3c8e959b 1549 char userlog[22+sizeof(username)];
c5e9c988 1550 sprintf(userlog, "Sent username \"%s\"", username);
1551 logevent(userlog);
3c8e959b 1552 if (flags & FLAG_INTERACTIVE &&
1553 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
1554 strcat(userlog, "\r\n");
1408a877 1555 c_write_str(userlog);
3c8e959b 1556 }
c5e9c988 1557 }
374330e2 1558 }
1559
fb09bf1c 1560 crWaitUntil(ispkt);
374330e2 1561
7cca0d81 1562 tried_publickey = 0;
1563
e5574168 1564 while (pktin.type == SSH1_SMSG_FAILURE) {
374330e2 1565 static char password[100];
a52f067e 1566 static char prompt[200];
374330e2 1567 static int pos;
1568 static char c;
ccbfb941 1569 static int pwpkt_type;
ccbfb941 1570 /*
1571 * Show password prompt, having first obtained it via a TIS
18515c51 1572 * or CryptoCard exchange if we're doing TIS or CryptoCard
1573 * authentication.
ccbfb941 1574 */
e5574168 1575 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
5c58ad2d 1576 if (agent_exists()) {
1577 /*
1578 * Attempt RSA authentication using Pageant.
1579 */
1580 static unsigned char request[5], *response, *p;
1581 static int responselen;
1582 static int i, nkeys;
1583 static int authed = FALSE;
1584 void *r;
1585
1586 logevent("Pageant is running. Requesting keys.");
1587
1588 /* Request the keys held by the agent. */
1589 PUT_32BIT(request, 1);
1983e559 1590 request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
5c58ad2d 1591 agent_query(request, 5, &r, &responselen);
1592 response = (unsigned char *)r;
1593 if (response) {
1594 p = response + 5;
1595 nkeys = GET_32BIT(p); p += 4;
6328ea7a 1596 { char buf[64]; sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
5c58ad2d 1597 logevent(buf); }
1598 for (i = 0; i < nkeys; i++) {
1599 static struct RSAKey key;
1600 static Bignum challenge;
b8bb811a 1601 static char *commentp;
1602 static int commentlen;
5c58ad2d 1603
1604 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1605 logevent(buf); }
1606 p += 4;
1607 p += ssh1_read_bignum(p, &key.exponent);
1608 p += ssh1_read_bignum(p, &key.modulus);
b8bb811a 1609 commentlen = GET_32BIT(p); p += 4;
1610 commentp = p; p += commentlen;
5c58ad2d 1611 send_packet(SSH1_CMSG_AUTH_RSA,
1612 PKT_BIGNUM, key.modulus, PKT_END);
1613 crWaitUntil(ispkt);
1614 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1615 logevent("Key refused");
1616 continue;
1617 }
1618 logevent("Received RSA challenge");
1619 ssh1_read_bignum(pktin.body, &challenge);
1620 {
1621 char *agentreq, *q, *ret;
1622 int len, retlen;
1623 len = 1 + 4; /* message type, bit count */
1624 len += ssh1_bignum_length(key.exponent);
1625 len += ssh1_bignum_length(key.modulus);
1626 len += ssh1_bignum_length(challenge);
1627 len += 16; /* session id */
1628 len += 4; /* response format */
dcbde236 1629 agentreq = smalloc(4 + len);
5c58ad2d 1630 PUT_32BIT(agentreq, len);
1631 q = agentreq + 4;
1983e559 1632 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
5c58ad2d 1633 PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1634 q += 4;
1635 q += ssh1_write_bignum(q, key.exponent);
1636 q += ssh1_write_bignum(q, key.modulus);
1637 q += ssh1_write_bignum(q, challenge);
1638 memcpy(q, session_id, 16); q += 16;
1639 PUT_32BIT(q, 1); /* response format */
1640 agent_query(agentreq, len+4, &ret, &retlen);
dcbde236 1641 sfree(agentreq);
5c58ad2d 1642 if (ret) {
1983e559 1643 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
5c58ad2d 1644 logevent("Sending Pageant's response");
1645 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1646 PKT_DATA, ret+5, 16, PKT_END);
dcbde236 1647 sfree(ret);
5c58ad2d 1648 crWaitUntil(ispkt);
1649 if (pktin.type == SSH1_SMSG_SUCCESS) {
1650 logevent("Pageant's response accepted");
c4fa2fce 1651 if (flags & FLAG_VERBOSE) {
1408a877 1652 c_write_str("Authenticated using RSA key \"");
c4fa2fce 1653 c_write(commentp, commentlen);
1408a877 1654 c_write_str("\" from agent\r\n");
c4fa2fce 1655 }
5c58ad2d 1656 authed = TRUE;
1657 } else
1658 logevent("Pageant's response not accepted");
1659 } else {
1660 logevent("Pageant failed to answer challenge");
dcbde236 1661 sfree(ret);
5c58ad2d 1662 }
1663 } else {
1664 logevent("No reply received from Pageant");
1665 }
1666 }
1667 freebn(key.exponent);
1668 freebn(key.modulus);
1669 freebn(challenge);
1670 if (authed)
1671 break;
1672 }
1673 }
1674 if (authed)
1675 break;
1676 }
7cca0d81 1677 if (*cfg.keyfile && !tried_publickey)
1678 pwpkt_type = SSH1_CMSG_AUTH_RSA;
fb09bf1c 1679
a52f067e 1680 if (pktin.type == SSH1_SMSG_FAILURE &&
1681 cfg.try_tis_auth &&
1682 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1683 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1684 logevent("Requested TIS authentication");
1685 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1686 crWaitUntil(ispkt);
1687 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1688 logevent("TIS authentication declined");
1689 if (flags & FLAG_INTERACTIVE)
1408a877 1690 c_write_str("TIS authentication refused.\r\n");
a52f067e 1691 } else {
1692 int challengelen = ((pktin.body[0] << 24) |
1693 (pktin.body[1] << 16) |
1694 (pktin.body[2] << 8) |
1695 (pktin.body[3]));
1696 logevent("Received TIS challenge");
1697 if (challengelen > sizeof(prompt)-1)
1698 challengelen = sizeof(prompt)-1; /* prevent overrun */
1699 memcpy(prompt, pktin.body+4, challengelen);
1700 prompt[challengelen] = '\0';
1701 }
1702 }
1703 if (pktin.type == SSH1_SMSG_FAILURE &&
1704 cfg.try_tis_auth &&
1705 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1706 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1707 logevent("Requested CryptoCard authentication");
1708 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1709 crWaitUntil(ispkt);
1710 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1711 logevent("CryptoCard authentication declined");
1408a877 1712 c_write_str("CryptoCard authentication refused.\r\n");
a52f067e 1713 } else {
1714 int challengelen = ((pktin.body[0] << 24) |
1715 (pktin.body[1] << 16) |
1716 (pktin.body[2] << 8) |
1717 (pktin.body[3]));
1718 logevent("Received CryptoCard challenge");
1719 if (challengelen > sizeof(prompt)-1)
1720 challengelen = sizeof(prompt)-1; /* prevent overrun */
1721 memcpy(prompt, pktin.body+4, challengelen);
1722 strncpy(prompt + challengelen, "\r\nResponse : ",
1723 sizeof(prompt)-challengelen);
1724 prompt[sizeof(prompt)-1] = '\0';
1725 }
1726 }
1727 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1728 sprintf(prompt, "%.90s@%.90s's password: ",
b585ec46 1729 username, savedhost);
a52f067e 1730 }
1731 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1732 char *comment = NULL;
1733 if (flags & FLAG_VERBOSE)
1408a877 1734 c_write_str("Trying public key authentication.\r\n");
a52f067e 1735 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1736 if (flags & FLAG_VERBOSE)
1408a877 1737 c_write_str("No passphrase required.\r\n");
a52f067e 1738 goto tryauth;
1739 }
1740 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
dcbde236 1741 sfree(comment);
a52f067e 1742 }
1743
d8426c54 1744 if (ssh_get_password) {
85ee8208 1745 if (!ssh_get_password(prompt, password, sizeof(password))) {
1746 /*
1747 * get_password failed to get a password (for
1748 * example because one was supplied on the command
1749 * line which has already failed to work).
1750 * Terminate.
1751 */
1752 logevent("No more passwords to try");
1753 ssh_state = SSH_STATE_CLOSED;
1754 crReturn(1);
1755 }
fb09bf1c 1756 } else {
1408a877 1757 c_write_str(prompt);
7cca0d81 1758 pos = 0;
67779be7 1759 ssh_send_ok = 1;
7cca0d81 1760 while (pos >= 0) {
1761 crWaitUntil(!ispkt);
1762 while (inlen--) switch (c = *in++) {
1763 case 10: case 13:
1764 password[pos] = 0;
1765 pos = -1;
1766 break;
1767 case 8: case 127:
1768 if (pos > 0)
1769 pos--;
1770 break;
1771 case 21: case 27:
1772 pos = 0;
1773 break;
1774 case 3: case 4:
1775 random_save_seed();
1776 exit(0);
1777 break;
1778 default:
1779 if (((c >= ' ' && c <= '~') ||
1780 ((unsigned char)c >= 160)) && pos < sizeof(password))
1781 password[pos++] = c;
1782 break;
1783 }
1784 }
1408a877 1785 c_write_str("\r\n");
a52f067e 1786 }
fb09bf1c 1787
7cca0d81 1788 tryauth:
1789 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1790 /*
1791 * Try public key authentication with the specified
1792 * key file.
1793 */
1794 static struct RSAKey pubkey;
1795 static Bignum challenge, response;
1796 static int i;
1797 static unsigned char buffer[32];
1798
1799 tried_publickey = 1;
65a22376 1800 i = loadrsakey(cfg.keyfile, &pubkey, password);
7cca0d81 1801 if (i == 0) {
1408a877 1802 c_write_str("Couldn't load public key from ");
1803 c_write_str(cfg.keyfile);
1804 c_write_str(".\r\n");
7cca0d81 1805 continue; /* go and try password */
1806 }
1807 if (i == -1) {
1408a877 1808 c_write_str("Wrong passphrase.\r\n");
7cca0d81 1809 tried_publickey = 0;
1810 continue; /* try again */
1811 }
1812
1813 /*
1814 * Send a public key attempt.
1815 */
1816 send_packet(SSH1_CMSG_AUTH_RSA,
1817 PKT_BIGNUM, pubkey.modulus, PKT_END);
1818
1819 crWaitUntil(ispkt);
1820 if (pktin.type == SSH1_SMSG_FAILURE) {
1408a877 1821 c_write_str("Server refused our public key.\r\n");
7cca0d81 1822 continue; /* go and try password */
1823 }
8d5de777 1824 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1825 bombout(("Bizarre response to offer of public key"));
1826 crReturn(0);
1827 }
7cca0d81 1828 ssh1_read_bignum(pktin.body, &challenge);
1829 response = rsadecrypt(challenge, &pubkey);
1830 freebn(pubkey.private_exponent); /* burn the evidence */
1831
3709bfe9 1832 for (i = 0; i < 32; i++) {
1833 buffer[i] = bignum_byte(response, 31-i);
7cca0d81 1834 }
1835
1836 MD5Init(&md5c);
1837 MD5Update(&md5c, buffer, 32);
1838 MD5Update(&md5c, session_id, 16);
1839 MD5Final(buffer, &md5c);
1840
1841 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1842 PKT_DATA, buffer, 16, PKT_END);
1843
1844 crWaitUntil(ispkt);
1845 if (pktin.type == SSH1_SMSG_FAILURE) {
4017be6d 1846 if (flags & FLAG_VERBOSE)
1408a877 1847 c_write_str("Failed to authenticate with our public key.\r\n");
7cca0d81 1848 continue; /* go and try password */
1849 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
8d5de777 1850 bombout(("Bizarre response to RSA authentication response"));
1851 crReturn(0);
7cca0d81 1852 }
1853
1854 break; /* we're through! */
1855 } else {
39065bed 1856 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1857 /*
1858 * Defence against traffic analysis: we send a
1859 * whole bunch of packets containing strings of
1860 * different lengths. One of these strings is the
1861 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
1862 * The others are all random data in
1863 * SSH1_MSG_IGNORE packets. This way a passive
1864 * listener can't tell which is the password, and
1865 * hence can't deduce the password length.
1866 *
1867 * Anybody with a password length greater than 16
1868 * bytes is going to have enough entropy in their
1869 * password that a listener won't find it _that_
1870 * much help to know how long it is. So what we'll
1871 * do is:
1872 *
1873 * - if password length < 16, we send 15 packets
1874 * containing string lengths 1 through 15
1875 *
1876 * - otherwise, we let N be the nearest multiple
1877 * of 8 below the password length, and send 8
1878 * packets containing string lengths N through
1879 * N+7. This won't obscure the order of
1880 * magnitude of the password length, but it will
1881 * introduce a bit of extra uncertainty.
7d503c31 1882 *
1883 * A few servers (the old 1.2.18 through 1.2.22)
1884 * can't deal with SSH1_MSG_IGNORE. For these
1885 * servers, we need an alternative defence. We make
1886 * use of the fact that the password is interpreted
1887 * as a C string: so we can append a NUL, then some
1888 * random data.
39065bed 1889 */
7d503c31 1890 if (ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) {
1891 char string[64];
1892 char *s;
1893 int len;
1894
1895 len = strlen(password);
1896 if (len < sizeof(string)) {
1897 s = string;
1898 strcpy(string, password);
1899 len++; /* cover the zero byte */
1900 while (len < sizeof(string)) {
1901 string[len++] = (char)random_byte();
1902 }
1903 } else {
1904 s = password;
1905 }
1906 send_packet(pwpkt_type, PKT_INT, len,
1907 PKT_DATA, s, len, PKT_END);
39065bed 1908 } else {
7d503c31 1909 int bottom, top, pwlen, i;
1910 char *randomstr;
1911
1912 pwlen = strlen(password);
1913 if (pwlen < 16) {
1914 bottom = 1;
1915 top = 15;
1916 } else {
1917 bottom = pwlen &~ 7;
1918 top = bottom + 7;
1919 }
39065bed 1920
7d503c31 1921 assert(pwlen >= bottom && pwlen <= top);
39065bed 1922
7d503c31 1923 randomstr = smalloc(top+1);
39065bed 1924
7d503c31 1925 for (i = bottom; i <= top; i++) {
1926 if (i == pwlen)
1927 defer_packet(pwpkt_type, PKT_STR, password, PKT_END);
1928 else {
1929 for (j = 0; j < i; j++) {
1930 do {
1931 randomstr[j] = random_byte();
1932 } while (randomstr[j] == '\0');
1933 }
1934 randomstr[i] = '\0';
1935 defer_packet(SSH1_MSG_IGNORE,
1936 PKT_STR, randomstr, PKT_END);
39065bed 1937 }
39065bed 1938 }
7d503c31 1939 ssh_pkt_defersend();
39065bed 1940 }
39065bed 1941 } else {
1942 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1943 }
7cca0d81 1944 }
c5e9c988 1945 logevent("Sent password");
374330e2 1946 memset(password, 0, strlen(password));
fb09bf1c 1947 crWaitUntil(ispkt);
e5574168 1948 if (pktin.type == SSH1_SMSG_FAILURE) {
4017be6d 1949 if (flags & FLAG_VERBOSE)
1408a877 1950 c_write_str("Access denied\r\n");
c5e9c988 1951 logevent("Authentication refused");
e5574168 1952 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
fb09bf1c 1953 logevent("Received disconnect request");
85ee8208 1954 ssh_state = SSH_STATE_CLOSED;
1955 crReturn(1);
e5574168 1956 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
8d5de777 1957 bombout(("Strange packet received, type %d", pktin.type));
1958 crReturn(0);
374330e2 1959 }
1960 }
1961
c5e9c988 1962 logevent("Authentication successful");
1963
fb09bf1c 1964 crFinish(1);
1965}
1966
9c964e85 1967void sshfwd_close(struct ssh_channel *c) {
783415f8 1968 if (c) {
1969 if (ssh_version == 1) {
1970 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END);
1971 } else {
1972 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
1973 ssh2_pkt_adduint32(c->remoteid);
1974 ssh2_pkt_send();
1975 }
1976 c->closes = 1;
1977 if (c->type == CHAN_X11) {
1978 c->u.x11.s = NULL;
1979 logevent("X11 connection terminated");
1980 }
1981 }
9c964e85 1982}
1983
1984void sshfwd_write(struct ssh_channel *c, char *buf, int len) {
783415f8 1985 if (ssh_version == 1) {
1986 send_packet(SSH1_MSG_CHANNEL_DATA,
1987 PKT_INT, c->remoteid,
1988 PKT_INT, len,
1989 PKT_DATA, buf, len,
1990 PKT_END);
1991 } else {
1992 ssh2_add_channel_data(c, buf, len);
1993 ssh2_try_send(c);
1994 }
9c964e85 1995}
1996
e5574168 1997static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
fb09bf1c 1998 crBegin;
1999
2000 random_init();
2001
e5574168 2002 while (!do_ssh1_login(in, inlen, ispkt)) {
fb09bf1c 2003 crReturnV;
85ee8208 2004 }
2005 if (ssh_state == SSH_STATE_CLOSED)
2006 crReturnV;
fb09bf1c 2007
979310f1 2008 if (cfg.agentfwd && agent_exists()) {
dacbd0e8 2009 logevent("Requesting agent forwarding");
2010 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2011 do { crReturnV; } while (!ispkt);
2012 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
8d5de777 2013 bombout(("Protocol confusion"));
2014 crReturnV;
dacbd0e8 2015 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2016 logevent("Agent forwarding refused");
db7d555c 2017 } else {
dacbd0e8 2018 logevent("Agent forwarding enabled");
db7d555c 2019 ssh_agentfwd_enabled = TRUE;
2020 }
dacbd0e8 2021 }
2022
9c964e85 2023 if (cfg.x11_forward) {
2024 char proto[20], data[64];
2025 logevent("Requesting X11 forwarding");
2026 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2027 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2028 PKT_STR, proto, PKT_STR, data,
2029 PKT_INT, 0,
2030 PKT_END);
2031 do { crReturnV; } while (!ispkt);
2032 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2033 bombout(("Protocol confusion"));
2034 crReturnV;
2035 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2036 logevent("X11 forwarding refused");
2037 } else {
2038 logevent("X11 forwarding enabled");
2039 ssh_X11_fwd_enabled = TRUE;
2040 }
2041 }
2042
fef97f43 2043 if (!cfg.nopty) {
e5574168 2044 send_packet(SSH1_CMSG_REQUEST_PTY,
fb09bf1c 2045 PKT_STR, cfg.termtype,
2046 PKT_INT, rows, PKT_INT, cols,
2047 PKT_INT, 0, PKT_INT, 0,
2048 PKT_CHAR, 0,
2049 PKT_END);
fef97f43 2050 ssh_state = SSH_STATE_INTERMED;
2051 do { crReturnV; } while (!ispkt);
e5574168 2052 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
8d5de777 2053 bombout(("Protocol confusion"));
2054 crReturnV;
e5574168 2055 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1408a877 2056 c_write_str("Server refused to allocate pty\r\n");
0965bee0 2057 ssh_editing = ssh_echoing = 1;
fef97f43 2058 }
c5e9c988 2059 logevent("Allocated pty");
0965bee0 2060 } else {
2061 ssh_editing = ssh_echoing = 1;
374330e2 2062 }
2063
4ba9b64b 2064 if (cfg.compression) {
2065 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
2066 do { crReturnV; } while (!ispkt);
2067 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2068 bombout(("Protocol confusion"));
2069 crReturnV;
2070 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1408a877 2071 c_write_str("Server refused to compress\r\n");
4ba9b64b 2072 }
2073 logevent("Started compression");
2074 ssh1_compressing = TRUE;
2075 zlib_compress_init();
2076 zlib_decompress_init();
2077 }
2078
6abbf9e3 2079 if (*cfg.remote_cmd)
2080 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
2081 else
2082 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
c5e9c988 2083 logevent("Started session");
374330e2 2084
2085 ssh_state = SSH_STATE_SESSION;
2086 if (size_needed)
2087 ssh_size();
3687d221 2088 if (eof_needed)
2089 ssh_special(TS_EOF);
374330e2 2090
0965bee0 2091 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
8ccc75b0 2092 ssh_send_ok = 1;
dacbd0e8 2093 ssh_channels = newtree234(ssh_channelcmp);
374330e2 2094 while (1) {
2095 crReturnV;
2096 if (ispkt) {
e5574168 2097 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
2098 pktin.type == SSH1_SMSG_STDERR_DATA) {
fb09bf1c 2099 long len = GET_32BIT(pktin.body);
fe50e814 2100 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
2101 pktin.body+4, len);
e5574168 2102 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
21248260 2103 ssh_state = SSH_STATE_CLOSED;
c5e9c988 2104 logevent("Received disconnect request");
3257deae 2105 crReturnV;
9c964e85 2106 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
2107 /* Remote side is trying to open a channel to talk to our
2108 * X-Server. Give them back a local channel number. */
2109 unsigned i;
2110 struct ssh_channel *c, *d;
2111 enum234 e;
2112
2113 logevent("Received X11 connect request");
2114 /* Refuse if X11 forwarding is disabled. */
2115 if (!ssh_X11_fwd_enabled) {
2116 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2117 PKT_INT, GET_32BIT(pktin.body),
2118 PKT_END);
2119 logevent("Rejected X11 connect request");
2120 } else {
9c964e85 2121 c = smalloc(sizeof(struct ssh_channel));
2122
0c6c9a70 2123 if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
9c964e85 2124 logevent("opening X11 forward connection failed");
2125 sfree(c);
2126 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2127 PKT_INT, GET_32BIT(pktin.body),
2128 PKT_END);
2129 } else {
2130 logevent("opening X11 forward connection succeeded");
2131 for (i=1, d = first234(ssh_channels, &e); d; d = next234(&e)) {
783415f8 2132 if (d->localid > i)
2133 break; /* found a free number */
2134 i = d->localid + 1;
9c964e85 2135 }
2136 c->remoteid = GET_32BIT(pktin.body);
2137 c->localid = i;
2138 c->closes = 0;
783415f8 2139 c->type = CHAN_X11; /* identify channel type */
9c964e85 2140 add234(ssh_channels, c);
2141 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2142 PKT_INT, c->remoteid, PKT_INT, c->localid,
2143 PKT_END);
2144 logevent("Opened X11 forward channel");
2145 }
2146 }
dacbd0e8 2147 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
2148 /* Remote side is trying to open a channel to talk to our
2149 * agent. Give them back a local channel number. */
db7d555c 2150 unsigned i;
dacbd0e8 2151 struct ssh_channel *c;
2152 enum234 e;
db7d555c 2153
2154 /* Refuse if agent forwarding is disabled. */
2155 if (!ssh_agentfwd_enabled) {
2156 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2157 PKT_INT, GET_32BIT(pktin.body),
2158 PKT_END);
2159 } else {
2160 i = 1;
2161 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
2162 if (c->localid > i)
2163 break; /* found a free number */
2164 i = c->localid + 1;
2165 }
dcbde236 2166 c = smalloc(sizeof(struct ssh_channel));
db7d555c 2167 c->remoteid = GET_32BIT(pktin.body);
2168 c->localid = i;
2169 c->closes = 0;
783415f8 2170 c->type = CHAN_AGENT; /* identify channel type */
db7d555c 2171 c->u.a.lensofar = 0;
2172 add234(ssh_channels, c);
2173 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2174 PKT_INT, c->remoteid, PKT_INT, c->localid,
2175 PKT_END);
2176 }
2177 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2178 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
dacbd0e8 2179 /* Remote side closes a channel. */
d211621f 2180 unsigned i = GET_32BIT(pktin.body);
dacbd0e8 2181 struct ssh_channel *c;
2182 c = find234(ssh_channels, &i, ssh_channelfind);
2183 if (c) {
2184 int closetype;
2185 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2186 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
783415f8 2187 if ((c->closes == 0) && (c->type == CHAN_X11)) {
9c964e85 2188 logevent("X11 connection closed");
2189 assert(c->u.x11.s != NULL);
2190 x11_close(c->u.x11.s);
2191 c->u.x11.s = NULL;
2192 }
dacbd0e8 2193 c->closes |= closetype;
2194 if (c->closes == 3) {
2195 del234(ssh_channels, c);
dcbde236 2196 sfree(c);
dacbd0e8 2197 }
2198 }
2199 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2200 /* Data sent down one of our channels. */
2201 int i = GET_32BIT(pktin.body);
2202 int len = GET_32BIT(pktin.body+4);
2203 unsigned char *p = pktin.body+8;
2204 struct ssh_channel *c;
2205 c = find234(ssh_channels, &i, ssh_channelfind);
2206 if (c) {
2207 switch(c->type) {
783415f8 2208 case CHAN_X11:
9c964e85 2209 x11_send(c->u.x11.s, p, len);
2210 break;
783415f8 2211 case CHAN_AGENT:
dacbd0e8 2212 /* Data for an agent message. Buffer it. */
2213 while (len > 0) {
2214 if (c->u.a.lensofar < 4) {
2215 int l = min(4 - c->u.a.lensofar, len);
2216 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
2217 p += l; len -= l; c->u.a.lensofar += l;
2218 }
2219 if (c->u.a.lensofar == 4) {
2220 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
dcbde236 2221 c->u.a.message = smalloc(c->u.a.totallen);
dacbd0e8 2222 memcpy(c->u.a.message, c->u.a.msglen, 4);
2223 }
2224 if (c->u.a.lensofar >= 4 && len > 0) {
2225 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
2226 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
2227 p += l; len -= l; c->u.a.lensofar += l;
2228 }
2229 if (c->u.a.lensofar == c->u.a.totallen) {
2230 void *reply, *sentreply;
2231 int replylen;
2232 agent_query(c->u.a.message, c->u.a.totallen,
2233 &reply, &replylen);
2234 if (reply)
2235 sentreply = reply;
2236 else {
2237 /* Fake SSH_AGENT_FAILURE. */
2238 sentreply = "\0\0\0\1\5";
2239 replylen = 5;
2240 }
2241 send_packet(SSH1_MSG_CHANNEL_DATA,
2242 PKT_INT, c->remoteid,
2243 PKT_INT, replylen,
2244 PKT_DATA, sentreply, replylen,
2245 PKT_END);
2246 if (reply)
dcbde236 2247 sfree(reply);
2248 sfree(c->u.a.message);
dacbd0e8 2249 c->u.a.lensofar = 0;
2250 }
2251 }
2252 break;
2253 }
2254 }
e5574168 2255 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
972a41c8 2256 /* may be from EXEC_SHELL on some servers */
e5574168 2257 } else if (pktin.type == SSH1_SMSG_FAILURE) {
972a41c8 2258 /* may be from EXEC_SHELL on some servers
374330e2 2259 * if no pty is available or in other odd cases. Ignore */
e5574168 2260 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2261 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
374330e2 2262 } else {
8d5de777 2263 bombout(("Strange packet received: type %d", pktin.type));
2264 crReturnV;
374330e2 2265 }
2266 } else {
8df7a775 2267 while (inlen > 0) {
2268 int len = min(inlen, 512);
2269 send_packet(SSH1_CMSG_STDIN_DATA,
2270 PKT_INT, len, PKT_DATA, in, len, PKT_END);
2271 in += len;
2272 inlen -= len;
2273 }
374330e2 2274 }
2275 }
2276
2277 crFinishV;
2278}
2279
2280/*
e5574168 2281 * Utility routine for decoding comma-separated strings in KEXINIT.
2282 */
75cab814 2283static int in_commasep_string(char *needle, char *haystack, int haylen) {
e5574168 2284 int needlen = strlen(needle);
2285 while (1) {
2286 /*
2287 * Is it at the start of the string?
2288 */
2289 if (haylen >= needlen && /* haystack is long enough */
2290 !memcmp(needle, haystack, needlen) && /* initial match */
2291 (haylen == needlen || haystack[needlen] == ',')
2292 /* either , or EOS follows */
2293 )
2294 return 1;
2295 /*
2296 * If not, search for the next comma and resume after that.
2297 * If no comma found, terminate.
2298 */
2299 while (haylen > 0 && *haystack != ',')
2300 haylen--, haystack++;
2301 if (haylen == 0)
2302 return 0;
2303 haylen--, haystack++; /* skip over comma itself */
2304 }
2305}
2306
2307/*
d39f364a 2308 * SSH2 key creation method.
2309 */
5e0d7cb8 2310static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr, char *keyspace) {
d39f364a 2311 SHA_State s;
2312 /* First 20 bytes. */
2313 SHA_Init(&s);
2314 sha_mpint(&s, K);
2315 SHA_Bytes(&s, H, 20);
2316 SHA_Bytes(&s, &chr, 1);
5e0d7cb8 2317 SHA_Bytes(&s, sessid, 20);
d39f364a 2318 SHA_Final(&s, keyspace);
2319 /* Next 20 bytes. */
2320 SHA_Init(&s);
2321 sha_mpint(&s, K);
2322 SHA_Bytes(&s, H, 20);
2323 SHA_Bytes(&s, keyspace, 20);
2324 SHA_Final(&s, keyspace+20);
2325}
2326
2327/*
7cca0d81 2328 * Handle the SSH2 transport layer.
e5574168 2329 */
7cca0d81 2330static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
e5574168 2331{
0a3f1d48 2332 static int i, j, len, nbits;
e5574168 2333 static char *str;
a92dd380 2334 static Bignum p, g, e, f, K;
2335 static int kex_init_value, kex_reply_value;
7591b9ff 2336 static const struct ssh_mac **maclist;
8b2715b2 2337 static int nmacs;
0a3f1d48 2338 static const struct ssh2_cipher *cscipher_tobe = NULL;
2339 static const struct ssh2_cipher *sccipher_tobe = NULL;
57476f6b 2340 static const struct ssh_mac *csmac_tobe = NULL;
2341 static const struct ssh_mac *scmac_tobe = NULL;
2342 static const struct ssh_compress *cscomp_tobe = NULL;
2343 static const struct ssh_compress *sccomp_tobe = NULL;
d5859615 2344 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
e5574168 2345 static int hostkeylen, siglen;
e055a386 2346 static void *hkey; /* actual host key */
e5574168 2347 static unsigned char exchange_hash[20];
d39f364a 2348 static unsigned char keyspace[40];
0a3f1d48 2349 static const struct ssh2_ciphers *preferred_cipher;
4ba9b64b 2350 static const struct ssh_compress *preferred_comp;
0db56f73 2351 static int first_kex;
e5574168 2352
2353 crBegin;
7cca0d81 2354 random_init();
0db56f73 2355 first_kex = 1;
e5574168 2356
5e8358ad 2357 /*
4ba9b64b 2358 * Set up the preferred cipher and compression.
5e8358ad 2359 */
2360 if (cfg.cipher == CIPHER_BLOWFISH) {
0a3f1d48 2361 preferred_cipher = &ssh2_blowfish;
5e8358ad 2362 } else if (cfg.cipher == CIPHER_DES) {
2363 logevent("Single DES not supported in SSH2; using 3DES");
0a3f1d48 2364 preferred_cipher = &ssh2_3des;
5e8358ad 2365 } else if (cfg.cipher == CIPHER_3DES) {
0a3f1d48 2366 preferred_cipher = &ssh2_3des;
2367 } else if (cfg.cipher == CIPHER_AES) {
2368 preferred_cipher = &ssh2_aes;
5e8358ad 2369 } else {
2370 /* Shouldn't happen, but we do want to initialise to _something_. */
0a3f1d48 2371 preferred_cipher = &ssh2_3des;
5e8358ad 2372 }
4ba9b64b 2373 if (cfg.compression)
2374 preferred_comp = &ssh_zlib;
2375 else
2376 preferred_comp = &ssh_comp_none;
5e8358ad 2377
7591b9ff 2378 /*
2379 * Be prepared to work around the buggy MAC problem.
2380 */
7d503c31 2381 if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
8b2715b2 2382 maclist = buggymacs, nmacs = lenof(buggymacs);
7591b9ff 2383 else
8b2715b2 2384 maclist = macs, nmacs = lenof(macs);
7591b9ff 2385
7cca0d81 2386 begin_key_exchange:
e5574168 2387 /*
2388 * Construct and send our key exchange packet.
2389 */
2390 ssh2_pkt_init(SSH2_MSG_KEXINIT);
2391 for (i = 0; i < 16; i++)
2392 ssh2_pkt_addbyte((unsigned char)random_byte());
2393 /* List key exchange algorithms. */
2394 ssh2_pkt_addstring_start();
2395 for (i = 0; i < lenof(kex_algs); i++) {
2396 ssh2_pkt_addstring_str(kex_algs[i]->name);
2397 if (i < lenof(kex_algs)-1)
2398 ssh2_pkt_addstring_str(",");
2399 }
2400 /* List server host key algorithms. */
2401 ssh2_pkt_addstring_start();
2402 for (i = 0; i < lenof(hostkey_algs); i++) {
2403 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
2404 if (i < lenof(hostkey_algs)-1)
2405 ssh2_pkt_addstring_str(",");
2406 }
2407 /* List client->server encryption algorithms. */
2408 ssh2_pkt_addstring_start();
729e54b4 2409 for (i = 0; i < lenof(ciphers)+1; i++) {
0a3f1d48 2410 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2411 for (j = 0; j < c->nciphers; j++) {
2412 ssh2_pkt_addstring_str(c->list[j]->name);
2413 if (i < lenof(ciphers) || j < c->nciphers-1)
2414 ssh2_pkt_addstring_str(",");
2415 }
e5574168 2416 }
2417 /* List server->client encryption algorithms. */
2418 ssh2_pkt_addstring_start();
729e54b4 2419 for (i = 0; i < lenof(ciphers)+1; i++) {
0a3f1d48 2420 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2421 for (j = 0; j < c->nciphers; j++) {
2422 ssh2_pkt_addstring_str(c->list[j]->name);
2423 if (i < lenof(ciphers) || j < c->nciphers-1)
2424 ssh2_pkt_addstring_str(",");
2425 }
e5574168 2426 }
2427 /* List client->server MAC algorithms. */
2428 ssh2_pkt_addstring_start();
8b2715b2 2429 for (i = 0; i < nmacs; i++) {
7591b9ff 2430 ssh2_pkt_addstring_str(maclist[i]->name);
8b2715b2 2431 if (i < nmacs-1)
e5574168 2432 ssh2_pkt_addstring_str(",");
2433 }
2434 /* List server->client MAC algorithms. */
2435 ssh2_pkt_addstring_start();
8b2715b2 2436 for (i = 0; i < nmacs; i++) {
7591b9ff 2437 ssh2_pkt_addstring_str(maclist[i]->name);
8b2715b2 2438 if (i < nmacs-1)
e5574168 2439 ssh2_pkt_addstring_str(",");
2440 }
2441 /* List client->server compression algorithms. */
2442 ssh2_pkt_addstring_start();
4ba9b64b 2443 for (i = 0; i < lenof(compressions)+1; i++) {
2444 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2445 ssh2_pkt_addstring_str(c->name);
2446 if (i < lenof(compressions))
e5574168 2447 ssh2_pkt_addstring_str(",");
2448 }
2449 /* List server->client compression algorithms. */
2450 ssh2_pkt_addstring_start();
4ba9b64b 2451 for (i = 0; i < lenof(compressions)+1; i++) {
2452 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2453 ssh2_pkt_addstring_str(c->name);
2454 if (i < lenof(compressions))
e5574168 2455 ssh2_pkt_addstring_str(",");
2456 }
2457 /* List client->server languages. Empty list. */
2458 ssh2_pkt_addstring_start();
2459 /* List server->client languages. Empty list. */
2460 ssh2_pkt_addstring_start();
2461 /* First KEX packet does _not_ follow, because we're not that brave. */
2462 ssh2_pkt_addbool(FALSE);
2463 /* Reserved. */
2464 ssh2_pkt_adduint32(0);
0db56f73 2465
2466 exhash = exhashbase;
e5574168 2467 sha_string(&exhash, pktout.data+5, pktout.length-5);
0db56f73 2468
e5574168 2469 ssh2_pkt_send();
2470
2471 if (!ispkt) crWaitUntil(ispkt);
2472 sha_string(&exhash, pktin.data+5, pktin.length-5);
2473
2474 /*
2475 * Now examine the other side's KEXINIT to see what we're up
2476 * to.
2477 */
7cca0d81 2478 if (pktin.type != SSH2_MSG_KEXINIT) {
8d5de777 2479 bombout(("expected key exchange packet from server"));
2480 crReturn(0);
7cca0d81 2481 }
e5574168 2482 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
2483 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
2484 pktin.savedpos += 16; /* skip garbage cookie */
2485 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
2486 for (i = 0; i < lenof(kex_algs); i++) {
2487 if (in_commasep_string(kex_algs[i]->name, str, len)) {
2488 kex = kex_algs[i];
2489 break;
2490 }
2491 }
2492 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
2493 for (i = 0; i < lenof(hostkey_algs); i++) {
2494 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
2495 hostkey = hostkey_algs[i];
2496 break;
2497 }
2498 }
2499 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
729e54b4 2500 for (i = 0; i < lenof(ciphers)+1; i++) {
0a3f1d48 2501 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2502 for (j = 0; j < c->nciphers; j++) {
2503 if (in_commasep_string(c->list[j]->name, str, len)) {
2504 cscipher_tobe = c->list[j];
2505 break;
2506 }
e5574168 2507 }
0a3f1d48 2508 if (cscipher_tobe)
2509 break;
e5574168 2510 }
2511 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
729e54b4 2512 for (i = 0; i < lenof(ciphers)+1; i++) {
0a3f1d48 2513 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2514 for (j = 0; j < c->nciphers; j++) {
2515 if (in_commasep_string(c->list[j]->name, str, len)) {
2516 sccipher_tobe = c->list[j];
2517 break;
2518 }
e5574168 2519 }
0a3f1d48 2520 if (sccipher_tobe)
2521 break;
e5574168 2522 }
2523 ssh2_pkt_getstring(&str, &len); /* client->server mac */
8b2715b2 2524 for (i = 0; i < nmacs; i++) {
7591b9ff 2525 if (in_commasep_string(maclist[i]->name, str, len)) {
2526 csmac_tobe = maclist[i];
e5574168 2527 break;
2528 }
2529 }
2530 ssh2_pkt_getstring(&str, &len); /* server->client mac */
8b2715b2 2531 for (i = 0; i < nmacs; i++) {
7591b9ff 2532 if (in_commasep_string(maclist[i]->name, str, len)) {
2533 scmac_tobe = maclist[i];
e5574168 2534 break;
2535 }
2536 }
2537 ssh2_pkt_getstring(&str, &len); /* client->server compression */
4ba9b64b 2538 for (i = 0; i < lenof(compressions)+1; i++) {
2539 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2540 if (in_commasep_string(c->name, str, len)) {
2541 cscomp_tobe = c;
e5574168 2542 break;
2543 }
2544 }
2545 ssh2_pkt_getstring(&str, &len); /* server->client compression */
4ba9b64b 2546 for (i = 0; i < lenof(compressions)+1; i++) {
2547 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2548 if (in_commasep_string(c->name, str, len)) {
2549 sccomp_tobe = c;
e5574168 2550 break;
2551 }
2552 }
e5574168 2553
2554 /*
a92dd380 2555 * If we're doing Diffie-Hellman group exchange, start by
2556 * requesting a group.
e5574168 2557 */
a92dd380 2558 if (kex == &ssh_diffiehellman_gex) {
2559 int csbits, scbits;
2560
2561 logevent("Doing Diffie-Hellman group exchange");
2562 /*
2563 * Work out number of bits. We start with the maximum key
2564 * length of either cipher...
2565 */
2566 csbits = cscipher_tobe->keylen;
2567 scbits = sccipher_tobe->keylen;
2568 nbits = (csbits > scbits ? csbits : scbits);
2569 /* The keys only have 160-bit entropy, since they're based on
2570 * a SHA-1 hash. So cap the key size at 160 bits. */
2571 if (nbits > 160) nbits = 160;
2572 /*
2573 * ... and then work out how big a DH group we will need to
2574 * allow that much data.
2575 */
2576 nbits = 512 << ((nbits-1) / 64);
2577 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
2578 ssh2_pkt_adduint32(nbits);
2579 ssh2_pkt_send();
2580
2581 crWaitUntil(ispkt);
2582 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
2583 bombout(("expected key exchange group packet from server"));
2584 crReturn(0);
2585 }
2586 p = ssh2_pkt_getmp();
2587 g = ssh2_pkt_getmp();
2588 dh_setup_group(p, g);
2589 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
2590 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
2591 } else {
2592 dh_setup_group1();
2593 kex_init_value = SSH2_MSG_KEXDH_INIT;
2594 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
8d5de777 2595 }
e5574168 2596
a92dd380 2597 logevent("Doing Diffie-Hellman key exchange");
e5574168 2598 /*
a92dd380 2599 * Now generate and send e for Diffie-Hellman.
e5574168 2600 */
2601 e = dh_create_e();
a92dd380 2602 ssh2_pkt_init(kex_init_value);
e5574168 2603 ssh2_pkt_addmp(e);
2604 ssh2_pkt_send();
2605
2606 crWaitUntil(ispkt);
a92dd380 2607 if (pktin.type != kex_reply_value) {
2608 bombout(("expected key exchange reply packet from server"));
8d5de777 2609 crReturn(0);
7cca0d81 2610 }
e5574168 2611 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2612 f = ssh2_pkt_getmp();
e5574168 2613 ssh2_pkt_getstring(&sigdata, &siglen);
2614
2615 K = dh_find_K(f);
e5574168 2616
2617 sha_string(&exhash, hostkeydata, hostkeylen);
a92dd380 2618 if (kex == &ssh_diffiehellman_gex) {
2619 sha_uint32(&exhash, nbits);
2620 sha_mpint(&exhash, p);
2621 sha_mpint(&exhash, g);
2622 }
e5574168 2623 sha_mpint(&exhash, e);
2624 sha_mpint(&exhash, f);
2625 sha_mpint(&exhash, K);
2626 SHA_Final(&exhash, exchange_hash);
2627
3709bfe9 2628 dh_cleanup();
2629
7cca0d81 2630#if 0
e5574168 2631 debug(("Exchange hash is:\r\n"));
2632 for (i = 0; i < 20; i++)
2633 debug((" %02x", exchange_hash[i]));
2634 debug(("\r\n"));
7cca0d81 2635#endif
2636
e055a386 2637 hkey = hostkey->newkey(hostkeydata, hostkeylen);
2638 if (!hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
8d5de777 2639 bombout(("Server failed host key check"));
2640 crReturn(0);
2641 }
e5574168 2642
2643 /*
7cca0d81 2644 * Expect SSH2_MSG_NEWKEYS from server.
d39f364a 2645 */
7cca0d81 2646 crWaitUntil(ispkt);
8d5de777 2647 if (pktin.type != SSH2_MSG_NEWKEYS) {
2648 bombout(("expected new-keys packet from server"));
2649 crReturn(0);
2650 }
d39f364a 2651
2652 /*
7cca0d81 2653 * Authenticate remote host: verify host key. (We've already
2654 * checked the signature of the exchange hash.)
e5574168 2655 */
e055a386 2656 keystr = hostkey->fmtkey(hkey);
2657 fingerprint = hostkey->fingerprint(hkey);
d4857987 2658 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
2659 keystr, fingerprint);
a92dd380 2660 if (first_kex) { /* don't bother logging this in rekeys */
5e0d7cb8 2661 logevent("Host key fingerprint is:");
2662 logevent(fingerprint);
2663 }
dcbde236 2664 sfree(fingerprint);
2665 sfree(keystr);
e055a386 2666 hostkey->freekey(hkey);
d39f364a 2667
2668 /*
7cca0d81 2669 * Send SSH2_MSG_NEWKEYS.
d39f364a 2670 */
2671 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2672 ssh2_pkt_send();
d39f364a 2673
2674 /*
2675 * Create and initialise session keys.
2676 */
2677 cscipher = cscipher_tobe;
2678 sccipher = sccipher_tobe;
2679 csmac = csmac_tobe;
2680 scmac = scmac_tobe;
2681 cscomp = cscomp_tobe;
2682 sccomp = sccomp_tobe;
4ba9b64b 2683 cscomp->compress_init();
2684 sccomp->decompress_init();
d39f364a 2685 /*
5e0d7cb8 2686 * Set IVs after keys. Here we use the exchange hash from the
2687 * _first_ key exchange.
d39f364a 2688 */
5e0d7cb8 2689 if (first_kex)
65a22376 2690 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
2691 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
5e0d7cb8 2692 cscipher->setcskey(keyspace);
65a22376 2693 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
5e0d7cb8 2694 sccipher->setsckey(keyspace);
65a22376 2695 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
5e0d7cb8 2696 cscipher->setcsiv(keyspace);
65a22376 2697 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
5e0d7cb8 2698 sccipher->setsciv(keyspace);
65a22376 2699 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
5e0d7cb8 2700 csmac->setcskey(keyspace);
65a22376 2701 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
5e0d7cb8 2702 scmac->setsckey(keyspace);
d39f364a 2703
033b4cef 2704 /*
0db56f73 2705 * If this is the first key exchange phase, we must pass the
2706 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2707 * wants to see it but because it will need time to initialise
2708 * itself before it sees an actual packet. In subsequent key
2709 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2710 * it would only confuse the layer above.
2711 */
2712 if (!first_kex) {
2713 crReturn(0);
2714 }
2715 first_kex = 0;
2716
2717 /*
7cca0d81 2718 * Now we're encrypting. Begin returning 1 to the protocol main
2719 * function so that other things can run on top of the
2720 * transport. If we ever see a KEXINIT, we must go back to the
2721 * start.
033b4cef 2722 */
e96adf72 2723 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
7cca0d81 2724 crReturn(1);
e96adf72 2725 }
5e0d7cb8 2726 logevent("Server initiated key re-exchange");
7cca0d81 2727 goto begin_key_exchange;
e5574168 2728
2729 crFinish(1);
2730}
2731
7cca0d81 2732/*
783415f8 2733 * Add data to an SSH2 channel output buffer.
2734 */
2735static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len) {
2736 if (c->v2.outbufsize <
2737 c->v2.outbuflen + len) {
2738 c->v2.outbufsize =
2739 c->v2.outbuflen + len + 1024;
2740 c->v2.outbuffer = srealloc(c->v2.outbuffer,
2741 c->v2.outbufsize);
2742 }
2743 memcpy(c->v2.outbuffer + c->v2.outbuflen,
2744 buf, len);
2745 c->v2.outbuflen += len;
2746}
2747
2748/*
2749 * Attempt to send data on an SSH2 channel.
2750 */
2751static void ssh2_try_send(struct ssh_channel *c) {
2752 while (c->v2.remwindow > 0 &&
2753 c->v2.outbuflen > 0) {
2754 unsigned len = c->v2.remwindow;
2755 if (len > c->v2.outbuflen)
2756 len = c->v2.outbuflen;
2757 if (len > c->v2.remmaxpkt)
2758 len = c->v2.remmaxpkt;
2759 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2760 ssh2_pkt_adduint32(c->remoteid);
2761 ssh2_pkt_addstring_start();
2762 ssh2_pkt_addstring_data(c->v2.outbuffer, len);
2763 ssh2_pkt_send();
2764 c->v2.outbuflen -= len;
2765 memmove(c->v2.outbuffer, c->v2.outbuffer+len,
2766 c->v2.outbuflen);
2767 c->v2.remwindow -= len;
2768 }
2769}
2770
2771/*
7cca0d81 2772 * Handle the SSH2 userauth and connection layers.
2773 */
2774static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2775{
7cca0d81 2776 static unsigned long remote_winsize;
2777 static unsigned long remote_maxpkt;
65a22376 2778 static enum {
2779 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE, AUTH_PASSWORD
2780 } method;
1408a877 2781 static enum {
2782 AUTH_TYPE_NONE,
2783 AUTH_TYPE_PUBLICKEY,
2784 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
2785 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
2786 AUTH_TYPE_PASSWORD
2787 } type;
1983e559 2788 static int gotit, need_pw, can_pubkey, can_passwd;
2789 static int tried_pubkey_config, tried_agent;
1408a877 2790 static int we_are_in;
65a22376 2791 static char username[100];
2792 static char pwprompt[200];
2793 static char password[100];
7cca0d81 2794
e5574168 2795 crBegin;
2796
7cca0d81 2797 /*
2798 * Request userauth protocol, and await a response to it.
2799 */
2800 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2801 ssh2_pkt_addstring("ssh-userauth");
2802 ssh2_pkt_send();
2803 crWaitUntilV(ispkt);
8d5de777 2804 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2805 bombout(("Server refused user authentication protocol"));
2806 crReturnV;
2807 }
7cca0d81 2808
2809 /*
1408a877 2810 * We repeat this whole loop, including the username prompt,
2811 * until we manage a successful authentication. If the user
2812 * types the wrong _password_, they are sent back to the
2813 * beginning to try another username. (If they specify a
2814 * username in the config, they are never asked, even if they
2815 * do give a wrong password.)
2816 *
2817 * I think this best serves the needs of
2818 *
2819 * - the people who have no configuration, no keys, and just
2820 * want to try repeated (username,password) pairs until they
2821 * type both correctly
2822 *
2823 * - people who have keys and configuration but occasionally
2824 * need to fall back to passwords
2825 *
2826 * - people with a key held in Pageant, who might not have
2827 * logged in to a particular machine before; so they want to
2828 * type a username, and then _either_ their key will be
2829 * accepted, _or_ they will type a password. If they mistype
2830 * the username they will want to be able to get back and
2831 * retype it!
7cca0d81 2832 */
1408a877 2833 do {
2834 static int pos;
7cca0d81 2835 static char c;
e5574168 2836
1408a877 2837 /*
2838 * Get a username.
2839 */
2840 pos = 0;
67779be7 2841 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1408a877 2842 c_write_str("login as: ");
65a22376 2843 ssh_send_ok = 1;
7cca0d81 2844 while (pos >= 0) {
2845 crWaitUntilV(!ispkt);
2846 while (inlen--) switch (c = *in++) {
2847 case 10: case 13:
2848 username[pos] = 0;
2849 pos = -1;
2850 break;
2851 case 8: case 127:
2852 if (pos > 0) {
1408a877 2853 c_write_str("\b \b");
7cca0d81 2854 pos--;
2855 }
2856 break;
2857 case 21: case 27:
2858 while (pos > 0) {
1408a877 2859 c_write_str("\b \b");
7cca0d81 2860 pos--;
2861 }
2862 break;
2863 case 3: case 4:
2864 random_save_seed();
2865 exit(0);
2866 break;
2867 default:
2868 if (((c >= ' ' && c <= '~') ||
65a22376 2869 ((unsigned char)c >= 160)) && pos < 40) {
7cca0d81 2870 username[pos++] = c;
2871 c_write(&c, 1);
2872 }
2873 break;
2874 }
2875 }
1408a877 2876 c_write_str("\r\n");
7cca0d81 2877 username[strcspn(username, "\n\r")] = '\0';
2878 } else {
2879 char stuff[200];
2880 strncpy(username, cfg.username, 99);
2881 username[99] = '\0';
65a22376 2882 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7cca0d81 2883 sprintf(stuff, "Using username \"%s\".\r\n", username);
1408a877 2884 c_write_str(stuff);
7cca0d81 2885 }
2886 }
2887
65a22376 2888 /*
1408a877 2889 * Send an authentication request using method "none": (a)
2890 * just in case it succeeds, and (b) so that we know what
2891 * authentication methods we can usefully try next.
65a22376 2892 */
1408a877 2893 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2894 ssh2_pkt_addstring(username);
2895 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2896 ssh2_pkt_addstring("none"); /* method */
2897 ssh2_pkt_send();
2898 type = AUTH_TYPE_NONE;
2899 gotit = FALSE;
2900 we_are_in = FALSE;
7cca0d81 2901
1408a877 2902 tried_pubkey_config = FALSE;
1983e559 2903 tried_agent = FALSE;
65a22376 2904
1408a877 2905 while (1) {
2906 /*
2907 * Wait for the result of the last authentication request.
2908 */
2909 if (!gotit)
2910 crWaitUntilV(ispkt);
2911 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
2912 /* FIXME: should support this */
2913 crWaitUntilV(ispkt);
2914 }
2915 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
2916 logevent("Access granted");
2917 we_are_in = TRUE;
2918 break;
2919 }
65a22376 2920
1408a877 2921 if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
2922 bombout(("Strange packet received during authentication: type %d",
2923 pktin.type));
65a22376 2924 }
2925
1408a877 2926 gotit = FALSE;
65a22376 2927
1408a877 2928 /*
2929 * OK, we're now sitting on a USERAUTH_FAILURE message, so
2930 * we can look at the string in it and know what we can
2931 * helpfully try next.
2932 */
2933 {
2934 char *methods;
2935 int methlen;
2936 ssh2_pkt_getstring(&methods, &methlen);
2937 if (!ssh2_pkt_getbool()) {
2938 /*
2939 * We have received an unequivocal Access
2940 * Denied. This can translate to a variety of
2941 * messages:
2942 *
2943 * - if we'd just tried "none" authentication,
2944 * it's not worth printing anything at all
2945 *
2946 * - if we'd just tried a public key _offer_,
2947 * the message should be "Server refused our
2948 * key" (or no message at all if the key
2949 * came from Pageant)
2950 *
2951 * - if we'd just tried anything else, the
2952 * message really should be "Access denied".
2953 *
2954 * Additionally, if we'd just tried password
2955 * authentication, we should break out of this
2956 * whole loop so as to go back to the username
2957 * prompt.
2958 */
2959 if (type == AUTH_TYPE_NONE) {
2960 /* do nothing */
2961 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
2962 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
2963 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
2964 c_write_str("Server refused our key\r\n");
2965 logevent("Server refused public key");
2966 } else {
2967 c_write_str("Access denied\r\n");
2968 logevent("Access denied");
2969 if (type == AUTH_TYPE_PASSWORD) {
2970 we_are_in = FALSE;
2971 break;
2972 }
2973 }
2974 } else {
2975 c_write_str("Further authentication required\r\n");
2976 logevent("Further authentication required");
2977 }
65a22376 2978
1408a877 2979 can_pubkey = in_commasep_string("publickey", methods, methlen);
2980 can_passwd = in_commasep_string("password", methods, methlen);
2981 }
65a22376 2982
1408a877 2983 method = 0;
65a22376 2984
1983e559 2985 if (!method && can_pubkey && agent_exists && !tried_agent) {
2986 /*
2987 * Attempt public-key authentication using Pageant.
2988 */
2989 static unsigned char request[5], *response, *p;
2990 static int responselen;
2991 static int i, nkeys;
2992 static int authed = FALSE;
2993 void *r;
2994
2995 tried_agent = TRUE;
2996
2997 logevent("Pageant is running. Requesting keys.");
2998
2999 /* Request the keys held by the agent. */
3000 PUT_32BIT(request, 1);
3001 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
3002 agent_query(request, 5, &r, &responselen);
3003 response = (unsigned char *)r;
3004 if (response) {
3005 p = response + 5;
3006 nkeys = GET_32BIT(p); p += 4;
6328ea7a 3007 { char buf[64]; sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
1983e559 3008 logevent(buf); }
3009 for (i = 0; i < nkeys; i++) {
3010 static char *pkblob, *alg, *commentp;
3011 static int pklen, alglen, commentlen;
3012 static int siglen, retlen, len;
3013 static char *q, *agentreq, *ret;
3014
3015 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
3016 logevent(buf); }
3017 pklen = GET_32BIT(p); p += 4;
3018 pkblob = p; p += pklen;
3019 alglen = GET_32BIT(pkblob);
3020 alg = pkblob + 4;
3021 commentlen = GET_32BIT(p); p += 4;
3022 commentp = p; p += commentlen;
3023 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3024 ssh2_pkt_addstring(username);
3025 ssh2_pkt_addstring("ssh-connection");/* service requested */
3026 ssh2_pkt_addstring("publickey");/* method */
3027 ssh2_pkt_addbool(FALSE); /* no signature included */
3028 ssh2_pkt_addstring_start();
3029 ssh2_pkt_addstring_data(alg, alglen);
3030 ssh2_pkt_addstring_start();
3031 ssh2_pkt_addstring_data(pkblob, pklen);
3032 ssh2_pkt_send();
3033
3034 crWaitUntilV(ispkt);
3035 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3036 logevent("Key refused");
3037 continue;
3038 }
3039
3040 c_write_str("Authenticating with public key \"");
3041 c_write(commentp, commentlen);
3042 c_write_str("\" from agent\r\n");
3043
3044 /*
3045 * Server is willing to accept the key.
3046 * Construct a SIGN_REQUEST.
3047 */
3048 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3049 ssh2_pkt_addstring(username);
3050 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3051 ssh2_pkt_addstring("publickey"); /* method */
3052 ssh2_pkt_addbool(TRUE);
3053 ssh2_pkt_addstring_start();
3054 ssh2_pkt_addstring_data(alg, alglen);
3055 ssh2_pkt_addstring_start();
3056 ssh2_pkt_addstring_data(pkblob, pklen);
3057
3058 siglen = pktout.length - 5 + 4 + 20;
3059 len = 1; /* message type */
3060 len += 4 + pklen; /* key blob */
3061 len += 4 + siglen; /* data to sign */
3062 len += 4; /* flags */
3063 agentreq = smalloc(4 + len);
3064 PUT_32BIT(agentreq, len);
3065 q = agentreq + 4;
3066 *q++ = SSH2_AGENTC_SIGN_REQUEST;
3067 PUT_32BIT(q, pklen); q += 4;
3068 memcpy(q, pkblob, pklen); q += pklen;
3069 PUT_32BIT(q, siglen); q += 4;
3070 /* Now the data to be signed... */
3071 PUT_32BIT(q, 20); q += 4;
3072 memcpy(q, ssh2_session_id, 20); q += 20;
3073 memcpy(q, pktout.data+5, pktout.length-5);
3074 q += pktout.length-5;
3075 /* And finally the (zero) flags word. */
3076 PUT_32BIT(q, 0);
3077 agent_query(agentreq, len+4, &ret, &retlen);
3078 sfree(agentreq);
3079 if (ret) {
3080 if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
3081 logevent("Sending Pageant's response");
3082 ssh2_pkt_addstring_start();
3083 ssh2_pkt_addstring_data(ret+9, GET_32BIT(ret+5));
3084 ssh2_pkt_send();
3085 authed = TRUE;
3086 break;
3087 } else {
3088 logevent("Pageant failed to answer challenge");
3089 sfree(ret);
3090 }
3091 }
3092 }
3093 if (authed)
3094 continue;
3095 }
3096 }
3097
1408a877 3098 if (!method && can_pubkey && *cfg.keyfile && !tried_pubkey_config) {
3099 unsigned char *pub_blob;
3100 char *algorithm, *comment;
3101 int pub_blob_len;
65a22376 3102
1408a877 3103 tried_pubkey_config = TRUE;
65a22376 3104
65a22376 3105 /*
1408a877 3106 * Try the public key supplied in the configuration.
3107 *
3108 * First, offer the public blob to see if the server is
3109 * willing to accept it.
65a22376 3110 */
1408a877 3111 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
3112 &pub_blob_len);
3113 if (pub_blob) {
3114 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3115 ssh2_pkt_addstring(username);
3116 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3117 ssh2_pkt_addstring("publickey");/* method */
3118 ssh2_pkt_addbool(FALSE); /* no signature included */
3119 ssh2_pkt_addstring(algorithm);
3120 ssh2_pkt_addstring_start();
3121 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
3122 ssh2_pkt_send();
3123 logevent("Offered public key"); /* FIXME */
3124
3125 crWaitUntilV(ispkt);
3126 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3127 gotit = TRUE;
3128 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
3129 continue; /* key refused; give up on it */
3130 }
65a22376 3131
1408a877 3132 logevent("Offer of public key accepted");
65a22376 3133 /*
1408a877 3134 * Actually attempt a serious authentication using
3135 * the key.
65a22376 3136 */
1408a877 3137 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
3138 sprintf(pwprompt, "Passphrase for key \"%.100s\": ", comment);
3139 need_pw = TRUE;
3140 } else {
3141 need_pw = FALSE;
3142 }
3143 c_write_str("Authenticating with public key \"");
3144 c_write_str(comment);
3145 c_write_str("\"\r\n");
3146 method = AUTH_PUBLICKEY_FILE;
65a22376 3147 }
1408a877 3148 }
3149
3150 if (!method && can_passwd) {
3151 method = AUTH_PASSWORD;
3152 sprintf(pwprompt, "%.90s@%.90s's password: ", username, savedhost);
3153 need_pw = TRUE;
3154 }
3155
3156 if (need_pw) {
3157 if (ssh_get_password) {
3158 if (!ssh_get_password(pwprompt, password, sizeof(password))) {
3159 /*
3160 * get_password failed to get a password (for
3161 * example because one was supplied on the command
3162 * line which has already failed to work).
3163 * Terminate.
3164 */
3165 logevent("No more passwords to try");
3166 ssh_state = SSH_STATE_CLOSED;
3167 crReturnV;
3168 }
3169 } else {
3170 static int pos = 0;
3171 static char c;
3172
3173 c_write_str(pwprompt);
3174 ssh_send_ok = 1;
3175
3176 pos = 0;
3177 while (pos >= 0) {
3178 crWaitUntilV(!ispkt);
3179 while (inlen--) switch (c = *in++) {
3180 case 10: case 13:
3181 password[pos] = 0;
3182 pos = -1;
3183 break;
3184 case 8: case 127:
3185 if (pos > 0)
3186 pos--;
3187 break;
3188 case 21: case 27:
3189 pos = 0;
3190 break;
3191 case 3: case 4:
3192 random_save_seed();
3193 exit(0);
3194 break;
3195 default:
3196 if (((c >= ' ' && c <= '~') ||
3197 ((unsigned char)c >= 160)) && pos < 40)
3198 password[pos++] = c;
3199 break;
3200 }
65a22376 3201 }
1408a877 3202 c_write_str("\r\n");
65a22376 3203 }
65a22376 3204 }
65a22376 3205
1408a877 3206 if (method == AUTH_PUBLICKEY_FILE) {
3207 /*
3208 * We have our passphrase. Now try the actual authentication.
3209 */
3210 struct ssh2_userkey *key;
65a22376 3211
1408a877 3212 key = ssh2_load_userkey(cfg.keyfile, password);
3213 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
3214 if (key == SSH2_WRONG_PASSPHRASE) {
3215 c_write_str("Wrong passphrase\r\n");
3216 tried_pubkey_config = FALSE;
3217 } else {
3218 c_write_str("Unable to load private key\r\n");
3219 tried_pubkey_config = TRUE;
3220 }
3221 /* Send a spurious AUTH_NONE to return to the top. */
3222 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3223 ssh2_pkt_addstring(username);
3224 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3225 ssh2_pkt_addstring("none"); /* method */
3226 ssh2_pkt_send();
3227 type = AUTH_TYPE_NONE;
3228 } else {
3229 unsigned char *blob, *sigdata;
3230 int blob_len, sigdata_len;
65a22376 3231
1408a877 3232 /*
3233 * We have loaded the private key and the server
3234 * has announced that it's willing to accept it.
3235 * Hallelujah. Generate a signature and send it.
3236 */
3237 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3238 ssh2_pkt_addstring(username);
3239 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3240 ssh2_pkt_addstring("publickey"); /* method */
3241 ssh2_pkt_addbool(TRUE);
3242 ssh2_pkt_addstring(key->alg->name);
3243 blob = key->alg->public_blob(key->data, &blob_len);
3244 ssh2_pkt_addstring_start();
3245 ssh2_pkt_addstring_data(blob, blob_len);
3246 sfree(blob);
3247
3248 /*
3249 * The data to be signed is:
3250 *
3251 * string session-id
3252 *
3253 * followed by everything so far placed in the
3254 * outgoing packet.
3255 */
3256 sigdata_len = pktout.length - 5 + 4 + 20;
3257 sigdata = smalloc(sigdata_len);
3258 PUT_32BIT(sigdata, 20);
3259 memcpy(sigdata+4, ssh2_session_id, 20);
3260 memcpy(sigdata+24, pktout.data+5, pktout.length-5);
3261 blob = key->alg->sign(key->data, sigdata, sigdata_len, &blob_len);
3262 ssh2_pkt_addstring_start();
3263 ssh2_pkt_addstring_data(blob, blob_len);
3264 sfree(blob);
3265 sfree(sigdata);
3266
3267 ssh2_pkt_send();
3268 type = AUTH_TYPE_PUBLICKEY;
3269 }
3270 } else if (method == AUTH_PASSWORD) {
65a22376 3271 /*
1408a877 3272 * We send the password packet lumped tightly together with
3273 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3274 * string long enough to make the total length of the two
3275 * packets constant. This should ensure that a passive
3276 * listener doing traffic analyis can't work out the length
3277 * of the password.
3278 *
3279 * For this to work, we need an assumption about the
3280 * maximum length of the password packet. I think 256 is
3281 * pretty conservative. Anyone using a password longer than
3282 * that probably doesn't have much to worry about from
3283 * people who find out how long their password is!
65a22376 3284 */
3285 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3286 ssh2_pkt_addstring(username);
3287 ssh2_pkt_addstring("ssh-connection"); /* service requested */
1408a877 3288 ssh2_pkt_addstring("password");
3289 ssh2_pkt_addbool(FALSE);
3290 ssh2_pkt_addstring(password);
3291 ssh2_pkt_defer();
65a22376 3292 /*
1408a877 3293 * We'll include a string that's an exact multiple of the
3294 * cipher block size. If the cipher is NULL for some
3295 * reason, we don't do this trick at all because we gain
3296 * nothing by it.
65a22376 3297 */
6e9e9520 3298 if (cscipher) {
3299 int stringlen, i;
3300
3301 stringlen = (256 - deferred_len);
3302 stringlen += cscipher->blksize - 1;
3303 stringlen -= (stringlen % cscipher->blksize);
3304 if (cscomp) {
3305 /*
3306 * Temporarily disable actual compression,
3307 * so we can guarantee to get this string
3308 * exactly the length we want it. The
3309 * compression-disabling routine should
3310 * return an integer indicating how many
3311 * bytes we should adjust our string length
3312 * by.
3313 */
3314 stringlen -= cscomp->disable_compression();
3315 }
1408a877 3316 ssh2_pkt_init(SSH2_MSG_IGNORE);
3317 ssh2_pkt_addstring_start();
6e9e9520 3318 for (i = 0; i < stringlen; i++) {
3319 char c = (char)random_byte();
3320 ssh2_pkt_addstring_data(&c, 1);
65a22376 3321 }
1408a877 3322 ssh2_pkt_defer();
65a22376 3323 }
39065bed 3324 ssh_pkt_defersend();
0d43337a 3325 logevent("Sent password");
1408a877 3326 type = AUTH_TYPE_PASSWORD;
3327 } else {
3328 c_write_str("No supported authentication methods left to try!\r\n");
3329 logevent("No supported authentications offered. Disconnecting");
3330 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3331 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3332 ssh2_pkt_addstring("No supported authentication methods available");
3333 ssh2_pkt_addstring("en"); /* language tag */
3334 ssh2_pkt_send();
3335 ssh_state = SSH_STATE_CLOSED;
3336 crReturnV;
65a22376 3337 }
65a22376 3338 }
1408a877 3339 } while (!we_are_in);
7cca0d81 3340
3341 /*
3342 * Now we're authenticated for the connection protocol. The
3343 * connection protocol will automatically have started at this
3344 * point; there's no need to send SERVICE_REQUEST.
3345 */
3346
3347 /*
3348 * So now create a channel with a session in it.
3349 */
dcbde236 3350 mainchan = smalloc(sizeof(struct ssh_channel));
d211621f 3351 mainchan->localid = 100; /* as good as any */
7cca0d81 3352 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
3353 ssh2_pkt_addstring("session");
d211621f 3354 ssh2_pkt_adduint32(mainchan->localid);
cf6e59d6 3355 ssh2_pkt_adduint32(0x8000UL); /* our window size */
d211621f 3356 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
7cca0d81 3357 ssh2_pkt_send();
3358 crWaitUntilV(ispkt);
3359 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8d5de777 3360 bombout(("Server refused to open a session"));
3361 crReturnV;
7cca0d81 3362 /* FIXME: error data comes back in FAILURE packet */
3363 }
d211621f 3364 if (ssh2_pkt_getuint32() != mainchan->localid) {
8d5de777 3365 bombout(("Server's channel confirmation cited wrong channel"));
3366 crReturnV;
7cca0d81 3367 }
d211621f 3368 mainchan->remoteid = ssh2_pkt_getuint32();
783415f8 3369 mainchan->type = CHAN_MAINSESSION;
3370 mainchan->closes = 0;
3371 mainchan->v2.remwindow = ssh2_pkt_getuint32();
3372 mainchan->v2.remmaxpkt = ssh2_pkt_getuint32();
3373 mainchan->v2.outbuffer = NULL;
3374 mainchan->v2.outbuflen = mainchan->v2.outbufsize = 0;
3375 ssh_channels = newtree234(ssh_channelcmp);
3376 add234(ssh_channels, mainchan);
7cca0d81 3377 logevent("Opened channel for session");
3378
3379 /*
783415f8 3380 * Potentially enable X11 forwarding.
3381 */
3382 if (cfg.x11_forward) {
3383 char proto[20], data[64];
3384 logevent("Requesting X11 forwarding");
3385 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3386 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3387 ssh2_pkt_adduint32(mainchan->remoteid);
3388 ssh2_pkt_addstring("x11-req");
3389 ssh2_pkt_addbool(1); /* want reply */
3390 ssh2_pkt_addbool(0); /* many connections */
3391 ssh2_pkt_addstring(proto);
3392 ssh2_pkt_addstring(data);
3393 ssh2_pkt_adduint32(0); /* screen number */
3394 ssh2_pkt_send();
3395
3396 do {
3397 crWaitUntilV(ispkt);
3398 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3399 unsigned i = ssh2_pkt_getuint32();
3400 struct ssh_channel *c;
3401 c = find234(ssh_channels, &i, ssh_channelfind);
3402 if (!c)
3403 continue; /* nonexistent channel */
3404 c->v2.remwindow += ssh2_pkt_getuint32();
3405 }
3406 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3407
3408 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3409 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3410 bombout(("Server got confused by X11 forwarding request"));
3411 crReturnV;
3412 }
3413 logevent("X11 forwarding refused");
3414 } else {
3415 logevent("X11 forwarding enabled");
3416 ssh_X11_fwd_enabled = TRUE;
3417 }
3418 }
3419
3420 /*
36c2a3e9 3421 * Potentially enable agent forwarding.
3422 */
3423 if (cfg.agentfwd && agent_exists()) {
3424 char proto[20], data[64];
3425 logevent("Requesting OpenSSH-style agent forwarding");
3426 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3427 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3428 ssh2_pkt_adduint32(mainchan->remoteid);
3429 ssh2_pkt_addstring("auth-agent-req@openssh.com");
3430 ssh2_pkt_addbool(1); /* want reply */
3431 ssh2_pkt_send();
3432
3433 do {
3434 crWaitUntilV(ispkt);
3435 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3436 unsigned i = ssh2_pkt_getuint32();
3437 struct ssh_channel *c;
3438 c = find234(ssh_channels, &i, ssh_channelfind);
3439 if (!c)
3440 continue; /* nonexistent channel */
3441 c->v2.remwindow += ssh2_pkt_getuint32();
3442 }
3443 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3444
3445 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3446 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3447 bombout(("Server got confused by agent forwarding request"));
3448 crReturnV;
3449 }
3450 logevent("Agent forwarding refused");
3451 } else {
3452 logevent("Agent forwarding enabled");
3453 ssh_agentfwd_enabled = TRUE;
3454 }
3455 }
3456
3457 /*
7cca0d81 3458 * Now allocate a pty for the session.
3459 */
67779be7 3460 if (!cfg.nopty) {
3461 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3462 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
3463 ssh2_pkt_addstring("pty-req");
3464 ssh2_pkt_addbool(1); /* want reply */
3465 ssh2_pkt_addstring(cfg.termtype);
3466 ssh2_pkt_adduint32(cols);
3467 ssh2_pkt_adduint32(rows);
3468 ssh2_pkt_adduint32(0); /* pixel width */
3469 ssh2_pkt_adduint32(0); /* pixel height */
3470 ssh2_pkt_addstring_start();
3471 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3472 ssh2_pkt_send();
6e48c3fe 3473 ssh_state = SSH_STATE_INTERMED;
7cca0d81 3474
67779be7 3475 do {
3476 crWaitUntilV(ispkt);
3477 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
783415f8 3478 unsigned i = ssh2_pkt_getuint32();
3479 struct ssh_channel *c;
3480 c = find234(ssh_channels, &i, ssh_channelfind);
3481 if (!c)
3482 continue; /* nonexistent channel */
3483 c->v2.remwindow += ssh2_pkt_getuint32();
67779be7 3484 }
3485 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7cca0d81 3486
67779be7 3487 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3488 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
8d5de777 3489 bombout(("Server got confused by pty request"));
3490 crReturnV;
67779be7 3491 }
1408a877 3492 c_write_str("Server refused to allocate pty\r\n");
0965bee0 3493 ssh_editing = ssh_echoing = 1;
67779be7 3494 } else {
3495 logevent("Allocated pty");
7cca0d81 3496 }
0965bee0 3497 } else {
3498 ssh_editing = ssh_echoing = 1;
7cca0d81 3499 }
3500
3501 /*
67779be7 3502 * Start a shell or a remote command.
7cca0d81 3503 */
3504 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
d211621f 3505 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
4a8fc3c4 3506 if (cfg.ssh_subsys) {
3507 ssh2_pkt_addstring("subsystem");
3508 ssh2_pkt_addbool(1); /* want reply */
3509 ssh2_pkt_addstring(cfg.remote_cmd);
3510 } else if (*cfg.remote_cmd) {
67779be7 3511 ssh2_pkt_addstring("exec");
3512 ssh2_pkt_addbool(1); /* want reply */
3513 ssh2_pkt_addstring(cfg.remote_cmd);
3514 } else {
3515 ssh2_pkt_addstring("shell");
3516 ssh2_pkt_addbool(1); /* want reply */
3517 }
7cca0d81 3518 ssh2_pkt_send();
d211621f 3519 do {
7cca0d81 3520 crWaitUntilV(ispkt);
d211621f 3521 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
783415f8 3522 unsigned i = ssh2_pkt_getuint32();
3523 struct ssh_channel *c;
3524 c = find234(ssh_channels, &i, ssh_channelfind);
3525 if (!c)
3526 continue; /* nonexistent channel */
3527 c->v2.remwindow += ssh2_pkt_getuint32();
d211621f 3528 }
7cca0d81 3529 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3530 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3531 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
8d5de777 3532 bombout(("Server got confused by shell/command request"));
3533 crReturnV;
7cca0d81 3534 }
8d5de777 3535 bombout(("Server refused to start a shell/command"));
3536 crReturnV;
7cca0d81 3537 } else {
8d5de777 3538 logevent("Started a shell/command");
7cca0d81 3539 }
3540
6e48c3fe 3541 ssh_state = SSH_STATE_SESSION;
3542 if (size_needed)
3543 ssh_size();
3687d221 3544 if (eof_needed)
3545 ssh_special(TS_EOF);
6e48c3fe 3546
7cca0d81 3547 /*
3548 * Transfer data!
3549 */
0965bee0 3550 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
8ccc75b0 3551 ssh_send_ok = 1;
7cca0d81 3552 while (1) {
d211621f 3553 static int try_send;
e5574168 3554 crReturnV;
d211621f 3555 try_send = FALSE;
7cca0d81 3556 if (ispkt) {
3557 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
3558 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
3559 char *data;
3560 int length;
783415f8 3561 unsigned i = ssh2_pkt_getuint32();
3562 struct ssh_channel *c;
3563 c = find234(ssh_channels, &i, ssh_channelfind);
3564 if (!c)
3565 continue; /* nonexistent channel */
7cca0d81 3566 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
3567 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
3568 continue; /* extended but not stderr */
3569 ssh2_pkt_getstring(&data, &length);
d211621f 3570 if (data) {
783415f8 3571 switch (c->type) {
3572 case CHAN_MAINSESSION:
3573 from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
3574 data, length);
3575 break;
3576 case CHAN_X11:
3577 x11_send(c->u.x11.s, data, length);
3578 break;
36c2a3e9 3579 case CHAN_AGENT:
3580 while (length > 0) {
3581 if (c->u.a.lensofar < 4) {
3582 int l = min(4 - c->u.a.lensofar, length);
3583 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
3584 data += l; length -= l; c->u.a.lensofar += l;
3585 }
3586 if (c->u.a.lensofar == 4) {
3587 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
3588 c->u.a.message = smalloc(c->u.a.totallen);
3589 memcpy(c->u.a.message, c->u.a.msglen, 4);
3590 }
3591 if (c->u.a.lensofar >= 4 && length > 0) {
3592 int l = min(c->u.a.totallen - c->u.a.lensofar,
3593 length);
3594 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
3595 data += l; length -= l; c->u.a.lensofar += l;
3596 }
3597 if (c->u.a.lensofar == c->u.a.totallen) {
3598 void *reply, *sentreply;
3599 int replylen;
3600 agent_query(c->u.a.message, c->u.a.totallen,
3601 &reply, &replylen);
3602 if (reply)
3603 sentreply = reply;
3604 else {
3605 /* Fake SSH_AGENT_FAILURE. */
3606 sentreply = "\0\0\0\1\5";
3607 replylen = 5;
3608 }
3609 ssh2_add_channel_data(c, sentreply, replylen);
3610 try_send = TRUE;
3611 if (reply)
3612 sfree(reply);
3613 sfree(c->u.a.message);
3614 c->u.a.lensofar = 0;
3615 }
3616 }
3617 break;
783415f8 3618 }
d211621f 3619 /*
783415f8 3620 * Enlarge the window again at the remote
3621 * side, just in case it ever runs down and
3622 * they fail to send us any more data.
d211621f 3623 */
3624 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
783415f8 3625 ssh2_pkt_adduint32(c->remoteid);
d211621f 3626 ssh2_pkt_adduint32(length);
3627 ssh2_pkt_send();
3628 }
7cca0d81 3629 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
3630 ssh_state = SSH_STATE_CLOSED;
d211621f 3631 logevent("Received disconnect message");
3257deae 3632 crReturnV;
7cca0d81 3633 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
3634 continue; /* exit status et al; ignore (FIXME?) */
d211621f 3635 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
783415f8 3636 unsigned i = ssh2_pkt_getuint32();
3637 struct ssh_channel *c;
3638
3639 c = find234(ssh_channels, &i, ssh_channelfind);
3640 if (!c)
3641 continue; /* nonexistent channel */
3642
3643 if (c->type == CHAN_X11) {
3644 /*
3645 * Remote EOF on an X11 channel means we should
3646 * wrap up and close the channel ourselves.
3647 */
3648 x11_close(c->u.x11.s);
3649 sshfwd_close(c);
36c2a3e9 3650 } else if (c->type == CHAN_AGENT) {
3651 sshfwd_close(c);
3652 }
d211621f 3653 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
783415f8 3654 unsigned i = ssh2_pkt_getuint32();
3655 struct ssh_channel *c;
3656 enum234 e;
3657
3658 c = find234(ssh_channels, &i, ssh_channelfind);
3659 if (!c)
3660 continue; /* nonexistent channel */
3661 if (c->closes == 0) {
3662 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3663 ssh2_pkt_adduint32(c->remoteid);
3664 ssh2_pkt_send();
3665 }
3666 /* Do pre-close processing on the channel. */
3667 switch (c->type) {
3668 case CHAN_MAINSESSION:
3669 break; /* nothing to see here, move along */
3670 case CHAN_X11:
3671 break;
36c2a3e9 3672 case CHAN_AGENT:
3673 break;
783415f8 3674 }
3675 del234(ssh_channels, c);
3676 sfree(c->v2.outbuffer);
3677 sfree(c);
3678
3679 /*
3680 * See if that was the last channel left open.
3681 */
3682 c = first234(ssh_channels, &e);
3683 if (!c) {
d211621f 3684 logevent("All channels closed. Disconnecting");
3685 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
9005f3ba 3686 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3687 ssh2_pkt_addstring("All open channels closed");
3688 ssh2_pkt_addstring("en"); /* language tag */
d211621f 3689 ssh2_pkt_send();
cf6e59d6 3690 ssh_state = SSH_STATE_CLOSED;
3257deae 3691 crReturnV;
d211621f 3692 }
3693 continue; /* remote sends close; ignore (FIXME) */
7cca0d81 3694 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
783415f8 3695 unsigned i = ssh2_pkt_getuint32();
3696 struct ssh_channel *c;
3697 c = find234(ssh_channels, &i, ssh_channelfind);
3698 if (!c)
3699 continue; /* nonexistent channel */
3700 mainchan->v2.remwindow += ssh2_pkt_getuint32();
d211621f 3701 try_send = TRUE;
783415f8 3702 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
3703 char *type;
3704 int typelen;
3705 char *error = NULL;
3706 struct ssh_channel *c;
3707 ssh2_pkt_getstring(&type, &typelen);
3708 c = smalloc(sizeof(struct ssh_channel));
3709
3710 if (typelen == 3 && !memcmp(type, "x11", 3)) {
783415f8 3711 if (!ssh_X11_fwd_enabled)
3712 error = "X11 forwarding is not enabled";
0c6c9a70 3713 else if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
783415f8 3714 error = "Unable to open an X11 connection";
3715 } else {
3716 c->type = CHAN_X11;
3717 }
36c2a3e9 3718 } else if (typelen == 22 &&
3719 !memcmp(type, "auth-agent@openssh.com", 3)) {
3720 if (!ssh_agentfwd_enabled)
3721 error = "Agent forwarding is not enabled";
3722 else {
3723 c->type = CHAN_AGENT; /* identify channel type */
3724 c->u.a.lensofar = 0;
3725 }
783415f8 3726 } else {
3727 error = "Unsupported channel type requested";
3728 }
3729
3730 c->remoteid = ssh2_pkt_getuint32();
3731 if (error) {
3732 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
3733 ssh2_pkt_adduint32(c->remoteid);
3734 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
3735 ssh2_pkt_addstring(error);
3736 ssh2_pkt_addstring("en"); /* language tag */
3737 ssh2_pkt_send();
3738 sfree(c);
3739 } else {
3740 struct ssh_channel *d;
3741 unsigned i;
3742 enum234 e;
3743
3744 for (i=1, d = first234(ssh_channels, &e); d;
3745 d = next234(&e)) {
3746 if (d->localid > i)
3747 break; /* found a free number */
3748 i = d->localid + 1;
3749 }
3750 c->localid = i;
3751 c->closes = 0;
3752 c->v2.remwindow = ssh2_pkt_getuint32();
3753 c->v2.remmaxpkt = ssh2_pkt_getuint32();
3754 c->v2.outbuffer = NULL;
3755 c->v2.outbuflen = c->v2.outbufsize = 0;
3756 add234(ssh_channels, c);
3757 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
3758 ssh2_pkt_adduint32(c->remoteid);
3759 ssh2_pkt_adduint32(c->localid);
3760 ssh2_pkt_adduint32(0x8000UL); /* our window size */
3761 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
3762 ssh2_pkt_send();
3763 }
7cca0d81 3764 } else {
8d5de777 3765 bombout(("Strange packet received: type %d", pktin.type));
3766 crReturnV;
7cca0d81 3767 }
3768 } else {
d211621f 3769 /*
3770 * We have spare data. Add it to the channel buffer.
3771 */
783415f8 3772 ssh2_add_channel_data(mainchan, in, inlen);
d211621f 3773 try_send = TRUE;
7cca0d81 3774 }
d211621f 3775 if (try_send) {
783415f8 3776 enum234 e;
3777 struct ssh_channel *c;
d211621f 3778 /*
783415f8 3779 * Try to send data on all channels if we can.
d211621f 3780 */
783415f8 3781 for (c = first234(ssh_channels, &e); c; c = next234(&e))
3782 ssh2_try_send(c);
d211621f 3783 }
e5574168 3784 }
3785
3786 crFinishV;
3787}
3788
3789/*
7cca0d81 3790 * Handle the top-level SSH2 protocol.
3791 */
3792static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
3793{
3794 if (do_ssh2_transport(in, inlen, ispkt) == 0)
3795 return;
3796 do_ssh2_authconn(in, inlen, ispkt);
3797}
3798
3799/*
8df7a775 3800 * Called to set up the connection.
374330e2 3801 *
3802 * Returns an error message, or NULL on success.
374330e2 3803 */
8df7a775 3804static char *ssh_init (char *host, int port, char **realhost) {
fb09bf1c 3805 char *p;
8f203108 3806
3807#ifdef MSCRYPTOAPI
3808 if(crypto_startup() == 0)
3809 return "Microsoft high encryption pack not installed!";
3810#endif
374330e2 3811
8df7a775 3812 ssh_send_ok = 0;
0965bee0 3813 ssh_editing = 0;
3814 ssh_echoing = 0;
8df7a775 3815
fb09bf1c 3816 p = connect_to_host(host, port, realhost);
3817 if (p != NULL)
3818 return p;
374330e2 3819
374330e2 3820 return NULL;
3821}
3822
3823/*
374330e2 3824 * Called to send data down the Telnet connection.
3825 */
3826static void ssh_send (char *buf, int len) {
f78051a1 3827 if (s == NULL || ssh_protocol == NULL)
374330e2 3828 return;
3829
3830 ssh_protocol(buf, len, 0);
3831}
3832
3833/*
6e48c3fe 3834 * Called to set the size of the window from SSH's POV.
374330e2 3835 */
3836static void ssh_size(void) {
3837 switch (ssh_state) {
3838 case SSH_STATE_BEFORE_SIZE:
3687d221 3839 case SSH_STATE_PREPACKET:
21248260 3840 case SSH_STATE_CLOSED:
374330e2 3841 break; /* do nothing */
3842 case SSH_STATE_INTERMED:
3843 size_needed = TRUE; /* buffer for later */
3844 break;
3845 case SSH_STATE_SESSION:
fef97f43 3846 if (!cfg.nopty) {
6e48c3fe 3847 if (ssh_version == 1) {
3848 send_packet(SSH1_CMSG_WINDOW_SIZE,
3849 PKT_INT, rows, PKT_INT, cols,
3850 PKT_INT, 0, PKT_INT, 0, PKT_END);
3851 } else {
3852 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3853 ssh2_pkt_adduint32(mainchan->remoteid);
3854 ssh2_pkt_addstring("window-change");
3855 ssh2_pkt_addbool(0);
3856 ssh2_pkt_adduint32(cols);
3857 ssh2_pkt_adduint32(rows);
3858 ssh2_pkt_adduint32(0);
3859 ssh2_pkt_adduint32(0);
3860 ssh2_pkt_send();
3861 }
fef97f43 3862 }
3687d221 3863 break;
374330e2 3864 }
3865}
3866
3867/*
6abbf9e3 3868 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3869 * can send an EOF and collect resulting output (e.g. `plink
3870 * hostname sort').
374330e2 3871 */
3872static void ssh_special (Telnet_Special code) {
6abbf9e3 3873 if (code == TS_EOF) {
3687d221 3874 if (ssh_state != SSH_STATE_SESSION) {
3875 /*
3876 * Buffer the EOF in case we are pre-SESSION, so we can
3877 * send it as soon as we reach SESSION.
3878 */
3879 if (code == TS_EOF)
3880 eof_needed = TRUE;
3881 return;
3882 }
67779be7 3883 if (ssh_version == 1) {
6abbf9e3 3884 send_packet(SSH1_CMSG_EOF, PKT_END);
3885 } else {
3886 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
d211621f 3887 ssh2_pkt_adduint32(mainchan->remoteid);
6abbf9e3 3888 ssh2_pkt_send();
3889 }
67779be7 3890 logevent("Sent EOF message");
ec55b220 3891 } else if (code == TS_PING) {
3687d221 3892 if (ssh_state == SSH_STATE_CLOSED || ssh_state == SSH_STATE_PREPACKET)
3893 return;
ec55b220 3894 if (ssh_version == 1) {
3895 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
3896 } else {
3897 ssh2_pkt_init(SSH2_MSG_IGNORE);
3898 ssh2_pkt_addstring_start();
3899 ssh2_pkt_send();
3900 }
6abbf9e3 3901 } else {
3902 /* do nothing */
3903 }
374330e2 3904}
3905
8df7a775 3906static Socket ssh_socket(void) { return s; }
8ccc75b0 3907
3908static int ssh_sendok(void) { return ssh_send_ok; }
fb09bf1c 3909
0965bee0 3910static int ssh_ldisc(int option) {
3911 if (option == LD_ECHO) return ssh_echoing;
3912 if (option == LD_EDIT) return ssh_editing;
3913 return FALSE;
3914}
3915
374330e2 3916Backend ssh_backend = {
3917 ssh_init,
374330e2 3918 ssh_send,
3919 ssh_size,
4017be6d 3920 ssh_special,
8ccc75b0 3921 ssh_socket,
97db3be4 3922 ssh_sendok,
0965bee0 3923 ssh_ldisc,
97db3be4 3924 22
374330e2 3925};