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