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