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