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