Add support for the OpenSSH SSH2 agent protocol.
[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
0c6c9a70 167extern char *x11_init (Socket *, char *, void *);
9c964e85 168extern void x11_close (Socket);
169extern void x11_send (Socket , char *, int);
170extern void x11_invent_auth(char *, int, char *, int);
171
5e8358ad 172/*
173 * Ciphers for SSH2. We miss out single-DES because it isn't
174 * supported; also 3DES and Blowfish are both done differently from
175 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
176 * endianness and different-sized keys.)
5e8358ad 177 */
0a3f1d48 178const static struct ssh2_ciphers *ciphers[] = {
179 &ssh2_aes,
180 &ssh2_blowfish,
181 &ssh2_3des,
8479e33c 182};
e5574168 183
a92dd380 184const static struct ssh_kex *kex_algs[] = {
185#ifdef DO_DIFFIE_HELLMAN_GEX
186 &ssh_diffiehellman_gex,
187#endif
188 &ssh_diffiehellman };
e5574168 189
85cc02bb 190const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
e5574168 191
d39f364a 192static void nullmac_key(unsigned char *key) { }
e5574168 193static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
194static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
57476f6b 195const static struct ssh_mac ssh_mac_none = {
d39f364a 196 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
e5574168 197};
8b2715b2 198const static struct ssh_mac *macs[] = {
199 &ssh_sha1, &ssh_md5, &ssh_mac_none };
200const static struct ssh_mac *buggymacs[] = {
201 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none };
e5574168 202
4ba9b64b 203static void ssh_comp_none_init(void) { }
204static int ssh_comp_none_block(unsigned char *block, int len,
205 unsigned char **outblock, int *outlen) {
206 return 0;
207}
57476f6b 208const static struct ssh_compress ssh_comp_none = {
4ba9b64b 209 "none",
210 ssh_comp_none_init, ssh_comp_none_block,
211 ssh_comp_none_init, ssh_comp_none_block
e5574168 212};
4ba9b64b 213extern const struct ssh_compress ssh_zlib;
214const static struct ssh_compress *compressions[] = {
215 &ssh_zlib, &ssh_comp_none };
374330e2 216
783415f8 217enum { /* channel types */
218 CHAN_MAINSESSION,
219 CHAN_X11,
220 CHAN_AGENT,
221};
222
dacbd0e8 223/*
224 * 2-3-4 tree storing channels.
225 */
226struct ssh_channel {
d211621f 227 unsigned remoteid, localid;
dacbd0e8 228 int type;
229 int closes;
783415f8 230 struct ssh2_data_channel {
231 unsigned char *outbuffer;
232 unsigned outbuflen, outbufsize;
233 unsigned remwindow, remmaxpkt;
234 } v2;
dacbd0e8 235 union {
236 struct ssh_agent_channel {
237 unsigned char *message;
238 unsigned char msglen[4];
239 int lensofar, totallen;
240 } a;
9c964e85 241 struct ssh_x11_channel {
242 Socket s;
783415f8 243 } x11;
dacbd0e8 244 } u;
245};
57476f6b 246
247struct Packet {
248 long length;
249 int type;
250 unsigned char *data;
251 unsigned char *body;
252 long savedpos;
253 long maxlen;
254};
255
0db56f73 256static SHA_State exhash, exhashbase;
57476f6b 257
8df7a775 258static Socket s = NULL;
57476f6b 259
260static unsigned char session_key[32];
4ba9b64b 261static int ssh1_compressing;
db7d555c 262static int ssh_agentfwd_enabled;
9c964e85 263static int ssh_X11_fwd_enabled;
57476f6b 264static const struct ssh_cipher *cipher = NULL;
0a3f1d48 265static const struct ssh2_cipher *cscipher = NULL;
266static const struct ssh2_cipher *sccipher = NULL;
57476f6b 267static const struct ssh_mac *csmac = NULL;
268static const struct ssh_mac *scmac = NULL;
269static const struct ssh_compress *cscomp = NULL;
270static const struct ssh_compress *sccomp = NULL;
271static const struct ssh_kex *kex = NULL;
e055a386 272static const struct ssh_signkey *hostkey = NULL;
65a22376 273static unsigned char ssh2_session_id[20];
57476f6b 274int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
275
276static char *savedhost;
277static int savedport;
278static int ssh_send_ok;
0965bee0 279static int ssh_echoing, ssh_editing;
57476f6b 280
dacbd0e8 281static tree234 *ssh_channels; /* indexed by local id */
57476f6b 282static struct ssh_channel *mainchan; /* primary session channel */
283
284static enum {
3687d221 285 SSH_STATE_PREPACKET,
57476f6b 286 SSH_STATE_BEFORE_SIZE,
287 SSH_STATE_INTERMED,
288 SSH_STATE_SESSION,
289 SSH_STATE_CLOSED
3687d221 290} ssh_state = SSH_STATE_PREPACKET;
57476f6b 291
3687d221 292static int size_needed = FALSE, eof_needed = FALSE;
57476f6b 293
294static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
295static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
b185170a 296static unsigned char *deferred_send_data = NULL;
297static int deferred_len = 0, deferred_size = 0;
57476f6b 298
299static int ssh_version;
300static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
301static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
302static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
303static void ssh_size(void);
3687d221 304static void ssh_special (Telnet_Special);
783415f8 305static void ssh2_try_send(struct ssh_channel *c);
306static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
57476f6b 307
308static int (*s_rdpkt)(unsigned char **data, int *datalen);
309
310static struct rdpkt1_state_tag {
311 long len, pad, biglen, to_read;
312 unsigned long realcrc, gotcrc;
313 unsigned char *p;
314 int i;
315 int chunk;
316} rdpkt1_state;
317
960e736a 318static struct rdpkt2_state_tag {
319 long len, pad, payload, packetlen, maclen;
320 int i;
321 int cipherblk;
322 unsigned long incoming_sequence;
323} rdpkt2_state;
324
dacbd0e8 325static int ssh_channelcmp(void *av, void *bv) {
326 struct ssh_channel *a = (struct ssh_channel *)av;
327 struct ssh_channel *b = (struct ssh_channel *)bv;
328 if (a->localid < b->localid) return -1;
329 if (a->localid > b->localid) return +1;
330 return 0;
331}
332static int ssh_channelfind(void *av, void *bv) {
d211621f 333 unsigned *a = (unsigned *)av;
dacbd0e8 334 struct ssh_channel *b = (struct ssh_channel *)bv;
335 if (*a < b->localid) return -1;
336 if (*a > b->localid) return +1;
337 return 0;
338}
339
374330e2 340static void c_write (char *buf, int len) {
67779be7 341 if ((flags & FLAG_STDERR)) {
4017be6d 342 int i;
343 for (i = 0; i < len; i++)
344 if (buf[i] != '\r')
345 fputc(buf[i], stderr);
fb09bf1c 346 return;
347 }
fe50e814 348 from_backend(1, buf, len);
3bdaf79d 349}
350
1408a877 351static void c_write_str (char *buf) {
352 c_write(buf, strlen(buf));
353}
354
fb09bf1c 355/*
356 * Collect incoming data in the incoming packet buffer.
e5574168 357 * Decipher and verify the packet when it is completely read.
358 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
fb09bf1c 359 * Update the *data and *datalen variables.
360 * Return the additional nr of bytes needed, or 0 when
361 * a complete packet is available.
362 */
e5574168 363static int ssh1_rdpkt(unsigned char **data, int *datalen)
fb09bf1c 364{
57476f6b 365 struct rdpkt1_state_tag *st = &rdpkt1_state;
374330e2 366
367 crBegin;
374330e2 368
fb09bf1c 369next_packet:
37508af4 370
fb09bf1c 371 pktin.type = 0;
372 pktin.length = 0;
374330e2 373
57476f6b 374 for (st->i = st->len = 0; st->i < 4; st->i++) {
fb09bf1c 375 while ((*datalen) == 0)
57476f6b 376 crReturn(4-st->i);
377 st->len = (st->len << 8) + **data;
fb09bf1c 378 (*data)++, (*datalen)--;
379 }
374330e2 380
fb09bf1c 381#ifdef FWHACK
57476f6b 382 if (st->len == 0x52656d6f) { /* "Remo"te server has closed ... */
383 st->len = 0x300; /* big enough to carry to end */
fb09bf1c 384 }
385#endif
374330e2 386
57476f6b 387 st->pad = 8 - (st->len % 8);
388 st->biglen = st->len + st->pad;
389 pktin.length = st->len - 5;
fb09bf1c 390
57476f6b 391 if (pktin.maxlen < st->biglen) {
392 pktin.maxlen = st->biglen;
dcbde236 393 pktin.data = (pktin.data == NULL ? smalloc(st->biglen+APIEXTRA) :
394 srealloc(pktin.data, st->biglen+APIEXTRA));
fb09bf1c 395 if (!pktin.data)
396 fatalbox("Out of memory");
397 }
374330e2 398
57476f6b 399 st->to_read = st->biglen;
400 st->p = pktin.data;
401 while (st->to_read > 0) {
402 st->chunk = st->to_read;
fb09bf1c 403 while ((*datalen) == 0)
57476f6b 404 crReturn(st->to_read);
405 if (st->chunk > (*datalen))
406 st->chunk = (*datalen);
407 memcpy(st->p, *data, st->chunk);
408 *data += st->chunk;
409 *datalen -= st->chunk;
410 st->p += st->chunk;
411 st->to_read -= st->chunk;
fb09bf1c 412 }
374330e2 413
fb09bf1c 414 if (cipher)
57476f6b 415 cipher->decrypt(pktin.data, st->biglen);
698a5108 416#if 0
417 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
418 for (st->i = 0; st->i < st->biglen; st->i++)
419 debug((" %02x", (unsigned char)pktin.data[st->i]));
420 debug(("\r\n"));
421#endif
374330e2 422
57476f6b 423 st->realcrc = crc32(pktin.data, st->biglen-4);
424 st->gotcrc = GET_32BIT(pktin.data+st->biglen-4);
425 if (st->gotcrc != st->realcrc) {
8d5de777 426 bombout(("Incorrect CRC received on packet"));
427 crReturn(0);
fb09bf1c 428 }
572f871e 429
4ba9b64b 430 pktin.body = pktin.data + st->pad + 1;
431
432 if (ssh1_compressing) {
433 unsigned char *decompblk;
434 int decomplen;
435#if 0
436 int i;
437 debug(("Packet payload pre-decompression:\n"));
438 for (i = -1; i < pktin.length; i++)
439 debug((" %02x", (unsigned char)pktin.body[i]));
440 debug(("\r\n"));
441#endif
442 zlib_decompress_block(pktin.body-1, pktin.length+1,
443 &decompblk, &decomplen);
444
445 if (pktin.maxlen < st->pad + decomplen) {
446 pktin.maxlen = st->pad + decomplen;
dcbde236 447 pktin.data = srealloc(pktin.data, pktin.maxlen+APIEXTRA);
58298665 448 pktin.body = pktin.data + st->pad + 1;
4ba9b64b 449 if (!pktin.data)
450 fatalbox("Out of memory");
451 }
452
453 memcpy(pktin.body-1, decompblk, decomplen);
dcbde236 454 sfree(decompblk);
4ba9b64b 455 pktin.length = decomplen-1;
456#if 0
457 debug(("Packet payload post-decompression:\n"));
458 for (i = -1; i < pktin.length; i++)
459 debug((" %02x", (unsigned char)pktin.body[i]));
460 debug(("\r\n"));
461#endif
462 }
463
e5574168 464 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
465 pktin.type == SSH1_SMSG_STDERR_DATA ||
466 pktin.type == SSH1_MSG_DEBUG ||
18515c51 467 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
468 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
fb09bf1c 469 long strlen = GET_32BIT(pktin.body);
8d5de777 470 if (strlen + 4 != pktin.length) {
471 bombout(("Received data packet with bogus string length"));
472 crReturn(0);
473 }
fb09bf1c 474 }
475
4ba9b64b 476 pktin.type = pktin.body[-1];
477
e5574168 478 if (pktin.type == SSH1_MSG_DEBUG) {
fb09bf1c 479 /* log debug message */
480 char buf[80];
481 int strlen = GET_32BIT(pktin.body);
482 strcpy(buf, "Remote: ");
483 if (strlen > 70) strlen = 70;
484 memcpy(buf+8, pktin.body+4, strlen);
485 buf[8+strlen] = '\0';
486 logevent(buf);
487 goto next_packet;
e5574168 488 } else if (pktin.type == SSH1_MSG_IGNORE) {
fb09bf1c 489 /* do nothing */
490 goto next_packet;
491 }
492
493 crFinish(0);
494}
495
e5574168 496static int ssh2_rdpkt(unsigned char **data, int *datalen)
497{
960e736a 498 struct rdpkt2_state_tag *st = &rdpkt2_state;
e5574168 499
500 crBegin;
501
502next_packet:
e5574168 503 pktin.type = 0;
504 pktin.length = 0;
960e736a 505 if (sccipher)
506 st->cipherblk = sccipher->blksize;
e5574168 507 else
960e736a 508 st->cipherblk = 8;
509 if (st->cipherblk < 8)
510 st->cipherblk = 8;
511
512 if (pktin.maxlen < st->cipherblk) {
513 pktin.maxlen = st->cipherblk;
dcbde236 514 pktin.data = (pktin.data == NULL ? smalloc(st->cipherblk+APIEXTRA) :
515 srealloc(pktin.data, st->cipherblk+APIEXTRA));
e5574168 516 if (!pktin.data)
517 fatalbox("Out of memory");
518 }
519
520 /*
521 * Acquire and decrypt the first block of the packet. This will
522 * contain the length and padding details.
523 */
960e736a 524 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
e5574168 525 while ((*datalen) == 0)
960e736a 526 crReturn(st->cipherblk-st->i);
527 pktin.data[st->i] = *(*data)++;
e5574168 528 (*datalen)--;
529 }
530#ifdef FWHACK
531 if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
532 /* FIXME */
533 }
534#endif
535 if (sccipher)
960e736a 536 sccipher->decrypt(pktin.data, st->cipherblk);
e5574168 537
538 /*
539 * Now get the length and padding figures.
540 */
960e736a 541 st->len = GET_32BIT(pktin.data);
542 st->pad = pktin.data[4];
e5574168 543
544 /*
545 * This enables us to deduce the payload length.
546 */
960e736a 547 st->payload = st->len - st->pad - 1;
e5574168 548
960e736a 549 pktin.length = st->payload + 5;
e5574168 550
551 /*
552 * So now we can work out the total packet length.
553 */
960e736a 554 st->packetlen = st->len + 4;
555 st->maclen = scmac ? scmac->len : 0;
e5574168 556
557 /*
558 * Adjust memory allocation if packet is too big.
559 */
960e736a 560 if (pktin.maxlen < st->packetlen+st->maclen) {
561 pktin.maxlen = st->packetlen+st->maclen;
dcbde236 562 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
563 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
e5574168 564 if (!pktin.data)
565 fatalbox("Out of memory");
566 }
567
568 /*
569 * Read and decrypt the remainder of the packet.
570 */
960e736a 571 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen; st->i++) {
e5574168 572 while ((*datalen) == 0)
960e736a 573 crReturn(st->packetlen + st->maclen - st->i);
574 pktin.data[st->i] = *(*data)++;
e5574168 575 (*datalen)--;
576 }
577 /* Decrypt everything _except_ the MAC. */
578 if (sccipher)
960e736a 579 sccipher->decrypt(pktin.data + st->cipherblk,
580 st->packetlen - st->cipherblk);
e5574168 581
7cca0d81 582#if 0
960e736a 583 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
584 for (st->i = 0; st->i < st->packetlen; st->i++)
585 debug((" %02x", (unsigned char)pktin.data[st->i]));
d39f364a 586 debug(("\r\n"));
7cca0d81 587#endif
d39f364a 588
e5574168 589 /*
590 * Check the MAC.
591 */
960e736a 592 if (scmac && !scmac->verify(pktin.data, st->len+4, st->incoming_sequence)) {
8d5de777 593 bombout(("Incorrect MAC received on packet"));
594 crReturn(0);
595 }
960e736a 596 st->incoming_sequence++; /* whether or not we MACed */
e5574168 597
4ba9b64b 598 /*
599 * Decompress packet payload.
600 */
601 {
602 unsigned char *newpayload;
603 int newlen;
604 if (sccomp && sccomp->decompress(pktin.data+5, pktin.length-5,
605 &newpayload, &newlen)) {
606 if (pktin.maxlen < newlen+5) {
607 pktin.maxlen = newlen+5;
dcbde236 608 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
609 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
4ba9b64b 610 if (!pktin.data)
611 fatalbox("Out of memory");
612 }
613 pktin.length = 5 + newlen;
614 memcpy(pktin.data+5, newpayload, newlen);
615#if 0
616 debug(("Post-decompression payload:\r\n"));
617 for (st->i = 0; st->i < newlen; st->i++)
618 debug((" %02x", (unsigned char)pktin.data[5+st->i]));
619 debug(("\r\n"));
620#endif
621
dcbde236 622 sfree(newpayload);
4ba9b64b 623 }
624 }
625
e5574168 626 pktin.savedpos = 6;
627 pktin.type = pktin.data[5];
e5574168 628
7cca0d81 629 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
630 goto next_packet; /* FIXME: print DEBUG message */
e5574168 631
632 crFinish(0);
633}
634
4ba9b64b 635static void ssh1_pktout_size(int len) {
374330e2 636 int pad, biglen;
637
638 len += 5; /* type and CRC */
639 pad = 8 - (len%8);
640 biglen = len + pad;
641
642 pktout.length = len-5;
643 if (pktout.maxlen < biglen) {
644 pktout.maxlen = biglen;
8f203108 645#ifdef MSCRYPTOAPI
fb09bf1c 646 /* Allocate enough buffer space for extra block
8f203108 647 * for MS CryptEncrypt() */
dcbde236 648 pktout.data = (pktout.data == NULL ? smalloc(biglen+12) :
649 srealloc(pktout.data, biglen+12));
8f203108 650#else
dcbde236 651 pktout.data = (pktout.data == NULL ? smalloc(biglen+4) :
652 srealloc(pktout.data, biglen+4));
8f203108 653#endif
374330e2 654 if (!pktout.data)
655 fatalbox("Out of memory");
656 }
4ba9b64b 657 pktout.body = pktout.data+4+pad+1;
658}
374330e2 659
4ba9b64b 660static void s_wrpkt_start(int type, int len) {
661 ssh1_pktout_size(len);
374330e2 662 pktout.type = type;
374330e2 663}
664
665static void s_wrpkt(void) {
666 int pad, len, biglen, i;
667 unsigned long crc;
668
4ba9b64b 669 pktout.body[-1] = pktout.type;
670
671 if (ssh1_compressing) {
672 unsigned char *compblk;
673 int complen;
674#if 0
675 debug(("Packet payload pre-compression:\n"));
676 for (i = -1; i < pktout.length; i++)
677 debug((" %02x", (unsigned char)pktout.body[i]));
678 debug(("\r\n"));
679#endif
680 zlib_compress_block(pktout.body-1, pktout.length+1,
681 &compblk, &complen);
682 ssh1_pktout_size(complen-1);
683 memcpy(pktout.body-1, compblk, complen);
dcbde236 684 sfree(compblk);
4ba9b64b 685#if 0
686 debug(("Packet payload post-compression:\n"));
687 for (i = -1; i < pktout.length; i++)
688 debug((" %02x", (unsigned char)pktout.body[i]));
689 debug(("\r\n"));
690#endif
691 }
692
374330e2 693 len = pktout.length + 5; /* type and CRC */
694 pad = 8 - (len%8);
695 biglen = len + pad;
696
374330e2 697 for (i=0; i<pad; i++)
698 pktout.data[i+4] = random_byte();
699 crc = crc32(pktout.data+4, biglen-4);
fb09bf1c 700 PUT_32BIT(pktout.data+biglen, crc);
701 PUT_32BIT(pktout.data, len);
374330e2 702
698a5108 703#if 0
704 debug(("Sending packet len=%d\r\n", biglen+4));
705 for (i = 0; i < biglen+4; i++)
706 debug((" %02x", (unsigned char)pktout.data[i]));
707 debug(("\r\n"));
708#endif
374330e2 709 if (cipher)
710 cipher->encrypt(pktout.data+4, biglen);
711
8df7a775 712 sk_write(s, pktout.data, biglen+4);
374330e2 713}
714
fb09bf1c 715/*
716 * Construct a packet with the specified contents and
717 * send it to the server.
718 */
719static void send_packet(int pkttype, ...)
720{
721 va_list args;
722 unsigned char *p, *argp, argchar;
723 unsigned long argint;
724 int pktlen, argtype, arglen;
7cca0d81 725 Bignum bn;
fb09bf1c 726
727 pktlen = 0;
728 va_start(args, pkttype);
729 while ((argtype = va_arg(args, int)) != PKT_END) {
730 switch (argtype) {
731 case PKT_INT:
732 (void) va_arg(args, int);
733 pktlen += 4;
734 break;
735 case PKT_CHAR:
736 (void) va_arg(args, char);
737 pktlen++;
738 break;
739 case PKT_DATA:
740 (void) va_arg(args, unsigned char *);
741 arglen = va_arg(args, int);
742 pktlen += arglen;
743 break;
744 case PKT_STR:
745 argp = va_arg(args, unsigned char *);
746 arglen = strlen(argp);
747 pktlen += 4 + arglen;
748 break;
7cca0d81 749 case PKT_BIGNUM:
750 bn = va_arg(args, Bignum);
5c58ad2d 751 pktlen += ssh1_bignum_length(bn);
7cca0d81 752 break;
fb09bf1c 753 default:
754 assert(0);
755 }
756 }
757 va_end(args);
758
759 s_wrpkt_start(pkttype, pktlen);
760 p = pktout.body;
761
762 va_start(args, pkttype);
763 while ((argtype = va_arg(args, int)) != PKT_END) {
764 switch (argtype) {
765 case PKT_INT:
766 argint = va_arg(args, int);
767 PUT_32BIT(p, argint);
768 p += 4;
769 break;
770 case PKT_CHAR:
771 argchar = va_arg(args, unsigned char);
772 *p = argchar;
773 p++;
774 break;
775 case PKT_DATA:
776 argp = va_arg(args, unsigned char *);
777 arglen = va_arg(args, int);
778 memcpy(p, argp, arglen);
779 p += arglen;
780 break;
781 case PKT_STR:
782 argp = va_arg(args, unsigned char *);
783 arglen = strlen(argp);
784 PUT_32BIT(p, arglen);
785 memcpy(p + 4, argp, arglen);
786 p += 4 + arglen;
787 break;
7cca0d81 788 case PKT_BIGNUM:
789 bn = va_arg(args, Bignum);
5c58ad2d 790 p += ssh1_write_bignum(p, bn);
7cca0d81 791 break;
fb09bf1c 792 }
793 }
794 va_end(args);
795
796 s_wrpkt();
797}
798
9697bfd2 799static int ssh_versioncmp(char *a, char *b) {
800 char *ae, *be;
801 unsigned long av, bv;
802
43aa02a7 803 av = strtoul(a, &ae, 10);
804 bv = strtoul(b, &be, 10);
9697bfd2 805 if (av != bv) return (av < bv ? -1 : +1);
806 if (*ae == '.') ae++;
807 if (*be == '.') be++;
43aa02a7 808 av = strtoul(ae, &ae, 10);
809 bv = strtoul(be, &be, 10);
9697bfd2 810 if (av != bv) return (av < bv ? -1 : +1);
811 return 0;
812}
813
e5574168 814
815/*
a92dd380 816 * Utility routines for putting an SSH-protocol `string' and
817 * `uint32' into a SHA state.
e5574168 818 */
819#include <stdio.h>
75cab814 820static void sha_string(SHA_State *s, void *str, int len) {
e5574168 821 unsigned char lenblk[4];
e5574168 822 PUT_32BIT(lenblk, len);
e5574168 823 SHA_Bytes(s, lenblk, 4);
e5574168 824 SHA_Bytes(s, str, len);
825}
826
a92dd380 827static void sha_uint32(SHA_State *s, unsigned i) {
828 unsigned char intblk[4];
829 PUT_32BIT(intblk, i);
830 SHA_Bytes(s, intblk, 4);
831}
832
7cca0d81 833/*
834 * SSH2 packet construction functions.
835 */
783415f8 836static void ssh2_pkt_ensure(int length) {
837 if (pktout.maxlen < length) {
838 pktout.maxlen = length + 256;
dcbde236 839 pktout.data = (pktout.data == NULL ? smalloc(pktout.maxlen+APIEXTRA) :
840 srealloc(pktout.data, pktout.maxlen+APIEXTRA));
7cca0d81 841 if (!pktout.data)
842 fatalbox("Out of memory");
843 }
783415f8 844}
845static void ssh2_pkt_adddata(void *data, int len) {
846 pktout.length += len;
847 ssh2_pkt_ensure(pktout.length);
7cca0d81 848 memcpy(pktout.data+pktout.length-len, data, len);
849}
75cab814 850static void ssh2_pkt_addbyte(unsigned char byte) {
7cca0d81 851 ssh2_pkt_adddata(&byte, 1);
852}
75cab814 853static void ssh2_pkt_init(int pkt_type) {
7cca0d81 854 pktout.length = 5;
855 ssh2_pkt_addbyte((unsigned char)pkt_type);
856}
75cab814 857static void ssh2_pkt_addbool(unsigned char value) {
7cca0d81 858 ssh2_pkt_adddata(&value, 1);
859}
75cab814 860static void ssh2_pkt_adduint32(unsigned long value) {
7cca0d81 861 unsigned char x[4];
862 PUT_32BIT(x, value);
863 ssh2_pkt_adddata(x, 4);
864}
75cab814 865static void ssh2_pkt_addstring_start(void) {
7cca0d81 866 ssh2_pkt_adduint32(0);
867 pktout.savedpos = pktout.length;
868}
75cab814 869static void ssh2_pkt_addstring_str(char *data) {
7cca0d81 870 ssh2_pkt_adddata(data, strlen(data));
871 PUT_32BIT(pktout.data + pktout.savedpos - 4,
872 pktout.length - pktout.savedpos);
873}
75cab814 874static void ssh2_pkt_addstring_data(char *data, int len) {
7cca0d81 875 ssh2_pkt_adddata(data, len);
876 PUT_32BIT(pktout.data + pktout.savedpos - 4,
877 pktout.length - pktout.savedpos);
878}
75cab814 879static void ssh2_pkt_addstring(char *data) {
7cca0d81 880 ssh2_pkt_addstring_start();
881 ssh2_pkt_addstring_str(data);
882}
75cab814 883static char *ssh2_mpint_fmt(Bignum b, int *len) {
7cca0d81 884 unsigned char *p;
3709bfe9 885 int i, n = (ssh1_bignum_bitcount(b)+7)/8;
886 p = smalloc(n + 1);
7cca0d81 887 if (!p)
888 fatalbox("out of memory");
889 p[0] = 0;
3709bfe9 890 for (i = 1; i <= n; i++)
891 p[i] = bignum_byte(b, n-i);
7cca0d81 892 i = 0;
3709bfe9 893 while (i <= n && p[i] == 0 && (p[i+1] & 0x80) == 0)
7cca0d81 894 i++;
3709bfe9 895 memmove(p, p+i, n+1-i);
896 *len = n+1-i;
7cca0d81 897 return p;
898}
75cab814 899static void ssh2_pkt_addmp(Bignum b) {
7cca0d81 900 unsigned char *p;
901 int len;
902 p = ssh2_mpint_fmt(b, &len);
903 ssh2_pkt_addstring_start();
904 ssh2_pkt_addstring_data(p, len);
dcbde236 905 sfree(p);
7cca0d81 906}
b185170a 907
908/*
909 * Construct an SSH2 final-form packet: compress it, encrypt it,
910 * put the MAC on it. Final packet, ready to be sent, is stored in
911 * pktout.data. Total length is returned.
912 */
913static int ssh2_pkt_construct(void) {
7cca0d81 914 int cipherblk, maclen, padding, i;
915 static unsigned long outgoing_sequence = 0;
916
917 /*
4ba9b64b 918 * Compress packet payload.
919 */
920#if 0
921 debug(("Pre-compression payload:\r\n"));
922 for (i = 5; i < pktout.length; i++)
923 debug((" %02x", (unsigned char)pktout.data[i]));
924 debug(("\r\n"));
925#endif
926 {
927 unsigned char *newpayload;
928 int newlen;
929 if (cscomp && cscomp->compress(pktout.data+5, pktout.length-5,
930 &newpayload, &newlen)) {
931 pktout.length = 5;
932 ssh2_pkt_adddata(newpayload, newlen);
dcbde236 933 sfree(newpayload);
4ba9b64b 934 }
935 }
936
937 /*
7cca0d81 938 * Add padding. At least four bytes, and must also bring total
939 * length (minus MAC) up to a multiple of the block size.
940 */
8479e33c 941 cipherblk = cscipher ? cscipher->blksize : 8; /* block size */
7cca0d81 942 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
943 padding = 4;
944 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
783415f8 945 maclen = csmac ? csmac->len : 0;
946 ssh2_pkt_ensure(pktout.length + padding + maclen);
7cca0d81 947 pktout.data[4] = padding;
948 for (i = 0; i < padding; i++)
949 pktout.data[pktout.length + i] = random_byte();
950 PUT_32BIT(pktout.data, pktout.length + padding - 4);
951 if (csmac)
952 csmac->generate(pktout.data, pktout.length + padding,
953 outgoing_sequence);
954 outgoing_sequence++; /* whether or not we MACed */
955
956#if 0
957 debug(("Sending packet len=%d\r\n", pktout.length+padding));
958 for (i = 0; i < pktout.length+padding; i++)
959 debug((" %02x", (unsigned char)pktout.data[i]));
960 debug(("\r\n"));
961#endif
962
963 if (cscipher)
964 cscipher->encrypt(pktout.data, pktout.length + padding);
7cca0d81 965
b185170a 966 /* Ready-to-send packet starts at pktout.data. We return length. */
967 return pktout.length + padding + maclen;
968}
969
970/*
971 * Construct and send an SSH2 packet immediately.
972 */
973static void ssh2_pkt_send(void) {
974 int len = ssh2_pkt_construct();
975 sk_write(s, pktout.data, len);
976}
977
978/*
979 * Construct an SSH2 packet and add it to a deferred data block.
980 * Useful for sending multiple packets in a single sk_write() call,
981 * to prevent a traffic-analysing listener from being able to work
982 * out the length of any particular packet (such as the password
983 * packet).
984 *
985 * Note that because SSH2 sequence-numbers its packets, this can
986 * NOT be used as an m4-style `defer' allowing packets to be
987 * constructed in one order and sent in another.
988 */
989static void ssh2_pkt_defer(void) {
990 int len = ssh2_pkt_construct();
991 if (deferred_len + len > deferred_size) {
992 deferred_size = deferred_len + len + 128;
993 deferred_send_data = srealloc(deferred_send_data, deferred_size);
994 }
995 memcpy(deferred_send_data+deferred_len, pktout.data, len);
996 deferred_len += len;
997}
998
999/*
1000 * Send the whole deferred data block constructed by
1001 * ssh2_pkt_defer().
1002 */
1003static void ssh2_pkt_defersend(void) {
1004 sk_write(s, deferred_send_data, deferred_len);
1005 deferred_len = deferred_size = 0;
1006 sfree(deferred_send_data);
1007 deferred_send_data = NULL;
7cca0d81 1008}
1009
1010#if 0
1011void bndebug(char *string, Bignum b) {
1012 unsigned char *p;
1013 int i, len;
1014 p = ssh2_mpint_fmt(b, &len);
1015 debug(("%s", string));
1016 for (i = 0; i < len; i++)
1017 debug((" %02x", p[i]));
1018 debug(("\r\n"));
dcbde236 1019 sfree(p);
7cca0d81 1020}
1021#endif
1022
75cab814 1023static void sha_mpint(SHA_State *s, Bignum b) {
7cca0d81 1024 unsigned char *p;
1025 int len;
1026 p = ssh2_mpint_fmt(b, &len);
1027 sha_string(s, p, len);
dcbde236 1028 sfree(p);
7cca0d81 1029}
1030
1031/*
1032 * SSH2 packet decode functions.
1033 */
75cab814 1034static unsigned long ssh2_pkt_getuint32(void) {
7cca0d81 1035 unsigned long value;
1036 if (pktin.length - pktin.savedpos < 4)
1037 return 0; /* arrgh, no way to decline (FIXME?) */
1038 value = GET_32BIT(pktin.data+pktin.savedpos);
1039 pktin.savedpos += 4;
1040 return value;
1041}
65a22376 1042static int ssh2_pkt_getbool(void) {
1043 unsigned long value;
1044 if (pktin.length - pktin.savedpos < 1)
1045 return 0; /* arrgh, no way to decline (FIXME?) */
1046 value = pktin.data[pktin.savedpos] != 0;
1047 pktin.savedpos++;
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:
1408a877 1401 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
0a3f1d48 1402 cipher_type = SSH_CIPHER_3DES;
1403 break;
1404 }
bea1ef5f 1405 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1408a877 1406 c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
bea1ef5f 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) {
1408a877 1446 c_write_str("login as: ");
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) {
1408a877 1457 c_write_str("\b \b");
374330e2 1458 pos--;
1459 }
1460 break;
1461 case 21: case 27:
1462 while (pos > 0) {
1408a877 1463 c_write_str("\b \b");
374330e2 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 }
1408a877 1480 c_write_str("\r\n");
374330e2 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");
1408a877 1495 c_write_str(userlog);
3c8e959b 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) {
1408a877 1592 c_write_str("Authenticated using RSA key \"");
c4fa2fce 1593 c_write(commentp, commentlen);
1408a877 1594 c_write_str("\" from agent\r\n");
c4fa2fce 1595 }
5c58ad2d 1596 authed = TRUE;
1597 } else
1598 logevent("Pageant's response not accepted");
1599 } else {
1600 logevent("Pageant failed to answer challenge");
dcbde236 1601 sfree(ret);
5c58ad2d 1602 }
1603 } else {
1604 logevent("No reply received from Pageant");
1605 }
1606 }
1607 freebn(key.exponent);
1608 freebn(key.modulus);
1609 freebn(challenge);
1610 if (authed)
1611 break;
1612 }
1613 }
1614 if (authed)
1615 break;
1616 }
7cca0d81 1617 if (*cfg.keyfile && !tried_publickey)
1618 pwpkt_type = SSH1_CMSG_AUTH_RSA;
fb09bf1c 1619
a52f067e 1620 if (pktin.type == SSH1_SMSG_FAILURE &&
1621 cfg.try_tis_auth &&
1622 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1623 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1624 logevent("Requested TIS authentication");
1625 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1626 crWaitUntil(ispkt);
1627 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1628 logevent("TIS authentication declined");
1629 if (flags & FLAG_INTERACTIVE)
1408a877 1630 c_write_str("TIS authentication refused.\r\n");
a52f067e 1631 } else {
1632 int challengelen = ((pktin.body[0] << 24) |
1633 (pktin.body[1] << 16) |
1634 (pktin.body[2] << 8) |
1635 (pktin.body[3]));
1636 logevent("Received TIS challenge");
1637 if (challengelen > sizeof(prompt)-1)
1638 challengelen = sizeof(prompt)-1; /* prevent overrun */
1639 memcpy(prompt, pktin.body+4, challengelen);
1640 prompt[challengelen] = '\0';
1641 }
1642 }
1643 if (pktin.type == SSH1_SMSG_FAILURE &&
1644 cfg.try_tis_auth &&
1645 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1646 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1647 logevent("Requested CryptoCard authentication");
1648 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1649 crWaitUntil(ispkt);
1650 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1651 logevent("CryptoCard authentication declined");
1408a877 1652 c_write_str("CryptoCard authentication refused.\r\n");
a52f067e 1653 } else {
1654 int challengelen = ((pktin.body[0] << 24) |
1655 (pktin.body[1] << 16) |
1656 (pktin.body[2] << 8) |
1657 (pktin.body[3]));
1658 logevent("Received CryptoCard challenge");
1659 if (challengelen > sizeof(prompt)-1)
1660 challengelen = sizeof(prompt)-1; /* prevent overrun */
1661 memcpy(prompt, pktin.body+4, challengelen);
1662 strncpy(prompt + challengelen, "\r\nResponse : ",
1663 sizeof(prompt)-challengelen);
1664 prompt[sizeof(prompt)-1] = '\0';
1665 }
1666 }
1667 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1668 sprintf(prompt, "%.90s@%.90s's password: ",
b585ec46 1669 username, savedhost);
a52f067e 1670 }
1671 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1672 char *comment = NULL;
1673 if (flags & FLAG_VERBOSE)
1408a877 1674 c_write_str("Trying public key authentication.\r\n");
a52f067e 1675 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1676 if (flags & FLAG_VERBOSE)
1408a877 1677 c_write_str("No passphrase required.\r\n");
a52f067e 1678 goto tryauth;
1679 }
1680 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
dcbde236 1681 sfree(comment);
a52f067e 1682 }
1683
d8426c54 1684 if (ssh_get_password) {
85ee8208 1685 if (!ssh_get_password(prompt, password, sizeof(password))) {
1686 /*
1687 * get_password failed to get a password (for
1688 * example because one was supplied on the command
1689 * line which has already failed to work).
1690 * Terminate.
1691 */
1692 logevent("No more passwords to try");
1693 ssh_state = SSH_STATE_CLOSED;
1694 crReturn(1);
1695 }
fb09bf1c 1696 } else {
1408a877 1697 c_write_str(prompt);
7cca0d81 1698 pos = 0;
67779be7 1699 ssh_send_ok = 1;
7cca0d81 1700 while (pos >= 0) {
1701 crWaitUntil(!ispkt);
1702 while (inlen--) switch (c = *in++) {
1703 case 10: case 13:
1704 password[pos] = 0;
1705 pos = -1;
1706 break;
1707 case 8: case 127:
1708 if (pos > 0)
1709 pos--;
1710 break;
1711 case 21: case 27:
1712 pos = 0;
1713 break;
1714 case 3: case 4:
1715 random_save_seed();
1716 exit(0);
1717 break;
1718 default:
1719 if (((c >= ' ' && c <= '~') ||
1720 ((unsigned char)c >= 160)) && pos < sizeof(password))
1721 password[pos++] = c;
1722 break;
1723 }
1724 }
1408a877 1725 c_write_str("\r\n");
a52f067e 1726 }
fb09bf1c 1727
7cca0d81 1728 tryauth:
1729 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1730 /*
1731 * Try public key authentication with the specified
1732 * key file.
1733 */
1734 static struct RSAKey pubkey;
1735 static Bignum challenge, response;
1736 static int i;
1737 static unsigned char buffer[32];
1738
1739 tried_publickey = 1;
65a22376 1740 i = loadrsakey(cfg.keyfile, &pubkey, password);
7cca0d81 1741 if (i == 0) {
1408a877 1742 c_write_str("Couldn't load public key from ");
1743 c_write_str(cfg.keyfile);
1744 c_write_str(".\r\n");
7cca0d81 1745 continue; /* go and try password */
1746 }
1747 if (i == -1) {
1408a877 1748 c_write_str("Wrong passphrase.\r\n");
7cca0d81 1749 tried_publickey = 0;
1750 continue; /* try again */
1751 }
1752
1753 /*
1754 * Send a public key attempt.
1755 */
1756 send_packet(SSH1_CMSG_AUTH_RSA,
1757 PKT_BIGNUM, pubkey.modulus, PKT_END);
1758
1759 crWaitUntil(ispkt);
1760 if (pktin.type == SSH1_SMSG_FAILURE) {
1408a877 1761 c_write_str("Server refused our public key.\r\n");
7cca0d81 1762 continue; /* go and try password */
1763 }
8d5de777 1764 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1765 bombout(("Bizarre response to offer of public key"));
1766 crReturn(0);
1767 }
7cca0d81 1768 ssh1_read_bignum(pktin.body, &challenge);
1769 response = rsadecrypt(challenge, &pubkey);
1770 freebn(pubkey.private_exponent); /* burn the evidence */
1771
3709bfe9 1772 for (i = 0; i < 32; i++) {
1773 buffer[i] = bignum_byte(response, 31-i);
7cca0d81 1774 }
1775
1776 MD5Init(&md5c);
1777 MD5Update(&md5c, buffer, 32);
1778 MD5Update(&md5c, session_id, 16);
1779 MD5Final(buffer, &md5c);
1780
1781 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1782 PKT_DATA, buffer, 16, PKT_END);
1783
1784 crWaitUntil(ispkt);
1785 if (pktin.type == SSH1_SMSG_FAILURE) {
4017be6d 1786 if (flags & FLAG_VERBOSE)
1408a877 1787 c_write_str("Failed to authenticate with our public key.\r\n");
7cca0d81 1788 continue; /* go and try password */
1789 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
8d5de777 1790 bombout(("Bizarre response to RSA authentication response"));
1791 crReturn(0);
7cca0d81 1792 }
1793
1794 break; /* we're through! */
1795 } else {
1796 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1797 }
c5e9c988 1798 logevent("Sent password");
374330e2 1799 memset(password, 0, strlen(password));
fb09bf1c 1800 crWaitUntil(ispkt);
e5574168 1801 if (pktin.type == SSH1_SMSG_FAILURE) {
4017be6d 1802 if (flags & FLAG_VERBOSE)
1408a877 1803 c_write_str("Access denied\r\n");
c5e9c988 1804 logevent("Authentication refused");
e5574168 1805 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
fb09bf1c 1806 logevent("Received disconnect request");
85ee8208 1807 ssh_state = SSH_STATE_CLOSED;
1808 crReturn(1);
e5574168 1809 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
8d5de777 1810 bombout(("Strange packet received, type %d", pktin.type));
1811 crReturn(0);
374330e2 1812 }
1813 }
1814
c5e9c988 1815 logevent("Authentication successful");
1816
fb09bf1c 1817 crFinish(1);
1818}
1819
9c964e85 1820void sshfwd_close(struct ssh_channel *c) {
783415f8 1821 if (c) {
1822 if (ssh_version == 1) {
1823 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END);
1824 } else {
1825 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
1826 ssh2_pkt_adduint32(c->remoteid);
1827 ssh2_pkt_send();
1828 }
1829 c->closes = 1;
1830 if (c->type == CHAN_X11) {
1831 c->u.x11.s = NULL;
1832 logevent("X11 connection terminated");
1833 }
1834 }
9c964e85 1835}
1836
1837void sshfwd_write(struct ssh_channel *c, char *buf, int len) {
783415f8 1838 if (ssh_version == 1) {
1839 send_packet(SSH1_MSG_CHANNEL_DATA,
1840 PKT_INT, c->remoteid,
1841 PKT_INT, len,
1842 PKT_DATA, buf, len,
1843 PKT_END);
1844 } else {
1845 ssh2_add_channel_data(c, buf, len);
1846 ssh2_try_send(c);
1847 }
9c964e85 1848}
1849
e5574168 1850static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
fb09bf1c 1851 crBegin;
1852
1853 random_init();
1854
e5574168 1855 while (!do_ssh1_login(in, inlen, ispkt)) {
fb09bf1c 1856 crReturnV;
85ee8208 1857 }
1858 if (ssh_state == SSH_STATE_CLOSED)
1859 crReturnV;
fb09bf1c 1860
979310f1 1861 if (cfg.agentfwd && agent_exists()) {
dacbd0e8 1862 logevent("Requesting agent forwarding");
1863 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1864 do { crReturnV; } while (!ispkt);
1865 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
8d5de777 1866 bombout(("Protocol confusion"));
1867 crReturnV;
dacbd0e8 1868 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1869 logevent("Agent forwarding refused");
db7d555c 1870 } else {
dacbd0e8 1871 logevent("Agent forwarding enabled");
db7d555c 1872 ssh_agentfwd_enabled = TRUE;
1873 }
dacbd0e8 1874 }
1875
9c964e85 1876 if (cfg.x11_forward) {
1877 char proto[20], data[64];
1878 logevent("Requesting X11 forwarding");
1879 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
1880 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
1881 PKT_STR, proto, PKT_STR, data,
1882 PKT_INT, 0,
1883 PKT_END);
1884 do { crReturnV; } while (!ispkt);
1885 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1886 bombout(("Protocol confusion"));
1887 crReturnV;
1888 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1889 logevent("X11 forwarding refused");
1890 } else {
1891 logevent("X11 forwarding enabled");
1892 ssh_X11_fwd_enabled = TRUE;
1893 }
1894 }
1895
fef97f43 1896 if (!cfg.nopty) {
e5574168 1897 send_packet(SSH1_CMSG_REQUEST_PTY,
fb09bf1c 1898 PKT_STR, cfg.termtype,
1899 PKT_INT, rows, PKT_INT, cols,
1900 PKT_INT, 0, PKT_INT, 0,
1901 PKT_CHAR, 0,
1902 PKT_END);
fef97f43 1903 ssh_state = SSH_STATE_INTERMED;
1904 do { crReturnV; } while (!ispkt);
e5574168 1905 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
8d5de777 1906 bombout(("Protocol confusion"));
1907 crReturnV;
e5574168 1908 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1408a877 1909 c_write_str("Server refused to allocate pty\r\n");
0965bee0 1910 ssh_editing = ssh_echoing = 1;
fef97f43 1911 }
c5e9c988 1912 logevent("Allocated pty");
0965bee0 1913 } else {
1914 ssh_editing = ssh_echoing = 1;
374330e2 1915 }
1916
4ba9b64b 1917 if (cfg.compression) {
1918 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
1919 do { crReturnV; } while (!ispkt);
1920 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1921 bombout(("Protocol confusion"));
1922 crReturnV;
1923 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1408a877 1924 c_write_str("Server refused to compress\r\n");
4ba9b64b 1925 }
1926 logevent("Started compression");
1927 ssh1_compressing = TRUE;
1928 zlib_compress_init();
1929 zlib_decompress_init();
1930 }
1931
6abbf9e3 1932 if (*cfg.remote_cmd)
1933 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1934 else
1935 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
c5e9c988 1936 logevent("Started session");
374330e2 1937
1938 ssh_state = SSH_STATE_SESSION;
1939 if (size_needed)
1940 ssh_size();
3687d221 1941 if (eof_needed)
1942 ssh_special(TS_EOF);
374330e2 1943
0965bee0 1944 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
8ccc75b0 1945 ssh_send_ok = 1;
dacbd0e8 1946 ssh_channels = newtree234(ssh_channelcmp);
374330e2 1947 while (1) {
1948 crReturnV;
1949 if (ispkt) {
e5574168 1950 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1951 pktin.type == SSH1_SMSG_STDERR_DATA) {
fb09bf1c 1952 long len = GET_32BIT(pktin.body);
fe50e814 1953 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
1954 pktin.body+4, len);
e5574168 1955 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
21248260 1956 ssh_state = SSH_STATE_CLOSED;
c5e9c988 1957 logevent("Received disconnect request");
3257deae 1958 crReturnV;
9c964e85 1959 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
1960 /* Remote side is trying to open a channel to talk to our
1961 * X-Server. Give them back a local channel number. */
1962 unsigned i;
1963 struct ssh_channel *c, *d;
1964 enum234 e;
1965
1966 logevent("Received X11 connect request");
1967 /* Refuse if X11 forwarding is disabled. */
1968 if (!ssh_X11_fwd_enabled) {
1969 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1970 PKT_INT, GET_32BIT(pktin.body),
1971 PKT_END);
1972 logevent("Rejected X11 connect request");
1973 } else {
9c964e85 1974 c = smalloc(sizeof(struct ssh_channel));
1975
0c6c9a70 1976 if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
9c964e85 1977 logevent("opening X11 forward connection failed");
1978 sfree(c);
1979 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1980 PKT_INT, GET_32BIT(pktin.body),
1981 PKT_END);
1982 } else {
1983 logevent("opening X11 forward connection succeeded");
1984 for (i=1, d = first234(ssh_channels, &e); d; d = next234(&e)) {
783415f8 1985 if (d->localid > i)
1986 break; /* found a free number */
1987 i = d->localid + 1;
9c964e85 1988 }
1989 c->remoteid = GET_32BIT(pktin.body);
1990 c->localid = i;
1991 c->closes = 0;
783415f8 1992 c->type = CHAN_X11; /* identify channel type */
9c964e85 1993 add234(ssh_channels, c);
1994 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1995 PKT_INT, c->remoteid, PKT_INT, c->localid,
1996 PKT_END);
1997 logevent("Opened X11 forward channel");
1998 }
1999 }
dacbd0e8 2000 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
2001 /* Remote side is trying to open a channel to talk to our
2002 * agent. Give them back a local channel number. */
db7d555c 2003 unsigned i;
dacbd0e8 2004 struct ssh_channel *c;
2005 enum234 e;
db7d555c 2006
2007 /* Refuse if agent forwarding is disabled. */
2008 if (!ssh_agentfwd_enabled) {
2009 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2010 PKT_INT, GET_32BIT(pktin.body),
2011 PKT_END);
2012 } else {
2013 i = 1;
2014 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
2015 if (c->localid > i)
2016 break; /* found a free number */
2017 i = c->localid + 1;
2018 }
dcbde236 2019 c = smalloc(sizeof(struct ssh_channel));
db7d555c 2020 c->remoteid = GET_32BIT(pktin.body);
2021 c->localid = i;
2022 c->closes = 0;
783415f8 2023 c->type = CHAN_AGENT; /* identify channel type */
db7d555c 2024 c->u.a.lensofar = 0;
2025 add234(ssh_channels, c);
2026 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2027 PKT_INT, c->remoteid, PKT_INT, c->localid,
2028 PKT_END);
2029 }
2030 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2031 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
dacbd0e8 2032 /* Remote side closes a channel. */
d211621f 2033 unsigned i = GET_32BIT(pktin.body);
dacbd0e8 2034 struct ssh_channel *c;
2035 c = find234(ssh_channels, &i, ssh_channelfind);
2036 if (c) {
2037 int closetype;
2038 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2039 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
783415f8 2040 if ((c->closes == 0) && (c->type == CHAN_X11)) {
9c964e85 2041 logevent("X11 connection closed");
2042 assert(c->u.x11.s != NULL);
2043 x11_close(c->u.x11.s);
2044 c->u.x11.s = NULL;
2045 }
dacbd0e8 2046 c->closes |= closetype;
2047 if (c->closes == 3) {
2048 del234(ssh_channels, c);
dcbde236 2049 sfree(c);
dacbd0e8 2050 }
2051 }
2052 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2053 /* Data sent down one of our channels. */
2054 int i = GET_32BIT(pktin.body);
2055 int len = GET_32BIT(pktin.body+4);
2056 unsigned char *p = pktin.body+8;
2057 struct ssh_channel *c;
2058 c = find234(ssh_channels, &i, ssh_channelfind);
2059 if (c) {
2060 switch(c->type) {
783415f8 2061 case CHAN_X11:
9c964e85 2062 x11_send(c->u.x11.s, p, len);
2063 break;
783415f8 2064 case CHAN_AGENT:
dacbd0e8 2065 /* Data for an agent message. Buffer it. */
2066 while (len > 0) {
2067 if (c->u.a.lensofar < 4) {
2068 int l = min(4 - c->u.a.lensofar, len);
2069 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
2070 p += l; len -= l; c->u.a.lensofar += l;
2071 }
2072 if (c->u.a.lensofar == 4) {
2073 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
dcbde236 2074 c->u.a.message = smalloc(c->u.a.totallen);
dacbd0e8 2075 memcpy(c->u.a.message, c->u.a.msglen, 4);
2076 }
2077 if (c->u.a.lensofar >= 4 && len > 0) {
2078 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
2079 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
2080 p += l; len -= l; c->u.a.lensofar += l;
2081 }
2082 if (c->u.a.lensofar == c->u.a.totallen) {
2083 void *reply, *sentreply;
2084 int replylen;
2085 agent_query(c->u.a.message, c->u.a.totallen,
2086 &reply, &replylen);
2087 if (reply)
2088 sentreply = reply;
2089 else {
2090 /* Fake SSH_AGENT_FAILURE. */
2091 sentreply = "\0\0\0\1\5";
2092 replylen = 5;
2093 }
2094 send_packet(SSH1_MSG_CHANNEL_DATA,
2095 PKT_INT, c->remoteid,
2096 PKT_INT, replylen,
2097 PKT_DATA, sentreply, replylen,
2098 PKT_END);
2099 if (reply)
dcbde236 2100 sfree(reply);
2101 sfree(c->u.a.message);
dacbd0e8 2102 c->u.a.lensofar = 0;
2103 }
2104 }
2105 break;
2106 }
2107 }
e5574168 2108 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
972a41c8 2109 /* may be from EXEC_SHELL on some servers */
e5574168 2110 } else if (pktin.type == SSH1_SMSG_FAILURE) {
972a41c8 2111 /* may be from EXEC_SHELL on some servers
374330e2 2112 * if no pty is available or in other odd cases. Ignore */
e5574168 2113 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2114 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
374330e2 2115 } else {
8d5de777 2116 bombout(("Strange packet received: type %d", pktin.type));
2117 crReturnV;
374330e2 2118 }
2119 } else {
8df7a775 2120 while (inlen > 0) {
2121 int len = min(inlen, 512);
2122 send_packet(SSH1_CMSG_STDIN_DATA,
2123 PKT_INT, len, PKT_DATA, in, len, PKT_END);
2124 in += len;
2125 inlen -= len;
2126 }
374330e2 2127 }
2128 }
2129
2130 crFinishV;
2131}
2132
2133/*
e5574168 2134 * Utility routine for decoding comma-separated strings in KEXINIT.
2135 */
75cab814 2136static int in_commasep_string(char *needle, char *haystack, int haylen) {
e5574168 2137 int needlen = strlen(needle);
2138 while (1) {
2139 /*
2140 * Is it at the start of the string?
2141 */
2142 if (haylen >= needlen && /* haystack is long enough */
2143 !memcmp(needle, haystack, needlen) && /* initial match */
2144 (haylen == needlen || haystack[needlen] == ',')
2145 /* either , or EOS follows */
2146 )
2147 return 1;
2148 /*
2149 * If not, search for the next comma and resume after that.
2150 * If no comma found, terminate.
2151 */
2152 while (haylen > 0 && *haystack != ',')
2153 haylen--, haystack++;
2154 if (haylen == 0)
2155 return 0;
2156 haylen--, haystack++; /* skip over comma itself */
2157 }
2158}
2159
2160/*
d39f364a 2161 * SSH2 key creation method.
2162 */
5e0d7cb8 2163static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr, char *keyspace) {
d39f364a 2164 SHA_State s;
2165 /* First 20 bytes. */
2166 SHA_Init(&s);
2167 sha_mpint(&s, K);
2168 SHA_Bytes(&s, H, 20);
2169 SHA_Bytes(&s, &chr, 1);
5e0d7cb8 2170 SHA_Bytes(&s, sessid, 20);
d39f364a 2171 SHA_Final(&s, keyspace);
2172 /* Next 20 bytes. */
2173 SHA_Init(&s);
2174 sha_mpint(&s, K);
2175 SHA_Bytes(&s, H, 20);
2176 SHA_Bytes(&s, keyspace, 20);
2177 SHA_Final(&s, keyspace+20);
2178}
2179
2180/*
7cca0d81 2181 * Handle the SSH2 transport layer.
e5574168 2182 */
7cca0d81 2183static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
e5574168 2184{
0a3f1d48 2185 static int i, j, len, nbits;
e5574168 2186 static char *str;
a92dd380 2187 static Bignum p, g, e, f, K;
2188 static int kex_init_value, kex_reply_value;
7591b9ff 2189 static const struct ssh_mac **maclist;
8b2715b2 2190 static int nmacs;
0a3f1d48 2191 static const struct ssh2_cipher *cscipher_tobe = NULL;
2192 static const struct ssh2_cipher *sccipher_tobe = NULL;
57476f6b 2193 static const struct ssh_mac *csmac_tobe = NULL;
2194 static const struct ssh_mac *scmac_tobe = NULL;
2195 static const struct ssh_compress *cscomp_tobe = NULL;
2196 static const struct ssh_compress *sccomp_tobe = NULL;
d5859615 2197 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
e5574168 2198 static int hostkeylen, siglen;
e055a386 2199 static void *hkey; /* actual host key */
e5574168 2200 static unsigned char exchange_hash[20];
d39f364a 2201 static unsigned char keyspace[40];
0a3f1d48 2202 static const struct ssh2_ciphers *preferred_cipher;
4ba9b64b 2203 static const struct ssh_compress *preferred_comp;
0db56f73 2204 static int first_kex;
e5574168 2205
2206 crBegin;
7cca0d81 2207 random_init();
0db56f73 2208 first_kex = 1;
e5574168 2209
5e8358ad 2210 /*
4ba9b64b 2211 * Set up the preferred cipher and compression.
5e8358ad 2212 */
2213 if (cfg.cipher == CIPHER_BLOWFISH) {
0a3f1d48 2214 preferred_cipher = &ssh2_blowfish;
5e8358ad 2215 } else if (cfg.cipher == CIPHER_DES) {
2216 logevent("Single DES not supported in SSH2; using 3DES");
0a3f1d48 2217 preferred_cipher = &ssh2_3des;
5e8358ad 2218 } else if (cfg.cipher == CIPHER_3DES) {
0a3f1d48 2219 preferred_cipher = &ssh2_3des;
2220 } else if (cfg.cipher == CIPHER_AES) {
2221 preferred_cipher = &ssh2_aes;
5e8358ad 2222 } else {
2223 /* Shouldn't happen, but we do want to initialise to _something_. */
0a3f1d48 2224 preferred_cipher = &ssh2_3des;
5e8358ad 2225 }
4ba9b64b 2226 if (cfg.compression)
2227 preferred_comp = &ssh_zlib;
2228 else
2229 preferred_comp = &ssh_comp_none;
5e8358ad 2230
7591b9ff 2231 /*
2232 * Be prepared to work around the buggy MAC problem.
2233 */
2234 if (cfg.buggymac)
8b2715b2 2235 maclist = buggymacs, nmacs = lenof(buggymacs);
7591b9ff 2236 else
8b2715b2 2237 maclist = macs, nmacs = lenof(macs);
7591b9ff 2238
7cca0d81 2239 begin_key_exchange:
e5574168 2240 /*
2241 * Construct and send our key exchange packet.
2242 */
2243 ssh2_pkt_init(SSH2_MSG_KEXINIT);
2244 for (i = 0; i < 16; i++)
2245 ssh2_pkt_addbyte((unsigned char)random_byte());
2246 /* List key exchange algorithms. */
2247 ssh2_pkt_addstring_start();
2248 for (i = 0; i < lenof(kex_algs); i++) {
2249 ssh2_pkt_addstring_str(kex_algs[i]->name);
2250 if (i < lenof(kex_algs)-1)
2251 ssh2_pkt_addstring_str(",");
2252 }
2253 /* List server host key algorithms. */
2254 ssh2_pkt_addstring_start();
2255 for (i = 0; i < lenof(hostkey_algs); i++) {
2256 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
2257 if (i < lenof(hostkey_algs)-1)
2258 ssh2_pkt_addstring_str(",");
2259 }
2260 /* List client->server encryption algorithms. */
2261 ssh2_pkt_addstring_start();
729e54b4 2262 for (i = 0; i < lenof(ciphers)+1; i++) {
0a3f1d48 2263 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2264 for (j = 0; j < c->nciphers; j++) {
2265 ssh2_pkt_addstring_str(c->list[j]->name);
2266 if (i < lenof(ciphers) || j < c->nciphers-1)
2267 ssh2_pkt_addstring_str(",");
2268 }
e5574168 2269 }
2270 /* List server->client encryption algorithms. */
2271 ssh2_pkt_addstring_start();
729e54b4 2272 for (i = 0; i < lenof(ciphers)+1; i++) {
0a3f1d48 2273 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2274 for (j = 0; j < c->nciphers; j++) {
2275 ssh2_pkt_addstring_str(c->list[j]->name);
2276 if (i < lenof(ciphers) || j < c->nciphers-1)
2277 ssh2_pkt_addstring_str(",");
2278 }
e5574168 2279 }
2280 /* List client->server MAC algorithms. */
2281 ssh2_pkt_addstring_start();
8b2715b2 2282 for (i = 0; i < nmacs; i++) {
7591b9ff 2283 ssh2_pkt_addstring_str(maclist[i]->name);
8b2715b2 2284 if (i < nmacs-1)
e5574168 2285 ssh2_pkt_addstring_str(",");
2286 }
2287 /* List server->client MAC algorithms. */
2288 ssh2_pkt_addstring_start();
8b2715b2 2289 for (i = 0; i < nmacs; i++) {
7591b9ff 2290 ssh2_pkt_addstring_str(maclist[i]->name);
8b2715b2 2291 if (i < nmacs-1)
e5574168 2292 ssh2_pkt_addstring_str(",");
2293 }
2294 /* List client->server compression algorithms. */
2295 ssh2_pkt_addstring_start();
4ba9b64b 2296 for (i = 0; i < lenof(compressions)+1; i++) {
2297 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2298 ssh2_pkt_addstring_str(c->name);
2299 if (i < lenof(compressions))
e5574168 2300 ssh2_pkt_addstring_str(",");
2301 }
2302 /* List server->client compression algorithms. */
2303 ssh2_pkt_addstring_start();
4ba9b64b 2304 for (i = 0; i < lenof(compressions)+1; i++) {
2305 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2306 ssh2_pkt_addstring_str(c->name);
2307 if (i < lenof(compressions))
e5574168 2308 ssh2_pkt_addstring_str(",");
2309 }
2310 /* List client->server languages. Empty list. */
2311 ssh2_pkt_addstring_start();
2312 /* List server->client languages. Empty list. */
2313 ssh2_pkt_addstring_start();
2314 /* First KEX packet does _not_ follow, because we're not that brave. */
2315 ssh2_pkt_addbool(FALSE);
2316 /* Reserved. */
2317 ssh2_pkt_adduint32(0);
0db56f73 2318
2319 exhash = exhashbase;
e5574168 2320 sha_string(&exhash, pktout.data+5, pktout.length-5);
0db56f73 2321
e5574168 2322 ssh2_pkt_send();
2323
2324 if (!ispkt) crWaitUntil(ispkt);
2325 sha_string(&exhash, pktin.data+5, pktin.length-5);
2326
2327 /*
2328 * Now examine the other side's KEXINIT to see what we're up
2329 * to.
2330 */
7cca0d81 2331 if (pktin.type != SSH2_MSG_KEXINIT) {
8d5de777 2332 bombout(("expected key exchange packet from server"));
2333 crReturn(0);
7cca0d81 2334 }
e5574168 2335 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
2336 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
2337 pktin.savedpos += 16; /* skip garbage cookie */
2338 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
2339 for (i = 0; i < lenof(kex_algs); i++) {
2340 if (in_commasep_string(kex_algs[i]->name, str, len)) {
2341 kex = kex_algs[i];
2342 break;
2343 }
2344 }
2345 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
2346 for (i = 0; i < lenof(hostkey_algs); i++) {
2347 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
2348 hostkey = hostkey_algs[i];
2349 break;
2350 }
2351 }
2352 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
729e54b4 2353 for (i = 0; i < lenof(ciphers)+1; i++) {
0a3f1d48 2354 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2355 for (j = 0; j < c->nciphers; j++) {
2356 if (in_commasep_string(c->list[j]->name, str, len)) {
2357 cscipher_tobe = c->list[j];
2358 break;
2359 }
e5574168 2360 }
0a3f1d48 2361 if (cscipher_tobe)
2362 break;
e5574168 2363 }
2364 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
729e54b4 2365 for (i = 0; i < lenof(ciphers)+1; i++) {
0a3f1d48 2366 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2367 for (j = 0; j < c->nciphers; j++) {
2368 if (in_commasep_string(c->list[j]->name, str, len)) {
2369 sccipher_tobe = c->list[j];
2370 break;
2371 }
e5574168 2372 }
0a3f1d48 2373 if (sccipher_tobe)
2374 break;
e5574168 2375 }
2376 ssh2_pkt_getstring(&str, &len); /* client->server mac */
8b2715b2 2377 for (i = 0; i < nmacs; i++) {
7591b9ff 2378 if (in_commasep_string(maclist[i]->name, str, len)) {
2379 csmac_tobe = maclist[i];
e5574168 2380 break;
2381 }
2382 }
2383 ssh2_pkt_getstring(&str, &len); /* server->client mac */
8b2715b2 2384 for (i = 0; i < nmacs; i++) {
7591b9ff 2385 if (in_commasep_string(maclist[i]->name, str, len)) {
2386 scmac_tobe = maclist[i];
e5574168 2387 break;
2388 }
2389 }
2390 ssh2_pkt_getstring(&str, &len); /* client->server compression */
4ba9b64b 2391 for (i = 0; i < lenof(compressions)+1; i++) {
2392 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2393 if (in_commasep_string(c->name, str, len)) {
2394 cscomp_tobe = c;
e5574168 2395 break;
2396 }
2397 }
2398 ssh2_pkt_getstring(&str, &len); /* server->client compression */
4ba9b64b 2399 for (i = 0; i < lenof(compressions)+1; i++) {
2400 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2401 if (in_commasep_string(c->name, str, len)) {
2402 sccomp_tobe = c;
e5574168 2403 break;
2404 }
2405 }
e5574168 2406
2407 /*
a92dd380 2408 * If we're doing Diffie-Hellman group exchange, start by
2409 * requesting a group.
e5574168 2410 */
a92dd380 2411 if (kex == &ssh_diffiehellman_gex) {
2412 int csbits, scbits;
2413
2414 logevent("Doing Diffie-Hellman group exchange");
2415 /*
2416 * Work out number of bits. We start with the maximum key
2417 * length of either cipher...
2418 */
2419 csbits = cscipher_tobe->keylen;
2420 scbits = sccipher_tobe->keylen;
2421 nbits = (csbits > scbits ? csbits : scbits);
2422 /* The keys only have 160-bit entropy, since they're based on
2423 * a SHA-1 hash. So cap the key size at 160 bits. */
2424 if (nbits > 160) nbits = 160;
2425 /*
2426 * ... and then work out how big a DH group we will need to
2427 * allow that much data.
2428 */
2429 nbits = 512 << ((nbits-1) / 64);
2430 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
2431 ssh2_pkt_adduint32(nbits);
2432 ssh2_pkt_send();
2433
2434 crWaitUntil(ispkt);
2435 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
2436 bombout(("expected key exchange group packet from server"));
2437 crReturn(0);
2438 }
2439 p = ssh2_pkt_getmp();
2440 g = ssh2_pkt_getmp();
2441 dh_setup_group(p, g);
2442 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
2443 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
2444 } else {
2445 dh_setup_group1();
2446 kex_init_value = SSH2_MSG_KEXDH_INIT;
2447 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
8d5de777 2448 }
e5574168 2449
a92dd380 2450 logevent("Doing Diffie-Hellman key exchange");
e5574168 2451 /*
a92dd380 2452 * Now generate and send e for Diffie-Hellman.
e5574168 2453 */
2454 e = dh_create_e();
a92dd380 2455 ssh2_pkt_init(kex_init_value);
e5574168 2456 ssh2_pkt_addmp(e);
2457 ssh2_pkt_send();
2458
2459 crWaitUntil(ispkt);
a92dd380 2460 if (pktin.type != kex_reply_value) {
2461 bombout(("expected key exchange reply packet from server"));
8d5de777 2462 crReturn(0);
7cca0d81 2463 }
e5574168 2464 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2465 f = ssh2_pkt_getmp();
e5574168 2466 ssh2_pkt_getstring(&sigdata, &siglen);
2467
2468 K = dh_find_K(f);
e5574168 2469
2470 sha_string(&exhash, hostkeydata, hostkeylen);
a92dd380 2471 if (kex == &ssh_diffiehellman_gex) {
2472 sha_uint32(&exhash, nbits);
2473 sha_mpint(&exhash, p);
2474 sha_mpint(&exhash, g);
2475 }
e5574168 2476 sha_mpint(&exhash, e);
2477 sha_mpint(&exhash, f);
2478 sha_mpint(&exhash, K);
2479 SHA_Final(&exhash, exchange_hash);
2480
3709bfe9 2481 dh_cleanup();
2482
7cca0d81 2483#if 0
e5574168 2484 debug(("Exchange hash is:\r\n"));
2485 for (i = 0; i < 20; i++)
2486 debug((" %02x", exchange_hash[i]));
2487 debug(("\r\n"));
7cca0d81 2488#endif
2489
e055a386 2490 hkey = hostkey->newkey(hostkeydata, hostkeylen);
2491 if (!hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
8d5de777 2492 bombout(("Server failed host key check"));
2493 crReturn(0);
2494 }
e5574168 2495
2496 /*
7cca0d81 2497 * Expect SSH2_MSG_NEWKEYS from server.
d39f364a 2498 */
7cca0d81 2499 crWaitUntil(ispkt);
8d5de777 2500 if (pktin.type != SSH2_MSG_NEWKEYS) {
2501 bombout(("expected new-keys packet from server"));
2502 crReturn(0);
2503 }
d39f364a 2504
2505 /*
7cca0d81 2506 * Authenticate remote host: verify host key. (We've already
2507 * checked the signature of the exchange hash.)
e5574168 2508 */
e055a386 2509 keystr = hostkey->fmtkey(hkey);
2510 fingerprint = hostkey->fingerprint(hkey);
d4857987 2511 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
2512 keystr, fingerprint);
a92dd380 2513 if (first_kex) { /* don't bother logging this in rekeys */
5e0d7cb8 2514 logevent("Host key fingerprint is:");
2515 logevent(fingerprint);
2516 }
dcbde236 2517 sfree(fingerprint);
2518 sfree(keystr);
e055a386 2519 hostkey->freekey(hkey);
d39f364a 2520
2521 /*
7cca0d81 2522 * Send SSH2_MSG_NEWKEYS.
d39f364a 2523 */
2524 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2525 ssh2_pkt_send();
d39f364a 2526
2527 /*
2528 * Create and initialise session keys.
2529 */
2530 cscipher = cscipher_tobe;
2531 sccipher = sccipher_tobe;
2532 csmac = csmac_tobe;
2533 scmac = scmac_tobe;
2534 cscomp = cscomp_tobe;
2535 sccomp = sccomp_tobe;
4ba9b64b 2536 cscomp->compress_init();
2537 sccomp->decompress_init();
d39f364a 2538 /*
5e0d7cb8 2539 * Set IVs after keys. Here we use the exchange hash from the
2540 * _first_ key exchange.
d39f364a 2541 */
5e0d7cb8 2542 if (first_kex)
65a22376 2543 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
2544 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
5e0d7cb8 2545 cscipher->setcskey(keyspace);
65a22376 2546 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
5e0d7cb8 2547 sccipher->setsckey(keyspace);
65a22376 2548 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
5e0d7cb8 2549 cscipher->setcsiv(keyspace);
65a22376 2550 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
5e0d7cb8 2551 sccipher->setsciv(keyspace);
65a22376 2552 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
5e0d7cb8 2553 csmac->setcskey(keyspace);
65a22376 2554 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
5e0d7cb8 2555 scmac->setsckey(keyspace);
d39f364a 2556
033b4cef 2557 /*
0db56f73 2558 * If this is the first key exchange phase, we must pass the
2559 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2560 * wants to see it but because it will need time to initialise
2561 * itself before it sees an actual packet. In subsequent key
2562 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2563 * it would only confuse the layer above.
2564 */
2565 if (!first_kex) {
2566 crReturn(0);
2567 }
2568 first_kex = 0;
2569
2570 /*
7cca0d81 2571 * Now we're encrypting. Begin returning 1 to the protocol main
2572 * function so that other things can run on top of the
2573 * transport. If we ever see a KEXINIT, we must go back to the
2574 * start.
033b4cef 2575 */
e96adf72 2576 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
7cca0d81 2577 crReturn(1);
e96adf72 2578 }
5e0d7cb8 2579 logevent("Server initiated key re-exchange");
7cca0d81 2580 goto begin_key_exchange;
e5574168 2581
2582 crFinish(1);
2583}
2584
7cca0d81 2585/*
783415f8 2586 * Add data to an SSH2 channel output buffer.
2587 */
2588static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len) {
2589 if (c->v2.outbufsize <
2590 c->v2.outbuflen + len) {
2591 c->v2.outbufsize =
2592 c->v2.outbuflen + len + 1024;
2593 c->v2.outbuffer = srealloc(c->v2.outbuffer,
2594 c->v2.outbufsize);
2595 }
2596 memcpy(c->v2.outbuffer + c->v2.outbuflen,
2597 buf, len);
2598 c->v2.outbuflen += len;
2599}
2600
2601/*
2602 * Attempt to send data on an SSH2 channel.
2603 */
2604static void ssh2_try_send(struct ssh_channel *c) {
2605 while (c->v2.remwindow > 0 &&
2606 c->v2.outbuflen > 0) {
2607 unsigned len = c->v2.remwindow;
2608 if (len > c->v2.outbuflen)
2609 len = c->v2.outbuflen;
2610 if (len > c->v2.remmaxpkt)
2611 len = c->v2.remmaxpkt;
2612 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2613 ssh2_pkt_adduint32(c->remoteid);
2614 ssh2_pkt_addstring_start();
2615 ssh2_pkt_addstring_data(c->v2.outbuffer, len);
2616 ssh2_pkt_send();
2617 c->v2.outbuflen -= len;
2618 memmove(c->v2.outbuffer, c->v2.outbuffer+len,
2619 c->v2.outbuflen);
2620 c->v2.remwindow -= len;
2621 }
2622}
2623
2624/*
7cca0d81 2625 * Handle the SSH2 userauth and connection layers.
2626 */
2627static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2628{
7cca0d81 2629 static unsigned long remote_winsize;
2630 static unsigned long remote_maxpkt;
65a22376 2631 static enum {
2632 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE, AUTH_PASSWORD
2633 } method;
1408a877 2634 static enum {
2635 AUTH_TYPE_NONE,
2636 AUTH_TYPE_PUBLICKEY,
2637 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
2638 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
2639 AUTH_TYPE_PASSWORD
2640 } type;
65a22376 2641 static int gotit, need_pw, can_pubkey, can_passwd, tried_pubkey_config;
1408a877 2642 static int we_are_in;
65a22376 2643 static char username[100];
2644 static char pwprompt[200];
2645 static char password[100];
7cca0d81 2646
e5574168 2647 crBegin;
2648
7cca0d81 2649 /*
2650 * Request userauth protocol, and await a response to it.
2651 */
2652 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2653 ssh2_pkt_addstring("ssh-userauth");
2654 ssh2_pkt_send();
2655 crWaitUntilV(ispkt);
8d5de777 2656 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2657 bombout(("Server refused user authentication protocol"));
2658 crReturnV;
2659 }
7cca0d81 2660
2661 /*
1408a877 2662 * We repeat this whole loop, including the username prompt,
2663 * until we manage a successful authentication. If the user
2664 * types the wrong _password_, they are sent back to the
2665 * beginning to try another username. (If they specify a
2666 * username in the config, they are never asked, even if they
2667 * do give a wrong password.)
2668 *
2669 * I think this best serves the needs of
2670 *
2671 * - the people who have no configuration, no keys, and just
2672 * want to try repeated (username,password) pairs until they
2673 * type both correctly
2674 *
2675 * - people who have keys and configuration but occasionally
2676 * need to fall back to passwords
2677 *
2678 * - people with a key held in Pageant, who might not have
2679 * logged in to a particular machine before; so they want to
2680 * type a username, and then _either_ their key will be
2681 * accepted, _or_ they will type a password. If they mistype
2682 * the username they will want to be able to get back and
2683 * retype it!
7cca0d81 2684 */
1408a877 2685 do {
2686 static int pos;
7cca0d81 2687 static char c;
e5574168 2688
1408a877 2689 /*
2690 * Get a username.
2691 */
2692 pos = 0;
67779be7 2693 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1408a877 2694 c_write_str("login as: ");
65a22376 2695 ssh_send_ok = 1;
7cca0d81 2696 while (pos >= 0) {
2697 crWaitUntilV(!ispkt);
2698 while (inlen--) switch (c = *in++) {
2699 case 10: case 13:
2700 username[pos] = 0;
2701 pos = -1;
2702 break;
2703 case 8: case 127:
2704 if (pos > 0) {
1408a877 2705 c_write_str("\b \b");
7cca0d81 2706 pos--;
2707 }
2708 break;
2709 case 21: case 27:
2710 while (pos > 0) {
1408a877 2711 c_write_str("\b \b");
7cca0d81 2712 pos--;
2713 }
2714 break;
2715 case 3: case 4:
2716 random_save_seed();
2717 exit(0);
2718 break;
2719 default:
2720 if (((c >= ' ' && c <= '~') ||
65a22376 2721 ((unsigned char)c >= 160)) && pos < 40) {
7cca0d81 2722 username[pos++] = c;
2723 c_write(&c, 1);
2724 }
2725 break;
2726 }
2727 }
1408a877 2728 c_write_str("\r\n");
7cca0d81 2729 username[strcspn(username, "\n\r")] = '\0';
2730 } else {
2731 char stuff[200];
2732 strncpy(username, cfg.username, 99);
2733 username[99] = '\0';
65a22376 2734 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7cca0d81 2735 sprintf(stuff, "Using username \"%s\".\r\n", username);
1408a877 2736 c_write_str(stuff);
7cca0d81 2737 }
2738 }
2739
65a22376 2740 /*
1408a877 2741 * Send an authentication request using method "none": (a)
2742 * just in case it succeeds, and (b) so that we know what
2743 * authentication methods we can usefully try next.
65a22376 2744 */
1408a877 2745 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2746 ssh2_pkt_addstring(username);
2747 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2748 ssh2_pkt_addstring("none"); /* method */
2749 ssh2_pkt_send();
2750 type = AUTH_TYPE_NONE;
2751 gotit = FALSE;
2752 we_are_in = FALSE;
7cca0d81 2753
1408a877 2754 tried_pubkey_config = FALSE;
65a22376 2755
1408a877 2756 while (1) {
2757 /*
2758 * Wait for the result of the last authentication request.
2759 */
2760 if (!gotit)
2761 crWaitUntilV(ispkt);
2762 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
2763 /* FIXME: should support this */
2764 crWaitUntilV(ispkt);
2765 }
2766 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
2767 logevent("Access granted");
2768 we_are_in = TRUE;
2769 break;
2770 }
65a22376 2771
1408a877 2772 if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
2773 bombout(("Strange packet received during authentication: type %d",
2774 pktin.type));
65a22376 2775 }
2776
1408a877 2777 gotit = FALSE;
65a22376 2778
1408a877 2779 /*
2780 * OK, we're now sitting on a USERAUTH_FAILURE message, so
2781 * we can look at the string in it and know what we can
2782 * helpfully try next.
2783 */
2784 {
2785 char *methods;
2786 int methlen;
2787 ssh2_pkt_getstring(&methods, &methlen);
2788 if (!ssh2_pkt_getbool()) {
2789 /*
2790 * We have received an unequivocal Access
2791 * Denied. This can translate to a variety of
2792 * messages:
2793 *
2794 * - if we'd just tried "none" authentication,
2795 * it's not worth printing anything at all
2796 *
2797 * - if we'd just tried a public key _offer_,
2798 * the message should be "Server refused our
2799 * key" (or no message at all if the key
2800 * came from Pageant)
2801 *
2802 * - if we'd just tried anything else, the
2803 * message really should be "Access denied".
2804 *
2805 * Additionally, if we'd just tried password
2806 * authentication, we should break out of this
2807 * whole loop so as to go back to the username
2808 * prompt.
2809 */
2810 if (type == AUTH_TYPE_NONE) {
2811 /* do nothing */
2812 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
2813 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
2814 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
2815 c_write_str("Server refused our key\r\n");
2816 logevent("Server refused public key");
2817 } else {
2818 c_write_str("Access denied\r\n");
2819 logevent("Access denied");
2820 if (type == AUTH_TYPE_PASSWORD) {
2821 we_are_in = FALSE;
2822 break;
2823 }
2824 }
2825 } else {
2826 c_write_str("Further authentication required\r\n");
2827 logevent("Further authentication required");
2828 }
65a22376 2829
1408a877 2830 can_pubkey = in_commasep_string("publickey", methods, methlen);
2831 can_passwd = in_commasep_string("password", methods, methlen);
2832 }
65a22376 2833
1408a877 2834 method = 0;
65a22376 2835
1408a877 2836 if (!method && can_pubkey && *cfg.keyfile && !tried_pubkey_config) {
2837 unsigned char *pub_blob;
2838 char *algorithm, *comment;
2839 int pub_blob_len;
65a22376 2840
1408a877 2841 tried_pubkey_config = TRUE;
65a22376 2842
65a22376 2843 /*
1408a877 2844 * Try the public key supplied in the configuration.
2845 *
2846 * First, offer the public blob to see if the server is
2847 * willing to accept it.
65a22376 2848 */
1408a877 2849 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
2850 &pub_blob_len);
2851 if (pub_blob) {
2852 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2853 ssh2_pkt_addstring(username);
2854 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2855 ssh2_pkt_addstring("publickey");/* method */
2856 ssh2_pkt_addbool(FALSE); /* no signature included */
2857 ssh2_pkt_addstring(algorithm);
2858 ssh2_pkt_addstring_start();
2859 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
2860 ssh2_pkt_send();
2861 logevent("Offered public key"); /* FIXME */
2862
2863 crWaitUntilV(ispkt);
2864 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
2865 gotit = TRUE;
2866 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
2867 continue; /* key refused; give up on it */
2868 }
65a22376 2869
1408a877 2870 logevent("Offer of public key accepted");
65a22376 2871 /*
1408a877 2872 * Actually attempt a serious authentication using
2873 * the key.
65a22376 2874 */
1408a877 2875 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
2876 sprintf(pwprompt, "Passphrase for key \"%.100s\": ", comment);
2877 need_pw = TRUE;
2878 } else {
2879 need_pw = FALSE;
2880 }
2881 c_write_str("Authenticating with public key \"");
2882 c_write_str(comment);
2883 c_write_str("\"\r\n");
2884 method = AUTH_PUBLICKEY_FILE;
65a22376 2885 }
1408a877 2886 }
2887
2888 if (!method && can_passwd) {
2889 method = AUTH_PASSWORD;
2890 sprintf(pwprompt, "%.90s@%.90s's password: ", username, savedhost);
2891 need_pw = TRUE;
2892 }
2893
2894 if (need_pw) {
2895 if (ssh_get_password) {
2896 if (!ssh_get_password(pwprompt, password, sizeof(password))) {
2897 /*
2898 * get_password failed to get a password (for
2899 * example because one was supplied on the command
2900 * line which has already failed to work).
2901 * Terminate.
2902 */
2903 logevent("No more passwords to try");
2904 ssh_state = SSH_STATE_CLOSED;
2905 crReturnV;
2906 }
2907 } else {
2908 static int pos = 0;
2909 static char c;
2910
2911 c_write_str(pwprompt);
2912 ssh_send_ok = 1;
2913
2914 pos = 0;
2915 while (pos >= 0) {
2916 crWaitUntilV(!ispkt);
2917 while (inlen--) switch (c = *in++) {
2918 case 10: case 13:
2919 password[pos] = 0;
2920 pos = -1;
2921 break;
2922 case 8: case 127:
2923 if (pos > 0)
2924 pos--;
2925 break;
2926 case 21: case 27:
2927 pos = 0;
2928 break;
2929 case 3: case 4:
2930 random_save_seed();
2931 exit(0);
2932 break;
2933 default:
2934 if (((c >= ' ' && c <= '~') ||
2935 ((unsigned char)c >= 160)) && pos < 40)
2936 password[pos++] = c;
2937 break;
2938 }
65a22376 2939 }
1408a877 2940 c_write_str("\r\n");
65a22376 2941 }
65a22376 2942 }
65a22376 2943
1408a877 2944 if (method == AUTH_PUBLICKEY_FILE) {
2945 /*
2946 * We have our passphrase. Now try the actual authentication.
2947 */
2948 struct ssh2_userkey *key;
65a22376 2949
1408a877 2950 key = ssh2_load_userkey(cfg.keyfile, password);
2951 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
2952 if (key == SSH2_WRONG_PASSPHRASE) {
2953 c_write_str("Wrong passphrase\r\n");
2954 tried_pubkey_config = FALSE;
2955 } else {
2956 c_write_str("Unable to load private key\r\n");
2957 tried_pubkey_config = TRUE;
2958 }
2959 /* Send a spurious AUTH_NONE to return to the top. */
2960 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2961 ssh2_pkt_addstring(username);
2962 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2963 ssh2_pkt_addstring("none"); /* method */
2964 ssh2_pkt_send();
2965 type = AUTH_TYPE_NONE;
2966 } else {
2967 unsigned char *blob, *sigdata;
2968 int blob_len, sigdata_len;
65a22376 2969
1408a877 2970 /*
2971 * We have loaded the private key and the server
2972 * has announced that it's willing to accept it.
2973 * Hallelujah. Generate a signature and send it.
2974 */
2975 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2976 ssh2_pkt_addstring(username);
2977 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2978 ssh2_pkt_addstring("publickey"); /* method */
2979 ssh2_pkt_addbool(TRUE);
2980 ssh2_pkt_addstring(key->alg->name);
2981 blob = key->alg->public_blob(key->data, &blob_len);
2982 ssh2_pkt_addstring_start();
2983 ssh2_pkt_addstring_data(blob, blob_len);
2984 sfree(blob);
2985
2986 /*
2987 * The data to be signed is:
2988 *
2989 * string session-id
2990 *
2991 * followed by everything so far placed in the
2992 * outgoing packet.
2993 */
2994 sigdata_len = pktout.length - 5 + 4 + 20;
2995 sigdata = smalloc(sigdata_len);
2996 PUT_32BIT(sigdata, 20);
2997 memcpy(sigdata+4, ssh2_session_id, 20);
2998 memcpy(sigdata+24, pktout.data+5, pktout.length-5);
2999 blob = key->alg->sign(key->data, sigdata, sigdata_len, &blob_len);
3000 ssh2_pkt_addstring_start();
3001 ssh2_pkt_addstring_data(blob, blob_len);
3002 sfree(blob);
3003 sfree(sigdata);
3004
3005 ssh2_pkt_send();
3006 type = AUTH_TYPE_PUBLICKEY;
3007 }
3008 } else if (method == AUTH_PASSWORD) {
65a22376 3009 /*
1408a877 3010 * We send the password packet lumped tightly together with
3011 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3012 * string long enough to make the total length of the two
3013 * packets constant. This should ensure that a passive
3014 * listener doing traffic analyis can't work out the length
3015 * of the password.
3016 *
3017 * For this to work, we need an assumption about the
3018 * maximum length of the password packet. I think 256 is
3019 * pretty conservative. Anyone using a password longer than
3020 * that probably doesn't have much to worry about from
3021 * people who find out how long their password is!
65a22376 3022 */
3023 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3024 ssh2_pkt_addstring(username);
3025 ssh2_pkt_addstring("ssh-connection"); /* service requested */
1408a877 3026 ssh2_pkt_addstring("password");
3027 ssh2_pkt_addbool(FALSE);
3028 ssh2_pkt_addstring(password);
3029 ssh2_pkt_defer();
65a22376 3030 /*
1408a877 3031 * We'll include a string that's an exact multiple of the
3032 * cipher block size. If the cipher is NULL for some
3033 * reason, we don't do this trick at all because we gain
3034 * nothing by it.
65a22376 3035 */
1408a877 3036 if (cscipher) {
3037 int i, j;
3038 ssh2_pkt_init(SSH2_MSG_IGNORE);
3039 ssh2_pkt_addstring_start();
3040 for (i = deferred_len; i <= 256; i += cscipher->blksize) {
3041 for (j = 0; j < cscipher->blksize; j++) {
3042 char c = (char)random_byte();
3043 ssh2_pkt_addstring_data(&c, 1);
3044 }
65a22376 3045 }
1408a877 3046 ssh2_pkt_defer();
65a22376 3047 }
1408a877 3048 ssh2_pkt_defersend();
3049 type = AUTH_TYPE_PASSWORD;
3050 } else {
3051 c_write_str("No supported authentication methods left to try!\r\n");
3052 logevent("No supported authentications offered. Disconnecting");
3053 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3054 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3055 ssh2_pkt_addstring("No supported authentication methods available");
3056 ssh2_pkt_addstring("en"); /* language tag */
3057 ssh2_pkt_send();
3058 ssh_state = SSH_STATE_CLOSED;
3059 crReturnV;
65a22376 3060 }
65a22376 3061 }
1408a877 3062 } while (!we_are_in);
7cca0d81 3063
3064 /*
3065 * Now we're authenticated for the connection protocol. The
3066 * connection protocol will automatically have started at this
3067 * point; there's no need to send SERVICE_REQUEST.
3068 */
3069
3070 /*
3071 * So now create a channel with a session in it.
3072 */
dcbde236 3073 mainchan = smalloc(sizeof(struct ssh_channel));
d211621f 3074 mainchan->localid = 100; /* as good as any */
7cca0d81 3075 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
3076 ssh2_pkt_addstring("session");
d211621f 3077 ssh2_pkt_adduint32(mainchan->localid);
cf6e59d6 3078 ssh2_pkt_adduint32(0x8000UL); /* our window size */
d211621f 3079 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
7cca0d81 3080 ssh2_pkt_send();
3081 crWaitUntilV(ispkt);
3082 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8d5de777 3083 bombout(("Server refused to open a session"));
3084 crReturnV;
7cca0d81 3085 /* FIXME: error data comes back in FAILURE packet */
3086 }
d211621f 3087 if (ssh2_pkt_getuint32() != mainchan->localid) {
8d5de777 3088 bombout(("Server's channel confirmation cited wrong channel"));
3089 crReturnV;
7cca0d81 3090 }
d211621f 3091 mainchan->remoteid = ssh2_pkt_getuint32();
783415f8 3092 mainchan->type = CHAN_MAINSESSION;
3093 mainchan->closes = 0;
3094 mainchan->v2.remwindow = ssh2_pkt_getuint32();
3095 mainchan->v2.remmaxpkt = ssh2_pkt_getuint32();
3096 mainchan->v2.outbuffer = NULL;
3097 mainchan->v2.outbuflen = mainchan->v2.outbufsize = 0;
3098 ssh_channels = newtree234(ssh_channelcmp);
3099 add234(ssh_channels, mainchan);
7cca0d81 3100 logevent("Opened channel for session");
3101
3102 /*
783415f8 3103 * Potentially enable X11 forwarding.
3104 */
3105 if (cfg.x11_forward) {
3106 char proto[20], data[64];
3107 logevent("Requesting X11 forwarding");
3108 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3109 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3110 ssh2_pkt_adduint32(mainchan->remoteid);
3111 ssh2_pkt_addstring("x11-req");
3112 ssh2_pkt_addbool(1); /* want reply */
3113 ssh2_pkt_addbool(0); /* many connections */
3114 ssh2_pkt_addstring(proto);
3115 ssh2_pkt_addstring(data);
3116 ssh2_pkt_adduint32(0); /* screen number */
3117 ssh2_pkt_send();
3118
3119 do {
3120 crWaitUntilV(ispkt);
3121 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3122 unsigned i = ssh2_pkt_getuint32();
3123 struct ssh_channel *c;
3124 c = find234(ssh_channels, &i, ssh_channelfind);
3125 if (!c)
3126 continue; /* nonexistent channel */
3127 c->v2.remwindow += ssh2_pkt_getuint32();
3128 }
3129 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3130
3131 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3132 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3133 bombout(("Server got confused by X11 forwarding request"));
3134 crReturnV;
3135 }
3136 logevent("X11 forwarding refused");
3137 } else {
3138 logevent("X11 forwarding enabled");
3139 ssh_X11_fwd_enabled = TRUE;
3140 }
3141 }
3142
3143 /*
7cca0d81 3144 * Now allocate a pty for the session.
3145 */
67779be7 3146 if (!cfg.nopty) {
3147 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3148 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
3149 ssh2_pkt_addstring("pty-req");
3150 ssh2_pkt_addbool(1); /* want reply */
3151 ssh2_pkt_addstring(cfg.termtype);
3152 ssh2_pkt_adduint32(cols);
3153 ssh2_pkt_adduint32(rows);
3154 ssh2_pkt_adduint32(0); /* pixel width */
3155 ssh2_pkt_adduint32(0); /* pixel height */
3156 ssh2_pkt_addstring_start();
3157 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3158 ssh2_pkt_send();
6e48c3fe 3159 ssh_state = SSH_STATE_INTERMED;
7cca0d81 3160
67779be7 3161 do {
3162 crWaitUntilV(ispkt);
3163 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
783415f8 3164 unsigned i = ssh2_pkt_getuint32();
3165 struct ssh_channel *c;
3166 c = find234(ssh_channels, &i, ssh_channelfind);
3167 if (!c)
3168 continue; /* nonexistent channel */
3169 c->v2.remwindow += ssh2_pkt_getuint32();
67779be7 3170 }
3171 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7cca0d81 3172
67779be7 3173 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3174 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
8d5de777 3175 bombout(("Server got confused by pty request"));
3176 crReturnV;
67779be7 3177 }
1408a877 3178 c_write_str("Server refused to allocate pty\r\n");
0965bee0 3179 ssh_editing = ssh_echoing = 1;
67779be7 3180 } else {
3181 logevent("Allocated pty");
7cca0d81 3182 }
0965bee0 3183 } else {
3184 ssh_editing = ssh_echoing = 1;
7cca0d81 3185 }
3186
3187 /*
67779be7 3188 * Start a shell or a remote command.
7cca0d81 3189 */
3190 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
d211621f 3191 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
4a8fc3c4 3192 if (cfg.ssh_subsys) {
3193 ssh2_pkt_addstring("subsystem");
3194 ssh2_pkt_addbool(1); /* want reply */
3195 ssh2_pkt_addstring(cfg.remote_cmd);
3196 } else if (*cfg.remote_cmd) {
67779be7 3197 ssh2_pkt_addstring("exec");
3198 ssh2_pkt_addbool(1); /* want reply */
3199 ssh2_pkt_addstring(cfg.remote_cmd);
3200 } else {
3201 ssh2_pkt_addstring("shell");
3202 ssh2_pkt_addbool(1); /* want reply */
3203 }
7cca0d81 3204 ssh2_pkt_send();
d211621f 3205 do {
7cca0d81 3206 crWaitUntilV(ispkt);
d211621f 3207 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
783415f8 3208 unsigned i = ssh2_pkt_getuint32();
3209 struct ssh_channel *c;
3210 c = find234(ssh_channels, &i, ssh_channelfind);
3211 if (!c)
3212 continue; /* nonexistent channel */
3213 c->v2.remwindow += ssh2_pkt_getuint32();
d211621f 3214 }
7cca0d81 3215 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3216 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3217 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
8d5de777 3218 bombout(("Server got confused by shell/command request"));
3219 crReturnV;
7cca0d81 3220 }
8d5de777 3221 bombout(("Server refused to start a shell/command"));
3222 crReturnV;
7cca0d81 3223 } else {
8d5de777 3224 logevent("Started a shell/command");
7cca0d81 3225 }
3226
6e48c3fe 3227 ssh_state = SSH_STATE_SESSION;
3228 if (size_needed)
3229 ssh_size();
3687d221 3230 if (eof_needed)
3231 ssh_special(TS_EOF);
6e48c3fe 3232
7cca0d81 3233 /*
3234 * Transfer data!
3235 */
0965bee0 3236 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
8ccc75b0 3237 ssh_send_ok = 1;
7cca0d81 3238 while (1) {
d211621f 3239 static int try_send;
e5574168 3240 crReturnV;
d211621f 3241 try_send = FALSE;
7cca0d81 3242 if (ispkt) {
3243 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
3244 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
3245 char *data;
3246 int length;
783415f8 3247 unsigned i = ssh2_pkt_getuint32();
3248 struct ssh_channel *c;
3249 c = find234(ssh_channels, &i, ssh_channelfind);
3250 if (!c)
3251 continue; /* nonexistent channel */
7cca0d81 3252 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
3253 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
3254 continue; /* extended but not stderr */
3255 ssh2_pkt_getstring(&data, &length);
d211621f 3256 if (data) {
783415f8 3257 switch (c->type) {
3258 case CHAN_MAINSESSION:
3259 from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
3260 data, length);
3261 break;
3262 case CHAN_X11:
3263 x11_send(c->u.x11.s, data, length);
3264 break;
3265 }
d211621f 3266 /*
783415f8 3267 * Enlarge the window again at the remote
3268 * side, just in case it ever runs down and
3269 * they fail to send us any more data.
d211621f 3270 */
3271 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
783415f8 3272 ssh2_pkt_adduint32(c->remoteid);
d211621f 3273 ssh2_pkt_adduint32(length);
3274 ssh2_pkt_send();
3275 }
7cca0d81 3276 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
3277 ssh_state = SSH_STATE_CLOSED;
d211621f 3278 logevent("Received disconnect message");
3257deae 3279 crReturnV;
7cca0d81 3280 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
3281 continue; /* exit status et al; ignore (FIXME?) */
d211621f 3282 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
783415f8 3283 unsigned i = ssh2_pkt_getuint32();
3284 struct ssh_channel *c;
3285
3286 c = find234(ssh_channels, &i, ssh_channelfind);
3287 if (!c)
3288 continue; /* nonexistent channel */
3289
3290 if (c->type == CHAN_X11) {
3291 /*
3292 * Remote EOF on an X11 channel means we should
3293 * wrap up and close the channel ourselves.
3294 */
3295 x11_close(c->u.x11.s);
3296 sshfwd_close(c);
3297 }
d211621f 3298 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
783415f8 3299 unsigned i = ssh2_pkt_getuint32();
3300 struct ssh_channel *c;
3301 enum234 e;
3302
3303 c = find234(ssh_channels, &i, ssh_channelfind);
3304 if (!c)
3305 continue; /* nonexistent channel */
3306 if (c->closes == 0) {
3307 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3308 ssh2_pkt_adduint32(c->remoteid);
3309 ssh2_pkt_send();
3310 }
3311 /* Do pre-close processing on the channel. */
3312 switch (c->type) {
3313 case CHAN_MAINSESSION:
3314 break; /* nothing to see here, move along */
3315 case CHAN_X11:
3316 break;
3317 }
3318 del234(ssh_channels, c);
3319 sfree(c->v2.outbuffer);
3320 sfree(c);
3321
3322 /*
3323 * See if that was the last channel left open.
3324 */
3325 c = first234(ssh_channels, &e);
3326 if (!c) {
d211621f 3327 logevent("All channels closed. Disconnecting");
3328 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
9005f3ba 3329 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3330 ssh2_pkt_addstring("All open channels closed");
3331 ssh2_pkt_addstring("en"); /* language tag */
d211621f 3332 ssh2_pkt_send();
cf6e59d6 3333 ssh_state = SSH_STATE_CLOSED;
3257deae 3334 crReturnV;
d211621f 3335 }
3336 continue; /* remote sends close; ignore (FIXME) */
7cca0d81 3337 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
783415f8 3338 unsigned i = ssh2_pkt_getuint32();
3339 struct ssh_channel *c;
3340 c = find234(ssh_channels, &i, ssh_channelfind);
3341 if (!c)
3342 continue; /* nonexistent channel */
3343 mainchan->v2.remwindow += ssh2_pkt_getuint32();
d211621f 3344 try_send = TRUE;
783415f8 3345 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
3346 char *type;
3347 int typelen;
3348 char *error = NULL;
3349 struct ssh_channel *c;
3350 ssh2_pkt_getstring(&type, &typelen);
3351 c = smalloc(sizeof(struct ssh_channel));
3352
3353 if (typelen == 3 && !memcmp(type, "x11", 3)) {
783415f8 3354 if (!ssh_X11_fwd_enabled)
3355 error = "X11 forwarding is not enabled";
0c6c9a70 3356 else if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
783415f8 3357 error = "Unable to open an X11 connection";
3358 } else {
3359 c->type = CHAN_X11;
3360 }
3361 } else {
3362 error = "Unsupported channel type requested";
3363 }
3364
3365 c->remoteid = ssh2_pkt_getuint32();
3366 if (error) {
3367 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
3368 ssh2_pkt_adduint32(c->remoteid);
3369 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
3370 ssh2_pkt_addstring(error);
3371 ssh2_pkt_addstring("en"); /* language tag */
3372 ssh2_pkt_send();
3373 sfree(c);
3374 } else {
3375 struct ssh_channel *d;
3376 unsigned i;
3377 enum234 e;
3378
3379 for (i=1, d = first234(ssh_channels, &e); d;
3380 d = next234(&e)) {
3381 if (d->localid > i)
3382 break; /* found a free number */
3383 i = d->localid + 1;
3384 }
3385 c->localid = i;
3386 c->closes = 0;
3387 c->v2.remwindow = ssh2_pkt_getuint32();
3388 c->v2.remmaxpkt = ssh2_pkt_getuint32();
3389 c->v2.outbuffer = NULL;
3390 c->v2.outbuflen = c->v2.outbufsize = 0;
3391 add234(ssh_channels, c);
3392 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
3393 ssh2_pkt_adduint32(c->remoteid);
3394 ssh2_pkt_adduint32(c->localid);
3395 ssh2_pkt_adduint32(0x8000UL); /* our window size */
3396 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
3397 ssh2_pkt_send();
3398 }
7cca0d81 3399 } else {
8d5de777 3400 bombout(("Strange packet received: type %d", pktin.type));
3401 crReturnV;
7cca0d81 3402 }
3403 } else {
d211621f 3404 /*
3405 * We have spare data. Add it to the channel buffer.
3406 */
783415f8 3407 ssh2_add_channel_data(mainchan, in, inlen);
d211621f 3408 try_send = TRUE;
7cca0d81 3409 }
d211621f 3410 if (try_send) {
783415f8 3411 enum234 e;
3412 struct ssh_channel *c;
d211621f 3413 /*
783415f8 3414 * Try to send data on all channels if we can.
d211621f 3415 */
783415f8 3416 for (c = first234(ssh_channels, &e); c; c = next234(&e))
3417 ssh2_try_send(c);
d211621f 3418 }
e5574168 3419 }
3420
3421 crFinishV;
3422}
3423
3424/*
7cca0d81 3425 * Handle the top-level SSH2 protocol.
3426 */
3427static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
3428{
3429 if (do_ssh2_transport(in, inlen, ispkt) == 0)
3430 return;
3431 do_ssh2_authconn(in, inlen, ispkt);
3432}
3433
3434/*
8df7a775 3435 * Called to set up the connection.
374330e2 3436 *
3437 * Returns an error message, or NULL on success.
374330e2 3438 */
8df7a775 3439static char *ssh_init (char *host, int port, char **realhost) {
fb09bf1c 3440 char *p;
8f203108 3441
3442#ifdef MSCRYPTOAPI
3443 if(crypto_startup() == 0)
3444 return "Microsoft high encryption pack not installed!";
3445#endif
374330e2 3446
8df7a775 3447 ssh_send_ok = 0;
0965bee0 3448 ssh_editing = 0;
3449 ssh_echoing = 0;
8df7a775 3450
fb09bf1c 3451 p = connect_to_host(host, port, realhost);
3452 if (p != NULL)
3453 return p;
374330e2 3454
374330e2 3455 return NULL;
3456}
3457
3458/*
374330e2 3459 * Called to send data down the Telnet connection.
3460 */
3461static void ssh_send (char *buf, int len) {
f78051a1 3462 if (s == NULL || ssh_protocol == NULL)
374330e2 3463 return;
3464
3465 ssh_protocol(buf, len, 0);
3466}
3467
3468/*
6e48c3fe 3469 * Called to set the size of the window from SSH's POV.
374330e2 3470 */
3471static void ssh_size(void) {
3472 switch (ssh_state) {
3473 case SSH_STATE_BEFORE_SIZE:
3687d221 3474 case SSH_STATE_PREPACKET:
21248260 3475 case SSH_STATE_CLOSED:
374330e2 3476 break; /* do nothing */
3477 case SSH_STATE_INTERMED:
3478 size_needed = TRUE; /* buffer for later */
3479 break;
3480 case SSH_STATE_SESSION:
fef97f43 3481 if (!cfg.nopty) {
6e48c3fe 3482 if (ssh_version == 1) {
3483 send_packet(SSH1_CMSG_WINDOW_SIZE,
3484 PKT_INT, rows, PKT_INT, cols,
3485 PKT_INT, 0, PKT_INT, 0, PKT_END);
3486 } else {
3487 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3488 ssh2_pkt_adduint32(mainchan->remoteid);
3489 ssh2_pkt_addstring("window-change");
3490 ssh2_pkt_addbool(0);
3491 ssh2_pkt_adduint32(cols);
3492 ssh2_pkt_adduint32(rows);
3493 ssh2_pkt_adduint32(0);
3494 ssh2_pkt_adduint32(0);
3495 ssh2_pkt_send();
3496 }
fef97f43 3497 }
3687d221 3498 break;
374330e2 3499 }
3500}
3501
3502/*
6abbf9e3 3503 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3504 * can send an EOF and collect resulting output (e.g. `plink
3505 * hostname sort').
374330e2 3506 */
3507static void ssh_special (Telnet_Special code) {
6abbf9e3 3508 if (code == TS_EOF) {
3687d221 3509 if (ssh_state != SSH_STATE_SESSION) {
3510 /*
3511 * Buffer the EOF in case we are pre-SESSION, so we can
3512 * send it as soon as we reach SESSION.
3513 */
3514 if (code == TS_EOF)
3515 eof_needed = TRUE;
3516 return;
3517 }
67779be7 3518 if (ssh_version == 1) {
6abbf9e3 3519 send_packet(SSH1_CMSG_EOF, PKT_END);
3520 } else {
3521 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
d211621f 3522 ssh2_pkt_adduint32(mainchan->remoteid);
6abbf9e3 3523 ssh2_pkt_send();
3524 }
67779be7 3525 logevent("Sent EOF message");
ec55b220 3526 } else if (code == TS_PING) {
3687d221 3527 if (ssh_state == SSH_STATE_CLOSED || ssh_state == SSH_STATE_PREPACKET)
3528 return;
ec55b220 3529 if (ssh_version == 1) {
3530 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
3531 } else {
3532 ssh2_pkt_init(SSH2_MSG_IGNORE);
3533 ssh2_pkt_addstring_start();
3534 ssh2_pkt_send();
3535 }
6abbf9e3 3536 } else {
3537 /* do nothing */
3538 }
374330e2 3539}
3540
8df7a775 3541static Socket ssh_socket(void) { return s; }
8ccc75b0 3542
3543static int ssh_sendok(void) { return ssh_send_ok; }
fb09bf1c 3544
0965bee0 3545static int ssh_ldisc(int option) {
3546 if (option == LD_ECHO) return ssh_echoing;
3547 if (option == LD_EDIT) return ssh_editing;
3548 return FALSE;
3549}
3550
374330e2 3551Backend ssh_backend = {
3552 ssh_init,
374330e2 3553 ssh_send,
3554 ssh_size,
4017be6d 3555 ssh_special,
8ccc75b0 3556 ssh_socket,
97db3be4 3557 ssh_sendok,
0965bee0 3558 ssh_ldisc,
97db3be4 3559 22
374330e2 3560};