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