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