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