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