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