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