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