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