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