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