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