Add a key length indication to each SSH2 cipher structure, in
[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;
3709bfe9 872 int i, n = (ssh1_bignum_bitcount(b)+7)/8;
873 p = smalloc(n + 1);
7cca0d81 874 if (!p)
875 fatalbox("out of memory");
876 p[0] = 0;
3709bfe9 877 for (i = 1; i <= n; i++)
878 p[i] = bignum_byte(b, n-i);
7cca0d81 879 i = 0;
3709bfe9 880 while (i <= n && p[i] == 0 && (p[i+1] & 0x80) == 0)
7cca0d81 881 i++;
3709bfe9 882 memmove(p, p+i, n+1-i);
883 *len = n+1-i;
7cca0d81 884 return p;
885}
75cab814 886static void ssh2_pkt_addmp(Bignum b) {
7cca0d81 887 unsigned char *p;
888 int len;
889 p = ssh2_mpint_fmt(b, &len);
890 ssh2_pkt_addstring_start();
891 ssh2_pkt_addstring_data(p, len);
dcbde236 892 sfree(p);
7cca0d81 893}
b185170a 894
895/*
896 * Construct an SSH2 final-form packet: compress it, encrypt it,
897 * put the MAC on it. Final packet, ready to be sent, is stored in
898 * pktout.data. Total length is returned.
899 */
900static int ssh2_pkt_construct(void) {
7cca0d81 901 int cipherblk, maclen, padding, i;
902 static unsigned long outgoing_sequence = 0;
903
904 /*
4ba9b64b 905 * Compress packet payload.
906 */
907#if 0
908 debug(("Pre-compression payload:\r\n"));
909 for (i = 5; i < pktout.length; i++)
910 debug((" %02x", (unsigned char)pktout.data[i]));
911 debug(("\r\n"));
912#endif
913 {
914 unsigned char *newpayload;
915 int newlen;
916 if (cscomp && cscomp->compress(pktout.data+5, pktout.length-5,
917 &newpayload, &newlen)) {
918 pktout.length = 5;
919 ssh2_pkt_adddata(newpayload, newlen);
dcbde236 920 sfree(newpayload);
4ba9b64b 921 }
922 }
923
924 /*
7cca0d81 925 * Add padding. At least four bytes, and must also bring total
926 * length (minus MAC) up to a multiple of the block size.
927 */
928 cipherblk = cipher ? cipher->blksize : 8; /* block size */
929 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
930 padding = 4;
931 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
783415f8 932 maclen = csmac ? csmac->len : 0;
933 ssh2_pkt_ensure(pktout.length + padding + maclen);
7cca0d81 934 pktout.data[4] = padding;
935 for (i = 0; i < padding; i++)
936 pktout.data[pktout.length + i] = random_byte();
937 PUT_32BIT(pktout.data, pktout.length + padding - 4);
938 if (csmac)
939 csmac->generate(pktout.data, pktout.length + padding,
940 outgoing_sequence);
941 outgoing_sequence++; /* whether or not we MACed */
942
943#if 0
944 debug(("Sending packet len=%d\r\n", pktout.length+padding));
945 for (i = 0; i < pktout.length+padding; i++)
946 debug((" %02x", (unsigned char)pktout.data[i]));
947 debug(("\r\n"));
948#endif
949
950 if (cscipher)
951 cscipher->encrypt(pktout.data, pktout.length + padding);
7cca0d81 952
b185170a 953 /* Ready-to-send packet starts at pktout.data. We return length. */
954 return pktout.length + padding + maclen;
955}
956
957/*
958 * Construct and send an SSH2 packet immediately.
959 */
960static void ssh2_pkt_send(void) {
961 int len = ssh2_pkt_construct();
962 sk_write(s, pktout.data, len);
963}
964
965/*
966 * Construct an SSH2 packet and add it to a deferred data block.
967 * Useful for sending multiple packets in a single sk_write() call,
968 * to prevent a traffic-analysing listener from being able to work
969 * out the length of any particular packet (such as the password
970 * packet).
971 *
972 * Note that because SSH2 sequence-numbers its packets, this can
973 * NOT be used as an m4-style `defer' allowing packets to be
974 * constructed in one order and sent in another.
975 */
976static void ssh2_pkt_defer(void) {
977 int len = ssh2_pkt_construct();
978 if (deferred_len + len > deferred_size) {
979 deferred_size = deferred_len + len + 128;
980 deferred_send_data = srealloc(deferred_send_data, deferred_size);
981 }
982 memcpy(deferred_send_data+deferred_len, pktout.data, len);
983 deferred_len += len;
984}
985
986/*
987 * Send the whole deferred data block constructed by
988 * ssh2_pkt_defer().
989 */
990static void ssh2_pkt_defersend(void) {
991 sk_write(s, deferred_send_data, deferred_len);
992 deferred_len = deferred_size = 0;
993 sfree(deferred_send_data);
994 deferred_send_data = NULL;
7cca0d81 995}
996
997#if 0
998void bndebug(char *string, Bignum b) {
999 unsigned char *p;
1000 int i, len;
1001 p = ssh2_mpint_fmt(b, &len);
1002 debug(("%s", string));
1003 for (i = 0; i < len; i++)
1004 debug((" %02x", p[i]));
1005 debug(("\r\n"));
dcbde236 1006 sfree(p);
7cca0d81 1007}
1008#endif
1009
75cab814 1010static void sha_mpint(SHA_State *s, Bignum b) {
7cca0d81 1011 unsigned char *p;
1012 int len;
1013 p = ssh2_mpint_fmt(b, &len);
1014 sha_string(s, p, len);
dcbde236 1015 sfree(p);
7cca0d81 1016}
1017
1018/*
1019 * SSH2 packet decode functions.
1020 */
75cab814 1021static unsigned long ssh2_pkt_getuint32(void) {
7cca0d81 1022 unsigned long value;
1023 if (pktin.length - pktin.savedpos < 4)
1024 return 0; /* arrgh, no way to decline (FIXME?) */
1025 value = GET_32BIT(pktin.data+pktin.savedpos);
1026 pktin.savedpos += 4;
1027 return value;
1028}
75cab814 1029static void ssh2_pkt_getstring(char **p, int *length) {
7cca0d81 1030 *p = NULL;
1031 if (pktin.length - pktin.savedpos < 4)
1032 return;
1033 *length = GET_32BIT(pktin.data+pktin.savedpos);
1034 pktin.savedpos += 4;
1035 if (pktin.length - pktin.savedpos < *length)
1036 return;
1037 *p = pktin.data+pktin.savedpos;
1038 pktin.savedpos += *length;
1039}
75cab814 1040static Bignum ssh2_pkt_getmp(void) {
7cca0d81 1041 char *p;
3709bfe9 1042 int length;
7cca0d81 1043 Bignum b;
1044
1045 ssh2_pkt_getstring(&p, &length);
1046 if (!p)
1047 return NULL;
8d5de777 1048 if (p[0] & 0x80) {
1049 bombout(("internal error: Can't handle negative mpints"));
1050 return NULL;
1051 }
3709bfe9 1052 b = bignum_from_bytes(p, length);
7cca0d81 1053 return b;
1054}
1055
8df7a775 1056static int do_ssh_init(unsigned char c) {
1057 static char *vsp;
1058 static char version[10];
1059 static char vstring[80];
1060 static char vlog[sizeof(vstring)+20];
1061 static int i;
374330e2 1062
8df7a775 1063 crBegin;
1064
1065 /* Search for the string "SSH-" in the input. */
374330e2 1066 i = 0;
8df7a775 1067 while (1) {
1068 static const int transS[] = { 1, 2, 2, 1 };
1069 static const int transH[] = { 0, 0, 3, 0 };
1070 static const int transminus[] = { 0, 0, 0, -1 };
1071 if (c == 'S') i = transS[i];
1072 else if (c == 'H') i = transH[i];
1073 else if (c == '-') i = transminus[i];
374330e2 1074 else i = 0;
8df7a775 1075 if (i < 0)
1076 break;
1077 crReturn(1); /* get another character */
374330e2 1078 }
8df7a775 1079
c5e9c988 1080 strcpy(vstring, "SSH-");
1081 vsp = vstring+4;
374330e2 1082 i = 0;
1083 while (1) {
8df7a775 1084 crReturn(1); /* get another char */
c5e9c988 1085 if (vsp < vstring+sizeof(vstring)-1)
1086 *vsp++ = c;
374330e2 1087 if (i >= 0) {
1088 if (c == '-') {
1089 version[i] = '\0';
1090 i = -1;
1091 } else if (i < sizeof(version)-1)
1092 version[i++] = c;
1093 }
1094 else if (c == '\n')
1095 break;
1096 }
1097
db7d555c 1098 ssh_agentfwd_enabled = FALSE;
960e736a 1099 rdpkt2_state.incoming_sequence = 0;
1100
c5e9c988 1101 *vsp = 0;
1102 sprintf(vlog, "Server version: %s", vstring);
1103 vlog[strcspn(vlog, "\r\n")] = '\0';
1104 logevent(vlog);
1105
adf799dd 1106 /*
1107 * Server version "1.99" means we can choose whether we use v1
1108 * or v2 protocol. Choice is based on cfg.sshprot.
1109 */
1110 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
e5574168 1111 /*
1112 * This is a v2 server. Begin v2 protocol.
1113 */
1114 char *verstring = "SSH-2.0-PuTTY";
0db56f73 1115 SHA_Init(&exhashbase);
e5574168 1116 /*
1117 * Hash our version string and their version string.
1118 */
0db56f73 1119 sha_string(&exhashbase, verstring, strlen(verstring));
1120 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
e5574168 1121 sprintf(vstring, "%s\n", verstring);
1122 sprintf(vlog, "We claim version: %s", verstring);
1123 logevent(vlog);
1124 logevent("Using SSH protocol version 2");
8df7a775 1125 sk_write(s, vstring, strlen(vstring));
e5574168 1126 ssh_protocol = ssh2_protocol;
6abbf9e3 1127 ssh_version = 2;
e5574168 1128 s_rdpkt = ssh2_rdpkt;
1129 } else {
1130 /*
1131 * This is a v1 server. Begin v1 protocol.
1132 */
1133 sprintf(vstring, "SSH-%s-PuTTY\n",
1134 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1135 sprintf(vlog, "We claim version: %s", vstring);
1136 vlog[strcspn(vlog, "\r\n")] = '\0';
1137 logevent(vlog);
1138 logevent("Using SSH protocol version 1");
8df7a775 1139 sk_write(s, vstring, strlen(vstring));
e5574168 1140 ssh_protocol = ssh1_protocol;
6abbf9e3 1141 ssh_version = 1;
e5574168 1142 s_rdpkt = ssh1_rdpkt;
1143 }
3687d221 1144 ssh_state = SSH_STATE_BEFORE_SIZE;
8df7a775 1145
1146 crFinish(0);
1147}
1148
1149static void ssh_gotdata(unsigned char *data, int datalen)
1150{
1151 crBegin;
1152
1153 /*
1154 * To begin with, feed the characters one by one to the
1155 * protocol initialisation / selection function do_ssh_init().
1156 * When that returns 0, we're done with the initial greeting
1157 * exchange and can move on to packet discipline.
1158 */
1159 while (1) {
1160 int ret;
1161 if (datalen == 0)
1162 crReturnV; /* more data please */
1163 ret = do_ssh_init(*data);
1164 data++; datalen--;
1165 if (ret == 0)
1166 break;
1167 }
1168
1169 /*
1170 * We emerge from that loop when the initial negotiation is
1171 * over and we have selected an s_rdpkt function. Now pass
1172 * everything to s_rdpkt, and then pass the resulting packets
1173 * to the proper protocol handler.
1174 */
1175 if (datalen == 0)
1176 crReturnV;
1177 while (1) {
1178 while (datalen > 0) {
1179 if ( s_rdpkt(&data, &datalen) == 0 ) {
1180 ssh_protocol(NULL, 0, 1);
1181 if (ssh_state == SSH_STATE_CLOSED) {
1182 return;
1183 }
1184 }
1185 }
1186 crReturnV;
1187 }
1188 crFinishV;
1189}
1190
340cf649 1191static int ssh_receive(Socket skt, int urgent, char *data, int len) {
2c94fd1c 1192 if (urgent==3) {
1193 /* A socket error has occurred. */
7dbb9f56 1194 ssh_state = SSH_STATE_CLOSED;
b47b2198 1195 sk_close(s);
7dbb9f56 1196 s = NULL;
2c94fd1c 1197 connection_fatal(data);
b47b2198 1198 return 0;
1199 } else if (!len) {
8df7a775 1200 /* Connection has closed. */
6abb6cd7 1201 ssh_state = SSH_STATE_CLOSED;
8df7a775 1202 sk_close(s);
1203 s = NULL;
1204 return 0;
1205 }
1206 ssh_gotdata (data, len);
3257deae 1207 if (ssh_state == SSH_STATE_CLOSED) {
1208 if (s) {
1209 sk_close(s);
1210 s = NULL;
1211 }
1212 return 0;
1213 }
fef97f43 1214 return 1;
374330e2 1215}
1216
fb09bf1c 1217/*
8df7a775 1218 * Connect to specified host and port.
1219 * Returns an error message, or NULL on success.
1220 * Also places the canonical host name into `realhost'.
1221 */
1222static char *connect_to_host(char *host, int port, char **realhost)
1223{
1224 SockAddr addr;
1225 char *err;
1226#ifdef FWHACK
1227 char *FWhost;
1228 int FWport;
1229#endif
1230
dcbde236 1231 savedhost = smalloc(1+strlen(host));
8df7a775 1232 if (!savedhost)
1233 fatalbox("Out of memory");
1234 strcpy(savedhost, host);
1235
1236 if (port < 0)
1237 port = 22; /* default ssh port */
1238 savedport = port;
1239
1240#ifdef FWHACK
1241 FWhost = host;
1242 FWport = port;
1243 host = FWSTR;
1244 port = 23;
1245#endif
1246
1247 /*
1248 * Try to find host.
1249 */
1250 addr = sk_namelookup(host, realhost);
1251 if ( (err = sk_addr_error(addr)) )
1252 return err;
1253
1254#ifdef FWHACK
1255 *realhost = FWhost;
1256#endif
1257
1258 /*
1259 * Open socket.
1260 */
4b1e8acc 1261 s = sk_new(addr, port, 0, 1, ssh_receive);
8df7a775 1262 if ( (err = sk_socket_error(s)) )
1263 return err;
1264
1265#ifdef FWHACK
1266 sk_write(s, "connect ", 8);
1267 sk_write(s, FWhost, strlen(FWhost));
1268 {
1269 char buf[20];
1270 sprintf(buf, " %d\n", FWport);
1271 sk_write(s, buf, strlen(buf));
1272 }
1273#endif
1274
1275 return NULL;
1276}
1277
1278/*
fb09bf1c 1279 * Handle the key exchange and user authentication phases.
1280 */
e5574168 1281static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
fb09bf1c 1282{
374330e2 1283 int i, j, len;
374330e2 1284 unsigned char *rsabuf, *keystr1, *keystr2;
1285 unsigned char cookie[8];
1286 struct RSAKey servkey, hostkey;
1287 struct MD5Context md5c;
ccbfb941 1288 static unsigned long supported_ciphers_mask, supported_auths_mask;
7cca0d81 1289 static int tried_publickey;
1290 static unsigned char session_id[16];
bea1ef5f 1291 int cipher_type;
b585ec46 1292 static char username[100];
374330e2 1293
374330e2 1294 crBegin;
1295
fb09bf1c 1296 if (!ispkt) crWaitUntil(ispkt);
374330e2 1297
8d5de777 1298 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1299 bombout(("Public key packet not received"));
1300 crReturn(0);
1301 }
374330e2 1302
c5e9c988 1303 logevent("Received public keys");
374330e2 1304
c5e9c988 1305 memcpy(cookie, pktin.body, 8);
374330e2 1306
7cca0d81 1307 i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1308 j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
374330e2 1309
c5e9c988 1310 /*
1c2a93c4 1311 * Log the host key fingerprint.
c5e9c988 1312 */
c5e9c988 1313 {
1314 char logmsg[80];
1c2a93c4 1315 logevent("Host key fingerprint is:");
c5e9c988 1316 strcpy(logmsg, " ");
1c2a93c4 1317 hostkey.comment = NULL;
1318 rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
1319 &hostkey);
c5e9c988 1320 logevent(logmsg);
1321 }
1322
fb09bf1c 1323 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1324 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
bea1ef5f 1325
c5e9c988 1326 MD5Init(&md5c);
374330e2 1327 MD5Update(&md5c, keystr2, hostkey.bytes);
1328 MD5Update(&md5c, keystr1, servkey.bytes);
1329 MD5Update(&md5c, pktin.body, 8);
374330e2 1330 MD5Final(session_id, &md5c);
1331
1332 for (i=0; i<32; i++)
1333 session_key[i] = random_byte();
1334
1335 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1336
dcbde236 1337 rsabuf = smalloc(len);
374330e2 1338 if (!rsabuf)
1339 fatalbox("Out of memory");
1340
89ee5268 1341 /*
1342 * Verify the host key.
1343 */
1344 {
1345 /*
1346 * First format the key into a string.
1347 */
1348 int len = rsastr_len(&hostkey);
d5859615 1349 char fingerprint[100];
dcbde236 1350 char *keystr = smalloc(len);
89ee5268 1351 if (!keystr)
1352 fatalbox("Out of memory");
1353 rsastr_fmt(keystr, &hostkey);
d5859615 1354 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
d4857987 1355 verify_ssh_host_key(savedhost, savedport, "rsa", keystr, fingerprint);
dcbde236 1356 sfree(keystr);
89ee5268 1357 }
374330e2 1358
1359 for (i=0; i<32; i++) {
1360 rsabuf[i] = session_key[i];
1361 if (i < 16)
1362 rsabuf[i] ^= session_id[i];
1363 }
1364
1365 if (hostkey.bytes > servkey.bytes) {
1366 rsaencrypt(rsabuf, 32, &servkey);
1367 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1368 } else {
1369 rsaencrypt(rsabuf, 32, &hostkey);
1370 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1371 }
1372
c5e9c988 1373 logevent("Encrypted session key");
1374
bea1ef5f 1375 cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
9697bfd2 1376 cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES :
bea1ef5f 1377 SSH_CIPHER_3DES;
1378 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1379 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1380 cipher_type = SSH_CIPHER_3DES;
1381 }
c5e9c988 1382 switch (cipher_type) {
1383 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1384 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1385 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1386 }
bea1ef5f 1387
e5574168 1388 send_packet(SSH1_CMSG_SESSION_KEY,
fb09bf1c 1389 PKT_CHAR, cipher_type,
1390 PKT_DATA, cookie, 8,
1391 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1392 PKT_DATA, rsabuf, len,
1393 PKT_INT, 0,
1394 PKT_END);
1395
c5e9c988 1396 logevent("Trying to enable encryption...");
374330e2 1397
dcbde236 1398 sfree(rsabuf);
374330e2 1399
5e8358ad 1400 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
9697bfd2 1401 cipher_type == SSH_CIPHER_DES ? &ssh_des :
bea1ef5f 1402 &ssh_3des;
374330e2 1403 cipher->sesskey(session_key);
1404
fb09bf1c 1405 crWaitUntil(ispkt);
374330e2 1406
8d5de777 1407 if (pktin.type != SSH1_SMSG_SUCCESS) {
1408 bombout(("Encryption not successfully enabled"));
1409 crReturn(0);
1410 }
374330e2 1411
c5e9c988 1412 logevent("Successfully started encryption");
1413
374330e2 1414 fflush(stdout);
1415 {
374330e2 1416 static int pos = 0;
1417 static char c;
67779be7 1418 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
374330e2 1419 c_write("login as: ", 10);
67779be7 1420 ssh_send_ok = 1;
374330e2 1421 while (pos >= 0) {
fb09bf1c 1422 crWaitUntil(!ispkt);
374330e2 1423 while (inlen--) switch (c = *in++) {
1424 case 10: case 13:
1425 username[pos] = 0;
1426 pos = -1;
1427 break;
1428 case 8: case 127:
1429 if (pos > 0) {
1430 c_write("\b \b", 3);
1431 pos--;
1432 }
1433 break;
1434 case 21: case 27:
1435 while (pos > 0) {
1436 c_write("\b \b", 3);
1437 pos--;
1438 }
1439 break;
1440 case 3: case 4:
1441 random_save_seed();
1442 exit(0);
1443 break;
1444 default:
40d24aa6 1445 if (((c >= ' ' && c <= '~') ||
1446 ((unsigned char)c >= 160)) && pos < 40) {
374330e2 1447 username[pos++] = c;
1448 c_write(&c, 1);
1449 }
1450 break;
1451 }
1452 }
1453 c_write("\r\n", 2);
1454 username[strcspn(username, "\n\r")] = '\0';
1455 } else {
374330e2 1456 strncpy(username, cfg.username, 99);
1457 username[99] = '\0';
374330e2 1458 }
fb09bf1c 1459
e5574168 1460 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
c5e9c988 1461 {
3c8e959b 1462 char userlog[22+sizeof(username)];
c5e9c988 1463 sprintf(userlog, "Sent username \"%s\"", username);
1464 logevent(userlog);
3c8e959b 1465 if (flags & FLAG_INTERACTIVE &&
1466 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
1467 strcat(userlog, "\r\n");
1468 c_write(userlog, strlen(userlog));
1469 }
c5e9c988 1470 }
374330e2 1471 }
1472
fb09bf1c 1473 crWaitUntil(ispkt);
374330e2 1474
7cca0d81 1475 tried_publickey = 0;
1476
e5574168 1477 while (pktin.type == SSH1_SMSG_FAILURE) {
374330e2 1478 static char password[100];
a52f067e 1479 static char prompt[200];
374330e2 1480 static int pos;
1481 static char c;
ccbfb941 1482 static int pwpkt_type;
ccbfb941 1483 /*
1484 * Show password prompt, having first obtained it via a TIS
18515c51 1485 * or CryptoCard exchange if we're doing TIS or CryptoCard
1486 * authentication.
ccbfb941 1487 */
e5574168 1488 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
5c58ad2d 1489 if (agent_exists()) {
1490 /*
1491 * Attempt RSA authentication using Pageant.
1492 */
1493 static unsigned char request[5], *response, *p;
1494 static int responselen;
1495 static int i, nkeys;
1496 static int authed = FALSE;
1497 void *r;
1498
1499 logevent("Pageant is running. Requesting keys.");
1500
1501 /* Request the keys held by the agent. */
1502 PUT_32BIT(request, 1);
1503 request[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
1504 agent_query(request, 5, &r, &responselen);
1505 response = (unsigned char *)r;
1506 if (response) {
1507 p = response + 5;
1508 nkeys = GET_32BIT(p); p += 4;
1509 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
1510 logevent(buf); }
1511 for (i = 0; i < nkeys; i++) {
1512 static struct RSAKey key;
1513 static Bignum challenge;
b8bb811a 1514 static char *commentp;
1515 static int commentlen;
5c58ad2d 1516
1517 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1518 logevent(buf); }
1519 p += 4;
1520 p += ssh1_read_bignum(p, &key.exponent);
1521 p += ssh1_read_bignum(p, &key.modulus);
b8bb811a 1522 commentlen = GET_32BIT(p); p += 4;
1523 commentp = p; p += commentlen;
5c58ad2d 1524 send_packet(SSH1_CMSG_AUTH_RSA,
1525 PKT_BIGNUM, key.modulus, PKT_END);
1526 crWaitUntil(ispkt);
1527 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1528 logevent("Key refused");
1529 continue;
1530 }
1531 logevent("Received RSA challenge");
1532 ssh1_read_bignum(pktin.body, &challenge);
1533 {
1534 char *agentreq, *q, *ret;
1535 int len, retlen;
1536 len = 1 + 4; /* message type, bit count */
1537 len += ssh1_bignum_length(key.exponent);
1538 len += ssh1_bignum_length(key.modulus);
1539 len += ssh1_bignum_length(challenge);
1540 len += 16; /* session id */
1541 len += 4; /* response format */
dcbde236 1542 agentreq = smalloc(4 + len);
5c58ad2d 1543 PUT_32BIT(agentreq, len);
1544 q = agentreq + 4;
1545 *q++ = SSH_AGENTC_RSA_CHALLENGE;
1546 PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1547 q += 4;
1548 q += ssh1_write_bignum(q, key.exponent);
1549 q += ssh1_write_bignum(q, key.modulus);
1550 q += ssh1_write_bignum(q, challenge);
1551 memcpy(q, session_id, 16); q += 16;
1552 PUT_32BIT(q, 1); /* response format */
1553 agent_query(agentreq, len+4, &ret, &retlen);
dcbde236 1554 sfree(agentreq);
5c58ad2d 1555 if (ret) {
1556 if (ret[4] == SSH_AGENT_RSA_RESPONSE) {
1557 logevent("Sending Pageant's response");
1558 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1559 PKT_DATA, ret+5, 16, PKT_END);
dcbde236 1560 sfree(ret);
5c58ad2d 1561 crWaitUntil(ispkt);
1562 if (pktin.type == SSH1_SMSG_SUCCESS) {
1563 logevent("Pageant's response accepted");
c4fa2fce 1564 if (flags & FLAG_VERBOSE) {
1565 c_write("Authenticated using RSA key \"",
1566 29);
1567 c_write(commentp, commentlen);
1568 c_write("\" from agent\r\n", 14);
1569 }
5c58ad2d 1570 authed = TRUE;
1571 } else
1572 logevent("Pageant's response not accepted");
1573 } else {
1574 logevent("Pageant failed to answer challenge");
dcbde236 1575 sfree(ret);
5c58ad2d 1576 }
1577 } else {
1578 logevent("No reply received from Pageant");
1579 }
1580 }
1581 freebn(key.exponent);
1582 freebn(key.modulus);
1583 freebn(challenge);
1584 if (authed)
1585 break;
1586 }
1587 }
1588 if (authed)
1589 break;
1590 }
7cca0d81 1591 if (*cfg.keyfile && !tried_publickey)
1592 pwpkt_type = SSH1_CMSG_AUTH_RSA;
fb09bf1c 1593
a52f067e 1594 if (pktin.type == SSH1_SMSG_FAILURE &&
1595 cfg.try_tis_auth &&
1596 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1597 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1598 logevent("Requested TIS authentication");
1599 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1600 crWaitUntil(ispkt);
1601 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1602 logevent("TIS authentication declined");
1603 if (flags & FLAG_INTERACTIVE)
1604 c_write("TIS authentication refused.\r\n", 29);
1605 } else {
1606 int challengelen = ((pktin.body[0] << 24) |
1607 (pktin.body[1] << 16) |
1608 (pktin.body[2] << 8) |
1609 (pktin.body[3]));
1610 logevent("Received TIS challenge");
1611 if (challengelen > sizeof(prompt)-1)
1612 challengelen = sizeof(prompt)-1; /* prevent overrun */
1613 memcpy(prompt, pktin.body+4, challengelen);
1614 prompt[challengelen] = '\0';
1615 }
1616 }
1617 if (pktin.type == SSH1_SMSG_FAILURE &&
1618 cfg.try_tis_auth &&
1619 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1620 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1621 logevent("Requested CryptoCard authentication");
1622 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1623 crWaitUntil(ispkt);
1624 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1625 logevent("CryptoCard authentication declined");
1626 c_write("CryptoCard authentication refused.\r\n", 29);
1627 } else {
1628 int challengelen = ((pktin.body[0] << 24) |
1629 (pktin.body[1] << 16) |
1630 (pktin.body[2] << 8) |
1631 (pktin.body[3]));
1632 logevent("Received CryptoCard challenge");
1633 if (challengelen > sizeof(prompt)-1)
1634 challengelen = sizeof(prompt)-1; /* prevent overrun */
1635 memcpy(prompt, pktin.body+4, challengelen);
1636 strncpy(prompt + challengelen, "\r\nResponse : ",
1637 sizeof(prompt)-challengelen);
1638 prompt[sizeof(prompt)-1] = '\0';
1639 }
1640 }
1641 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1642 sprintf(prompt, "%.90s@%.90s's password: ",
b585ec46 1643 username, savedhost);
a52f067e 1644 }
1645 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1646 char *comment = NULL;
1647 if (flags & FLAG_VERBOSE)
1648 c_write("Trying public key authentication.\r\n", 35);
1649 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1650 if (flags & FLAG_VERBOSE)
1651 c_write("No passphrase required.\r\n", 25);
1652 goto tryauth;
1653 }
1654 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
dcbde236 1655 sfree(comment);
a52f067e 1656 }
1657
d8426c54 1658 if (ssh_get_password) {
85ee8208 1659 if (!ssh_get_password(prompt, password, sizeof(password))) {
1660 /*
1661 * get_password failed to get a password (for
1662 * example because one was supplied on the command
1663 * line which has already failed to work).
1664 * Terminate.
1665 */
1666 logevent("No more passwords to try");
1667 ssh_state = SSH_STATE_CLOSED;
1668 crReturn(1);
1669 }
fb09bf1c 1670 } else {
a52f067e 1671 c_write(prompt, strlen(prompt));
7cca0d81 1672 pos = 0;
67779be7 1673 ssh_send_ok = 1;
7cca0d81 1674 while (pos >= 0) {
1675 crWaitUntil(!ispkt);
1676 while (inlen--) switch (c = *in++) {
1677 case 10: case 13:
1678 password[pos] = 0;
1679 pos = -1;
1680 break;
1681 case 8: case 127:
1682 if (pos > 0)
1683 pos--;
1684 break;
1685 case 21: case 27:
1686 pos = 0;
1687 break;
1688 case 3: case 4:
1689 random_save_seed();
1690 exit(0);
1691 break;
1692 default:
1693 if (((c >= ' ' && c <= '~') ||
1694 ((unsigned char)c >= 160)) && pos < sizeof(password))
1695 password[pos++] = c;
1696 break;
1697 }
1698 }
1699 c_write("\r\n", 2);
a52f067e 1700 }
fb09bf1c 1701
7cca0d81 1702 tryauth:
1703 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1704 /*
1705 * Try public key authentication with the specified
1706 * key file.
1707 */
1708 static struct RSAKey pubkey;
1709 static Bignum challenge, response;
1710 static int i;
1711 static unsigned char buffer[32];
1712
1713 tried_publickey = 1;
6e522441 1714 i = loadrsakey(cfg.keyfile, &pubkey, NULL, password);
7cca0d81 1715 if (i == 0) {
1716 c_write("Couldn't load public key from ", 30);
1717 c_write(cfg.keyfile, strlen(cfg.keyfile));
1718 c_write(".\r\n", 3);
1719 continue; /* go and try password */
1720 }
1721 if (i == -1) {
1722 c_write("Wrong passphrase.\r\n", 19);
1723 tried_publickey = 0;
1724 continue; /* try again */
1725 }
1726
1727 /*
1728 * Send a public key attempt.
1729 */
1730 send_packet(SSH1_CMSG_AUTH_RSA,
1731 PKT_BIGNUM, pubkey.modulus, PKT_END);
1732
1733 crWaitUntil(ispkt);
1734 if (pktin.type == SSH1_SMSG_FAILURE) {
a52f067e 1735 c_write("Server refused our public key.\r\n", 32);
7cca0d81 1736 continue; /* go and try password */
1737 }
8d5de777 1738 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1739 bombout(("Bizarre response to offer of public key"));
1740 crReturn(0);
1741 }
7cca0d81 1742 ssh1_read_bignum(pktin.body, &challenge);
1743 response = rsadecrypt(challenge, &pubkey);
1744 freebn(pubkey.private_exponent); /* burn the evidence */
1745
3709bfe9 1746 for (i = 0; i < 32; i++) {
1747 buffer[i] = bignum_byte(response, 31-i);
7cca0d81 1748 }
1749
1750 MD5Init(&md5c);
1751 MD5Update(&md5c, buffer, 32);
1752 MD5Update(&md5c, session_id, 16);
1753 MD5Final(buffer, &md5c);
1754
1755 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1756 PKT_DATA, buffer, 16, PKT_END);
1757
1758 crWaitUntil(ispkt);
1759 if (pktin.type == SSH1_SMSG_FAILURE) {
4017be6d 1760 if (flags & FLAG_VERBOSE)
1761 c_write("Failed to authenticate with our public key.\r\n",
1762 45);
7cca0d81 1763 continue; /* go and try password */
1764 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
8d5de777 1765 bombout(("Bizarre response to RSA authentication response"));
1766 crReturn(0);
7cca0d81 1767 }
1768
1769 break; /* we're through! */
1770 } else {
1771 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1772 }
c5e9c988 1773 logevent("Sent password");
374330e2 1774 memset(password, 0, strlen(password));
fb09bf1c 1775 crWaitUntil(ispkt);
e5574168 1776 if (pktin.type == SSH1_SMSG_FAILURE) {
4017be6d 1777 if (flags & FLAG_VERBOSE)
1778 c_write("Access denied\r\n", 15);
c5e9c988 1779 logevent("Authentication refused");
e5574168 1780 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
fb09bf1c 1781 logevent("Received disconnect request");
85ee8208 1782 ssh_state = SSH_STATE_CLOSED;
1783 crReturn(1);
e5574168 1784 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
8d5de777 1785 bombout(("Strange packet received, type %d", pktin.type));
1786 crReturn(0);
374330e2 1787 }
1788 }
1789
c5e9c988 1790 logevent("Authentication successful");
1791
fb09bf1c 1792 crFinish(1);
1793}
1794
9c964e85 1795void sshfwd_close(struct ssh_channel *c) {
783415f8 1796 if (c) {
1797 if (ssh_version == 1) {
1798 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END);
1799 } else {
1800 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
1801 ssh2_pkt_adduint32(c->remoteid);
1802 ssh2_pkt_send();
1803 }
1804 c->closes = 1;
1805 if (c->type == CHAN_X11) {
1806 c->u.x11.s = NULL;
1807 logevent("X11 connection terminated");
1808 }
1809 }
9c964e85 1810}
1811
1812void sshfwd_write(struct ssh_channel *c, char *buf, int len) {
783415f8 1813 if (ssh_version == 1) {
1814 send_packet(SSH1_MSG_CHANNEL_DATA,
1815 PKT_INT, c->remoteid,
1816 PKT_INT, len,
1817 PKT_DATA, buf, len,
1818 PKT_END);
1819 } else {
1820 ssh2_add_channel_data(c, buf, len);
1821 ssh2_try_send(c);
1822 }
9c964e85 1823}
1824
e5574168 1825static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
fb09bf1c 1826 crBegin;
1827
1828 random_init();
1829
e5574168 1830 while (!do_ssh1_login(in, inlen, ispkt)) {
fb09bf1c 1831 crReturnV;
85ee8208 1832 }
1833 if (ssh_state == SSH_STATE_CLOSED)
1834 crReturnV;
fb09bf1c 1835
979310f1 1836 if (cfg.agentfwd && agent_exists()) {
dacbd0e8 1837 logevent("Requesting agent forwarding");
1838 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1839 do { crReturnV; } while (!ispkt);
1840 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
8d5de777 1841 bombout(("Protocol confusion"));
1842 crReturnV;
dacbd0e8 1843 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1844 logevent("Agent forwarding refused");
db7d555c 1845 } else {
dacbd0e8 1846 logevent("Agent forwarding enabled");
db7d555c 1847 ssh_agentfwd_enabled = TRUE;
1848 }
dacbd0e8 1849 }
1850
9c964e85 1851 if (cfg.x11_forward) {
1852 char proto[20], data[64];
1853 logevent("Requesting X11 forwarding");
1854 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
1855 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
1856 PKT_STR, proto, PKT_STR, data,
1857 PKT_INT, 0,
1858 PKT_END);
1859 do { crReturnV; } while (!ispkt);
1860 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1861 bombout(("Protocol confusion"));
1862 crReturnV;
1863 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1864 logevent("X11 forwarding refused");
1865 } else {
1866 logevent("X11 forwarding enabled");
1867 ssh_X11_fwd_enabled = TRUE;
1868 }
1869 }
1870
fef97f43 1871 if (!cfg.nopty) {
e5574168 1872 send_packet(SSH1_CMSG_REQUEST_PTY,
fb09bf1c 1873 PKT_STR, cfg.termtype,
1874 PKT_INT, rows, PKT_INT, cols,
1875 PKT_INT, 0, PKT_INT, 0,
1876 PKT_CHAR, 0,
1877 PKT_END);
fef97f43 1878 ssh_state = SSH_STATE_INTERMED;
1879 do { crReturnV; } while (!ispkt);
e5574168 1880 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
8d5de777 1881 bombout(("Protocol confusion"));
1882 crReturnV;
e5574168 1883 } else if (pktin.type == SSH1_SMSG_FAILURE) {
fef97f43 1884 c_write("Server refused to allocate pty\r\n", 32);
0965bee0 1885 ssh_editing = ssh_echoing = 1;
fef97f43 1886 }
c5e9c988 1887 logevent("Allocated pty");
0965bee0 1888 } else {
1889 ssh_editing = ssh_echoing = 1;
374330e2 1890 }
1891
4ba9b64b 1892 if (cfg.compression) {
1893 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
1894 do { crReturnV; } while (!ispkt);
1895 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1896 bombout(("Protocol confusion"));
1897 crReturnV;
1898 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1899 c_write("Server refused to compress\r\n", 32);
1900 }
1901 logevent("Started compression");
1902 ssh1_compressing = TRUE;
1903 zlib_compress_init();
1904 zlib_decompress_init();
1905 }
1906
6abbf9e3 1907 if (*cfg.remote_cmd)
1908 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1909 else
1910 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
c5e9c988 1911 logevent("Started session");
374330e2 1912
1913 ssh_state = SSH_STATE_SESSION;
1914 if (size_needed)
1915 ssh_size();
3687d221 1916 if (eof_needed)
1917 ssh_special(TS_EOF);
374330e2 1918
0965bee0 1919 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
8ccc75b0 1920 ssh_send_ok = 1;
dacbd0e8 1921 ssh_channels = newtree234(ssh_channelcmp);
374330e2 1922 while (1) {
1923 crReturnV;
1924 if (ispkt) {
e5574168 1925 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1926 pktin.type == SSH1_SMSG_STDERR_DATA) {
fb09bf1c 1927 long len = GET_32BIT(pktin.body);
fe50e814 1928 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
1929 pktin.body+4, len);
e5574168 1930 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
21248260 1931 ssh_state = SSH_STATE_CLOSED;
c5e9c988 1932 logevent("Received disconnect request");
3257deae 1933 crReturnV;
9c964e85 1934 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
1935 /* Remote side is trying to open a channel to talk to our
1936 * X-Server. Give them back a local channel number. */
1937 unsigned i;
1938 struct ssh_channel *c, *d;
1939 enum234 e;
1940
1941 logevent("Received X11 connect request");
1942 /* Refuse if X11 forwarding is disabled. */
1943 if (!ssh_X11_fwd_enabled) {
1944 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1945 PKT_INT, GET_32BIT(pktin.body),
1946 PKT_END);
1947 logevent("Rejected X11 connect request");
1948 } else {
9c964e85 1949 c = smalloc(sizeof(struct ssh_channel));
1950
0c6c9a70 1951 if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
9c964e85 1952 logevent("opening X11 forward connection failed");
1953 sfree(c);
1954 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1955 PKT_INT, GET_32BIT(pktin.body),
1956 PKT_END);
1957 } else {
1958 logevent("opening X11 forward connection succeeded");
1959 for (i=1, d = first234(ssh_channels, &e); d; d = next234(&e)) {
783415f8 1960 if (d->localid > i)
1961 break; /* found a free number */
1962 i = d->localid + 1;
9c964e85 1963 }
1964 c->remoteid = GET_32BIT(pktin.body);
1965 c->localid = i;
1966 c->closes = 0;
783415f8 1967 c->type = CHAN_X11; /* identify channel type */
9c964e85 1968 add234(ssh_channels, c);
1969 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1970 PKT_INT, c->remoteid, PKT_INT, c->localid,
1971 PKT_END);
1972 logevent("Opened X11 forward channel");
1973 }
1974 }
dacbd0e8 1975 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
1976 /* Remote side is trying to open a channel to talk to our
1977 * agent. Give them back a local channel number. */
db7d555c 1978 unsigned i;
dacbd0e8 1979 struct ssh_channel *c;
1980 enum234 e;
db7d555c 1981
1982 /* Refuse if agent forwarding is disabled. */
1983 if (!ssh_agentfwd_enabled) {
1984 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1985 PKT_INT, GET_32BIT(pktin.body),
1986 PKT_END);
1987 } else {
1988 i = 1;
1989 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
1990 if (c->localid > i)
1991 break; /* found a free number */
1992 i = c->localid + 1;
1993 }
dcbde236 1994 c = smalloc(sizeof(struct ssh_channel));
db7d555c 1995 c->remoteid = GET_32BIT(pktin.body);
1996 c->localid = i;
1997 c->closes = 0;
783415f8 1998 c->type = CHAN_AGENT; /* identify channel type */
db7d555c 1999 c->u.a.lensofar = 0;
2000 add234(ssh_channels, c);
2001 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2002 PKT_INT, c->remoteid, PKT_INT, c->localid,
2003 PKT_END);
2004 }
2005 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2006 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
dacbd0e8 2007 /* Remote side closes a channel. */
d211621f 2008 unsigned i = GET_32BIT(pktin.body);
dacbd0e8 2009 struct ssh_channel *c;
2010 c = find234(ssh_channels, &i, ssh_channelfind);
2011 if (c) {
2012 int closetype;
2013 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2014 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
783415f8 2015 if ((c->closes == 0) && (c->type == CHAN_X11)) {
9c964e85 2016 logevent("X11 connection closed");
2017 assert(c->u.x11.s != NULL);
2018 x11_close(c->u.x11.s);
2019 c->u.x11.s = NULL;
2020 }
dacbd0e8 2021 c->closes |= closetype;
2022 if (c->closes == 3) {
2023 del234(ssh_channels, c);
dcbde236 2024 sfree(c);
dacbd0e8 2025 }
2026 }
2027 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2028 /* Data sent down one of our channels. */
2029 int i = GET_32BIT(pktin.body);
2030 int len = GET_32BIT(pktin.body+4);
2031 unsigned char *p = pktin.body+8;
2032 struct ssh_channel *c;
2033 c = find234(ssh_channels, &i, ssh_channelfind);
2034 if (c) {
2035 switch(c->type) {
783415f8 2036 case CHAN_X11:
9c964e85 2037 x11_send(c->u.x11.s, p, len);
2038 break;
783415f8 2039 case CHAN_AGENT:
dacbd0e8 2040 /* Data for an agent message. Buffer it. */
2041 while (len > 0) {
2042 if (c->u.a.lensofar < 4) {
2043 int l = min(4 - c->u.a.lensofar, len);
2044 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
2045 p += l; len -= l; c->u.a.lensofar += l;
2046 }
2047 if (c->u.a.lensofar == 4) {
2048 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
dcbde236 2049 c->u.a.message = smalloc(c->u.a.totallen);
dacbd0e8 2050 memcpy(c->u.a.message, c->u.a.msglen, 4);
2051 }
2052 if (c->u.a.lensofar >= 4 && len > 0) {
2053 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
2054 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
2055 p += l; len -= l; c->u.a.lensofar += l;
2056 }
2057 if (c->u.a.lensofar == c->u.a.totallen) {
2058 void *reply, *sentreply;
2059 int replylen;
2060 agent_query(c->u.a.message, c->u.a.totallen,
2061 &reply, &replylen);
2062 if (reply)
2063 sentreply = reply;
2064 else {
2065 /* Fake SSH_AGENT_FAILURE. */
2066 sentreply = "\0\0\0\1\5";
2067 replylen = 5;
2068 }
2069 send_packet(SSH1_MSG_CHANNEL_DATA,
2070 PKT_INT, c->remoteid,
2071 PKT_INT, replylen,
2072 PKT_DATA, sentreply, replylen,
2073 PKT_END);
2074 if (reply)
dcbde236 2075 sfree(reply);
2076 sfree(c->u.a.message);
dacbd0e8 2077 c->u.a.lensofar = 0;
2078 }
2079 }
2080 break;
2081 }
2082 }
e5574168 2083 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
972a41c8 2084 /* may be from EXEC_SHELL on some servers */
e5574168 2085 } else if (pktin.type == SSH1_SMSG_FAILURE) {
972a41c8 2086 /* may be from EXEC_SHELL on some servers
374330e2 2087 * if no pty is available or in other odd cases. Ignore */
e5574168 2088 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2089 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
374330e2 2090 } else {
8d5de777 2091 bombout(("Strange packet received: type %d", pktin.type));
2092 crReturnV;
374330e2 2093 }
2094 } else {
8df7a775 2095 while (inlen > 0) {
2096 int len = min(inlen, 512);
2097 send_packet(SSH1_CMSG_STDIN_DATA,
2098 PKT_INT, len, PKT_DATA, in, len, PKT_END);
2099 in += len;
2100 inlen -= len;
2101 }
374330e2 2102 }
2103 }
2104
2105 crFinishV;
2106}
2107
2108/*
e5574168 2109 * Utility routine for decoding comma-separated strings in KEXINIT.
2110 */
75cab814 2111static int in_commasep_string(char *needle, char *haystack, int haylen) {
e5574168 2112 int needlen = strlen(needle);
2113 while (1) {
2114 /*
2115 * Is it at the start of the string?
2116 */
2117 if (haylen >= needlen && /* haystack is long enough */
2118 !memcmp(needle, haystack, needlen) && /* initial match */
2119 (haylen == needlen || haystack[needlen] == ',')
2120 /* either , or EOS follows */
2121 )
2122 return 1;
2123 /*
2124 * If not, search for the next comma and resume after that.
2125 * If no comma found, terminate.
2126 */
2127 while (haylen > 0 && *haystack != ',')
2128 haylen--, haystack++;
2129 if (haylen == 0)
2130 return 0;
2131 haylen--, haystack++; /* skip over comma itself */
2132 }
2133}
2134
2135/*
d39f364a 2136 * SSH2 key creation method.
2137 */
5e0d7cb8 2138static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr, char *keyspace) {
d39f364a 2139 SHA_State s;
2140 /* First 20 bytes. */
2141 SHA_Init(&s);
2142 sha_mpint(&s, K);
2143 SHA_Bytes(&s, H, 20);
2144 SHA_Bytes(&s, &chr, 1);
5e0d7cb8 2145 SHA_Bytes(&s, sessid, 20);
d39f364a 2146 SHA_Final(&s, keyspace);
2147 /* Next 20 bytes. */
2148 SHA_Init(&s);
2149 sha_mpint(&s, K);
2150 SHA_Bytes(&s, H, 20);
2151 SHA_Bytes(&s, keyspace, 20);
2152 SHA_Final(&s, keyspace+20);
2153}
2154
2155/*
7cca0d81 2156 * Handle the SSH2 transport layer.
e5574168 2157 */
7cca0d81 2158static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
e5574168 2159{
2160 static int i, len;
2161 static char *str;
2162 static Bignum e, f, K;
7591b9ff 2163 static const struct ssh_mac **maclist;
8b2715b2 2164 static int nmacs;
57476f6b 2165 static const struct ssh_cipher *cscipher_tobe = NULL;
2166 static const struct ssh_cipher *sccipher_tobe = NULL;
2167 static const struct ssh_mac *csmac_tobe = NULL;
2168 static const struct ssh_mac *scmac_tobe = NULL;
2169 static const struct ssh_compress *cscomp_tobe = NULL;
2170 static const struct ssh_compress *sccomp_tobe = NULL;
d5859615 2171 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
e5574168 2172 static int hostkeylen, siglen;
e055a386 2173 static void *hkey; /* actual host key */
e5574168 2174 static unsigned char exchange_hash[20];
5e0d7cb8 2175 static unsigned char first_exchange_hash[20];
d39f364a 2176 static unsigned char keyspace[40];
57476f6b 2177 static const struct ssh_cipher *preferred_cipher;
4ba9b64b 2178 static const struct ssh_compress *preferred_comp;
0db56f73 2179 static int first_kex;
e5574168 2180
2181 crBegin;
7cca0d81 2182 random_init();
0db56f73 2183 first_kex = 1;
e5574168 2184
5e8358ad 2185 /*
4ba9b64b 2186 * Set up the preferred cipher and compression.
5e8358ad 2187 */
2188 if (cfg.cipher == CIPHER_BLOWFISH) {
57476f6b 2189 preferred_cipher = &ssh_blowfish_ssh2;
5e8358ad 2190 } else if (cfg.cipher == CIPHER_DES) {
2191 logevent("Single DES not supported in SSH2; using 3DES");
57476f6b 2192 preferred_cipher = &ssh_3des_ssh2;
5e8358ad 2193 } else if (cfg.cipher == CIPHER_3DES) {
57476f6b 2194 preferred_cipher = &ssh_3des_ssh2;
5e8358ad 2195 } else {
2196 /* Shouldn't happen, but we do want to initialise to _something_. */
57476f6b 2197 preferred_cipher = &ssh_3des_ssh2;
5e8358ad 2198 }
4ba9b64b 2199 if (cfg.compression)
2200 preferred_comp = &ssh_zlib;
2201 else
2202 preferred_comp = &ssh_comp_none;
5e8358ad 2203
7591b9ff 2204 /*
2205 * Be prepared to work around the buggy MAC problem.
2206 */
2207 if (cfg.buggymac)
8b2715b2 2208 maclist = buggymacs, nmacs = lenof(buggymacs);
7591b9ff 2209 else
8b2715b2 2210 maclist = macs, nmacs = lenof(macs);
7591b9ff 2211
7cca0d81 2212 begin_key_exchange:
e5574168 2213 /*
2214 * Construct and send our key exchange packet.
2215 */
2216 ssh2_pkt_init(SSH2_MSG_KEXINIT);
2217 for (i = 0; i < 16; i++)
2218 ssh2_pkt_addbyte((unsigned char)random_byte());
2219 /* List key exchange algorithms. */
2220 ssh2_pkt_addstring_start();
2221 for (i = 0; i < lenof(kex_algs); i++) {
2222 ssh2_pkt_addstring_str(kex_algs[i]->name);
2223 if (i < lenof(kex_algs)-1)
2224 ssh2_pkt_addstring_str(",");
2225 }
2226 /* List server host key algorithms. */
2227 ssh2_pkt_addstring_start();
2228 for (i = 0; i < lenof(hostkey_algs); i++) {
2229 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
2230 if (i < lenof(hostkey_algs)-1)
2231 ssh2_pkt_addstring_str(",");
2232 }
2233 /* List client->server encryption algorithms. */
2234 ssh2_pkt_addstring_start();
729e54b4 2235 for (i = 0; i < lenof(ciphers)+1; i++) {
2236 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
57476f6b 2237 ssh2_pkt_addstring_str(c->name);
729e54b4 2238 if (i < lenof(ciphers))
e5574168 2239 ssh2_pkt_addstring_str(",");
2240 }
2241 /* List server->client encryption algorithms. */
2242 ssh2_pkt_addstring_start();
729e54b4 2243 for (i = 0; i < lenof(ciphers)+1; i++) {
2244 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
57476f6b 2245 ssh2_pkt_addstring_str(c->name);
729e54b4 2246 if (i < lenof(ciphers))
e5574168 2247 ssh2_pkt_addstring_str(",");
2248 }
2249 /* List client->server MAC algorithms. */
2250 ssh2_pkt_addstring_start();
8b2715b2 2251 for (i = 0; i < nmacs; i++) {
7591b9ff 2252 ssh2_pkt_addstring_str(maclist[i]->name);
8b2715b2 2253 if (i < nmacs-1)
e5574168 2254 ssh2_pkt_addstring_str(",");
2255 }
2256 /* List server->client MAC algorithms. */
2257 ssh2_pkt_addstring_start();
8b2715b2 2258 for (i = 0; i < nmacs; i++) {
7591b9ff 2259 ssh2_pkt_addstring_str(maclist[i]->name);
8b2715b2 2260 if (i < nmacs-1)
e5574168 2261 ssh2_pkt_addstring_str(",");
2262 }
2263 /* List client->server compression algorithms. */
2264 ssh2_pkt_addstring_start();
4ba9b64b 2265 for (i = 0; i < lenof(compressions)+1; i++) {
2266 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2267 ssh2_pkt_addstring_str(c->name);
2268 if (i < lenof(compressions))
e5574168 2269 ssh2_pkt_addstring_str(",");
2270 }
2271 /* List server->client compression algorithms. */
2272 ssh2_pkt_addstring_start();
4ba9b64b 2273 for (i = 0; i < lenof(compressions)+1; i++) {
2274 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2275 ssh2_pkt_addstring_str(c->name);
2276 if (i < lenof(compressions))
e5574168 2277 ssh2_pkt_addstring_str(",");
2278 }
2279 /* List client->server languages. Empty list. */
2280 ssh2_pkt_addstring_start();
2281 /* List server->client languages. Empty list. */
2282 ssh2_pkt_addstring_start();
2283 /* First KEX packet does _not_ follow, because we're not that brave. */
2284 ssh2_pkt_addbool(FALSE);
2285 /* Reserved. */
2286 ssh2_pkt_adduint32(0);
0db56f73 2287
2288 exhash = exhashbase;
e5574168 2289 sha_string(&exhash, pktout.data+5, pktout.length-5);
0db56f73 2290
e5574168 2291 ssh2_pkt_send();
2292
2293 if (!ispkt) crWaitUntil(ispkt);
2294 sha_string(&exhash, pktin.data+5, pktin.length-5);
2295
2296 /*
2297 * Now examine the other side's KEXINIT to see what we're up
2298 * to.
2299 */
7cca0d81 2300 if (pktin.type != SSH2_MSG_KEXINIT) {
8d5de777 2301 bombout(("expected key exchange packet from server"));
2302 crReturn(0);
7cca0d81 2303 }
e5574168 2304 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
2305 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
2306 pktin.savedpos += 16; /* skip garbage cookie */
2307 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
2308 for (i = 0; i < lenof(kex_algs); i++) {
2309 if (in_commasep_string(kex_algs[i]->name, str, len)) {
2310 kex = kex_algs[i];
2311 break;
2312 }
2313 }
2314 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
2315 for (i = 0; i < lenof(hostkey_algs); i++) {
2316 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
2317 hostkey = hostkey_algs[i];
2318 break;
2319 }
2320 }
2321 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
729e54b4 2322 for (i = 0; i < lenof(ciphers)+1; i++) {
2323 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
57476f6b 2324 if (in_commasep_string(c->name, str, len)) {
729e54b4 2325 cscipher_tobe = c;
e5574168 2326 break;
2327 }
2328 }
2329 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
729e54b4 2330 for (i = 0; i < lenof(ciphers)+1; i++) {
2331 const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
57476f6b 2332 if (in_commasep_string(c->name, str, len)) {
729e54b4 2333 sccipher_tobe = c;
e5574168 2334 break;
2335 }
2336 }
2337 ssh2_pkt_getstring(&str, &len); /* client->server mac */
8b2715b2 2338 for (i = 0; i < nmacs; i++) {
7591b9ff 2339 if (in_commasep_string(maclist[i]->name, str, len)) {
2340 csmac_tobe = maclist[i];
e5574168 2341 break;
2342 }
2343 }
2344 ssh2_pkt_getstring(&str, &len); /* server->client mac */
8b2715b2 2345 for (i = 0; i < nmacs; i++) {
7591b9ff 2346 if (in_commasep_string(maclist[i]->name, str, len)) {
2347 scmac_tobe = maclist[i];
e5574168 2348 break;
2349 }
2350 }
2351 ssh2_pkt_getstring(&str, &len); /* client->server compression */
4ba9b64b 2352 for (i = 0; i < lenof(compressions)+1; i++) {
2353 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2354 if (in_commasep_string(c->name, str, len)) {
2355 cscomp_tobe = c;
e5574168 2356 break;
2357 }
2358 }
2359 ssh2_pkt_getstring(&str, &len); /* server->client compression */
4ba9b64b 2360 for (i = 0; i < lenof(compressions)+1; i++) {
2361 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2362 if (in_commasep_string(c->name, str, len)) {
2363 sccomp_tobe = c;
e5574168 2364 break;
2365 }
2366 }
e5574168 2367
2368 /*
2369 * Currently we only support Diffie-Hellman and DSS, so let's
2370 * bomb out if those aren't selected.
2371 */
8d5de777 2372 if (kex != &ssh_diffiehellman || hostkey != &ssh_dss) {
2373 bombout(("internal fault: chaos in SSH 2 transport layer"));
2374 crReturn(0);
2375 }
e5574168 2376
2377 /*
2378 * Now we begin the fun. Generate and send e for Diffie-Hellman.
2379 */
3709bfe9 2380 dh_setup_group1();
2381
e5574168 2382 e = dh_create_e();
e5574168 2383 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
2384 ssh2_pkt_addmp(e);
2385 ssh2_pkt_send();
2386
2387 crWaitUntil(ispkt);
7cca0d81 2388 if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
8d5de777 2389 bombout(("expected key exchange packet from server"));
2390 crReturn(0);
7cca0d81 2391 }
e5574168 2392 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2393 f = ssh2_pkt_getmp();
e5574168 2394 ssh2_pkt_getstring(&sigdata, &siglen);
2395
2396 K = dh_find_K(f);
e5574168 2397
2398 sha_string(&exhash, hostkeydata, hostkeylen);
2399 sha_mpint(&exhash, e);
2400 sha_mpint(&exhash, f);
2401 sha_mpint(&exhash, K);
2402 SHA_Final(&exhash, exchange_hash);
2403
3709bfe9 2404 dh_cleanup();
2405
7cca0d81 2406#if 0
e5574168 2407 debug(("Exchange hash is:\r\n"));
2408 for (i = 0; i < 20; i++)
2409 debug((" %02x", exchange_hash[i]));
2410 debug(("\r\n"));
7cca0d81 2411#endif
2412
e055a386 2413 hkey = hostkey->newkey(hostkeydata, hostkeylen);
2414 if (!hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
8d5de777 2415 bombout(("Server failed host key check"));
2416 crReturn(0);
2417 }
e5574168 2418
2419 /*
7cca0d81 2420 * Expect SSH2_MSG_NEWKEYS from server.
d39f364a 2421 */
7cca0d81 2422 crWaitUntil(ispkt);
8d5de777 2423 if (pktin.type != SSH2_MSG_NEWKEYS) {
2424 bombout(("expected new-keys packet from server"));
2425 crReturn(0);
2426 }
d39f364a 2427
2428 /*
7cca0d81 2429 * Authenticate remote host: verify host key. (We've already
2430 * checked the signature of the exchange hash.)
e5574168 2431 */
e055a386 2432 keystr = hostkey->fmtkey(hkey);
2433 fingerprint = hostkey->fingerprint(hkey);
d4857987 2434 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
2435 keystr, fingerprint);
5e0d7cb8 2436 if (first_kex) { /* don't bother logging this in rekeys */
2437 logevent("Host key fingerprint is:");
2438 logevent(fingerprint);
2439 }
dcbde236 2440 sfree(fingerprint);
2441 sfree(keystr);
e055a386 2442 hostkey->freekey(hkey);
d39f364a 2443
2444 /*
7cca0d81 2445 * Send SSH2_MSG_NEWKEYS.
d39f364a 2446 */
2447 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2448 ssh2_pkt_send();
d39f364a 2449
2450 /*
2451 * Create and initialise session keys.
2452 */
2453 cscipher = cscipher_tobe;
2454 sccipher = sccipher_tobe;
2455 csmac = csmac_tobe;
2456 scmac = scmac_tobe;
2457 cscomp = cscomp_tobe;
2458 sccomp = sccomp_tobe;
4ba9b64b 2459 cscomp->compress_init();
2460 sccomp->decompress_init();
d39f364a 2461 /*
5e0d7cb8 2462 * Set IVs after keys. Here we use the exchange hash from the
2463 * _first_ key exchange.
d39f364a 2464 */
5e0d7cb8 2465 if (first_kex)
2466 memcpy(first_exchange_hash, exchange_hash, sizeof(exchange_hash));
2467 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'C', keyspace);
2468 cscipher->setcskey(keyspace);
2469 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'D', keyspace);
2470 sccipher->setsckey(keyspace);
2471 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'A', keyspace);
2472 cscipher->setcsiv(keyspace);
2473 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'B', keyspace);
2474 sccipher->setsciv(keyspace);
2475 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'E', keyspace);
2476 csmac->setcskey(keyspace);
2477 ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'F', keyspace);
2478 scmac->setsckey(keyspace);
d39f364a 2479
033b4cef 2480 /*
0db56f73 2481 * If this is the first key exchange phase, we must pass the
2482 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2483 * wants to see it but because it will need time to initialise
2484 * itself before it sees an actual packet. In subsequent key
2485 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2486 * it would only confuse the layer above.
2487 */
2488 if (!first_kex) {
2489 crReturn(0);
2490 }
2491 first_kex = 0;
2492
2493 /*
7cca0d81 2494 * Now we're encrypting. Begin returning 1 to the protocol main
2495 * function so that other things can run on top of the
2496 * transport. If we ever see a KEXINIT, we must go back to the
2497 * start.
033b4cef 2498 */
e96adf72 2499 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
7cca0d81 2500 crReturn(1);
e96adf72 2501 }
5e0d7cb8 2502 logevent("Server initiated key re-exchange");
7cca0d81 2503 goto begin_key_exchange;
e5574168 2504
2505 crFinish(1);
2506}
2507
7cca0d81 2508/*
783415f8 2509 * Add data to an SSH2 channel output buffer.
2510 */
2511static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len) {
2512 if (c->v2.outbufsize <
2513 c->v2.outbuflen + len) {
2514 c->v2.outbufsize =
2515 c->v2.outbuflen + len + 1024;
2516 c->v2.outbuffer = srealloc(c->v2.outbuffer,
2517 c->v2.outbufsize);
2518 }
2519 memcpy(c->v2.outbuffer + c->v2.outbuflen,
2520 buf, len);
2521 c->v2.outbuflen += len;
2522}
2523
2524/*
2525 * Attempt to send data on an SSH2 channel.
2526 */
2527static void ssh2_try_send(struct ssh_channel *c) {
2528 while (c->v2.remwindow > 0 &&
2529 c->v2.outbuflen > 0) {
2530 unsigned len = c->v2.remwindow;
2531 if (len > c->v2.outbuflen)
2532 len = c->v2.outbuflen;
2533 if (len > c->v2.remmaxpkt)
2534 len = c->v2.remmaxpkt;
2535 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2536 ssh2_pkt_adduint32(c->remoteid);
2537 ssh2_pkt_addstring_start();
2538 ssh2_pkt_addstring_data(c->v2.outbuffer, len);
2539 ssh2_pkt_send();
2540 c->v2.outbuflen -= len;
2541 memmove(c->v2.outbuffer, c->v2.outbuffer+len,
2542 c->v2.outbuflen);
2543 c->v2.remwindow -= len;
2544 }
2545}
2546
2547/*
7cca0d81 2548 * Handle the SSH2 userauth and connection layers.
2549 */
2550static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2551{
7cca0d81 2552 static unsigned long remote_winsize;
2553 static unsigned long remote_maxpkt;
2554
e5574168 2555 crBegin;
2556
7cca0d81 2557 /*
2558 * Request userauth protocol, and await a response to it.
2559 */
2560 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2561 ssh2_pkt_addstring("ssh-userauth");
2562 ssh2_pkt_send();
2563 crWaitUntilV(ispkt);
8d5de777 2564 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2565 bombout(("Server refused user authentication protocol"));
2566 crReturnV;
2567 }
7cca0d81 2568
2569 /*
2570 * FIXME: currently we support only password authentication.
2571 * (This places us technically in violation of the SSH2 spec.
2572 * We must fix this.)
2573 */
2574 while (1) {
2575 /*
2576 * Get a username and a password.
2577 */
2578 static char username[100];
2579 static char password[100];
2580 static int pos = 0;
2581 static char c;
e5574168 2582
67779be7 2583 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
7cca0d81 2584 c_write("login as: ", 10);
67779be7 2585 ssh_send_ok = 1;
7cca0d81 2586 while (pos >= 0) {
2587 crWaitUntilV(!ispkt);
2588 while (inlen--) switch (c = *in++) {
2589 case 10: case 13:
2590 username[pos] = 0;
2591 pos = -1;
2592 break;
2593 case 8: case 127:
2594 if (pos > 0) {
2595 c_write("\b \b", 3);
2596 pos--;
2597 }
2598 break;
2599 case 21: case 27:
2600 while (pos > 0) {
2601 c_write("\b \b", 3);
2602 pos--;
2603 }
2604 break;
2605 case 3: case 4:
2606 random_save_seed();
2607 exit(0);
2608 break;
2609 default:
2610 if (((c >= ' ' && c <= '~') ||
2611 ((unsigned char)c >= 160)) && pos < 40) {
2612 username[pos++] = c;
2613 c_write(&c, 1);
2614 }
2615 break;
2616 }
2617 }
2618 c_write("\r\n", 2);
2619 username[strcspn(username, "\n\r")] = '\0';
2620 } else {
2621 char stuff[200];
2622 strncpy(username, cfg.username, 99);
2623 username[99] = '\0';
67779be7 2624 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7cca0d81 2625 sprintf(stuff, "Using username \"%s\".\r\n", username);
2626 c_write(stuff, strlen(stuff));
2627 }
2628 }
2629
d8426c54 2630 if (ssh_get_password) {
7cca0d81 2631 char prompt[200];
b585ec46 2632 sprintf(prompt, "%.90s@%.90s's password: ", username, savedhost);
7cca0d81 2633 if (!ssh_get_password(prompt, password, sizeof(password))) {
2634 /*
2635 * get_password failed to get a password (for
2636 * example because one was supplied on the command
2637 * line which has already failed to work).
2638 * Terminate.
2639 */
2640 logevent("No more passwords to try");
2641 ssh_state = SSH_STATE_CLOSED;
2642 crReturnV;
2643 }
2644 } else {
2645 c_write("password: ", 10);
67779be7 2646 ssh_send_ok = 1;
7cca0d81 2647
2648 pos = 0;
2649 while (pos >= 0) {
2650 crWaitUntilV(!ispkt);
2651 while (inlen--) switch (c = *in++) {
2652 case 10: case 13:
2653 password[pos] = 0;
2654 pos = -1;
2655 break;
2656 case 8: case 127:
2657 if (pos > 0)
2658 pos--;
2659 break;
2660 case 21: case 27:
2661 pos = 0;
2662 break;
2663 case 3: case 4:
2664 random_save_seed();
2665 exit(0);
2666 break;
2667 default:
2668 if (((c >= ' ' && c <= '~') ||
2669 ((unsigned char)c >= 160)) && pos < 40)
2670 password[pos++] = c;
2671 break;
2672 }
2673 }
2674 c_write("\r\n", 2);
2675 }
2676
b185170a 2677 /*
2678 * We send the password packet lumped tightly together with
2679 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
2680 * string long enough to make the total length of the two
2681 * packets constant. This should ensure that a passive
2682 * listener doing traffic analyis can't work out the length
2683 * of the password.
2684 *
2685 * For this to work, we need an assumption about the
2686 * maximum length of the password packet. I think 256 is
2687 * pretty conservative. Anyone using a password longer than
2688 * that probably doesn't have much to worry about from
2689 * people who find out how long their password is!
2690 */
7cca0d81 2691 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2692 ssh2_pkt_addstring(username);
2693 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2694 ssh2_pkt_addstring("password");
2695 ssh2_pkt_addbool(FALSE);
2696 ssh2_pkt_addstring(password);
b185170a 2697 ssh2_pkt_defer();
2698 /*
2699 * We'll include a string that's an exact multiple of the
2700 * cipher block size. If the cipher is NULL for some
2701 * reason, we don't do this trick at all because we gain
2702 * nothing by it.
2703 */
2704 if (cscipher) {
2705 int i, j;
2706 ssh2_pkt_init(SSH2_MSG_IGNORE);
2707 ssh2_pkt_addstring_start();
2708 for (i = deferred_len; i <= 256; i += cscipher->blksize) {
2709 for (j = 0; j < cscipher->blksize; j++) {
2710 char c = (char)random_byte();
2711 ssh2_pkt_addstring_data(&c, 1);
2712 }
2713 }
2714 ssh2_pkt_defer();
2715 }
2716 ssh2_pkt_defersend();
7cca0d81 2717
2718 crWaitUntilV(ispkt);
2719 if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
2720 c_write("Access denied\r\n", 15);
2721 logevent("Authentication refused");
2722 } else
2723 break;
2724 }
2725
2726 /*
2727 * Now we're authenticated for the connection protocol. The
2728 * connection protocol will automatically have started at this
2729 * point; there's no need to send SERVICE_REQUEST.
2730 */
2731
2732 /*
2733 * So now create a channel with a session in it.
2734 */
dcbde236 2735 mainchan = smalloc(sizeof(struct ssh_channel));
d211621f 2736 mainchan->localid = 100; /* as good as any */
7cca0d81 2737 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
2738 ssh2_pkt_addstring("session");
d211621f 2739 ssh2_pkt_adduint32(mainchan->localid);
cf6e59d6 2740 ssh2_pkt_adduint32(0x8000UL); /* our window size */
d211621f 2741 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
7cca0d81 2742 ssh2_pkt_send();
2743 crWaitUntilV(ispkt);
2744 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8d5de777 2745 bombout(("Server refused to open a session"));
2746 crReturnV;
7cca0d81 2747 /* FIXME: error data comes back in FAILURE packet */
2748 }
d211621f 2749 if (ssh2_pkt_getuint32() != mainchan->localid) {
8d5de777 2750 bombout(("Server's channel confirmation cited wrong channel"));
2751 crReturnV;
7cca0d81 2752 }
d211621f 2753 mainchan->remoteid = ssh2_pkt_getuint32();
783415f8 2754 mainchan->type = CHAN_MAINSESSION;
2755 mainchan->closes = 0;
2756 mainchan->v2.remwindow = ssh2_pkt_getuint32();
2757 mainchan->v2.remmaxpkt = ssh2_pkt_getuint32();
2758 mainchan->v2.outbuffer = NULL;
2759 mainchan->v2.outbuflen = mainchan->v2.outbufsize = 0;
2760 ssh_channels = newtree234(ssh_channelcmp);
2761 add234(ssh_channels, mainchan);
7cca0d81 2762 logevent("Opened channel for session");
2763
2764 /*
783415f8 2765 * Potentially enable X11 forwarding.
2766 */
2767 if (cfg.x11_forward) {
2768 char proto[20], data[64];
2769 logevent("Requesting X11 forwarding");
2770 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2771 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2772 ssh2_pkt_adduint32(mainchan->remoteid);
2773 ssh2_pkt_addstring("x11-req");
2774 ssh2_pkt_addbool(1); /* want reply */
2775 ssh2_pkt_addbool(0); /* many connections */
2776 ssh2_pkt_addstring(proto);
2777 ssh2_pkt_addstring(data);
2778 ssh2_pkt_adduint32(0); /* screen number */
2779 ssh2_pkt_send();
2780
2781 do {
2782 crWaitUntilV(ispkt);
2783 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2784 unsigned i = ssh2_pkt_getuint32();
2785 struct ssh_channel *c;
2786 c = find234(ssh_channels, &i, ssh_channelfind);
2787 if (!c)
2788 continue; /* nonexistent channel */
2789 c->v2.remwindow += ssh2_pkt_getuint32();
2790 }
2791 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2792
2793 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2794 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2795 bombout(("Server got confused by X11 forwarding request"));
2796 crReturnV;
2797 }
2798 logevent("X11 forwarding refused");
2799 } else {
2800 logevent("X11 forwarding enabled");
2801 ssh_X11_fwd_enabled = TRUE;
2802 }
2803 }
2804
2805 /*
7cca0d81 2806 * Now allocate a pty for the session.
2807 */
67779be7 2808 if (!cfg.nopty) {
2809 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2810 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2811 ssh2_pkt_addstring("pty-req");
2812 ssh2_pkt_addbool(1); /* want reply */
2813 ssh2_pkt_addstring(cfg.termtype);
2814 ssh2_pkt_adduint32(cols);
2815 ssh2_pkt_adduint32(rows);
2816 ssh2_pkt_adduint32(0); /* pixel width */
2817 ssh2_pkt_adduint32(0); /* pixel height */
2818 ssh2_pkt_addstring_start();
2819 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
2820 ssh2_pkt_send();
6e48c3fe 2821 ssh_state = SSH_STATE_INTERMED;
7cca0d81 2822
67779be7 2823 do {
2824 crWaitUntilV(ispkt);
2825 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
783415f8 2826 unsigned i = ssh2_pkt_getuint32();
2827 struct ssh_channel *c;
2828 c = find234(ssh_channels, &i, ssh_channelfind);
2829 if (!c)
2830 continue; /* nonexistent channel */
2831 c->v2.remwindow += ssh2_pkt_getuint32();
67779be7 2832 }
2833 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7cca0d81 2834
67779be7 2835 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2836 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
8d5de777 2837 bombout(("Server got confused by pty request"));
2838 crReturnV;
67779be7 2839 }
2840 c_write("Server refused to allocate pty\r\n", 32);
0965bee0 2841 ssh_editing = ssh_echoing = 1;
67779be7 2842 } else {
2843 logevent("Allocated pty");
7cca0d81 2844 }
0965bee0 2845 } else {
2846 ssh_editing = ssh_echoing = 1;
7cca0d81 2847 }
2848
2849 /*
67779be7 2850 * Start a shell or a remote command.
7cca0d81 2851 */
2852 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
d211621f 2853 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
4a8fc3c4 2854 if (cfg.ssh_subsys) {
2855 ssh2_pkt_addstring("subsystem");
2856 ssh2_pkt_addbool(1); /* want reply */
2857 ssh2_pkt_addstring(cfg.remote_cmd);
2858 } else if (*cfg.remote_cmd) {
67779be7 2859 ssh2_pkt_addstring("exec");
2860 ssh2_pkt_addbool(1); /* want reply */
2861 ssh2_pkt_addstring(cfg.remote_cmd);
2862 } else {
2863 ssh2_pkt_addstring("shell");
2864 ssh2_pkt_addbool(1); /* want reply */
2865 }
7cca0d81 2866 ssh2_pkt_send();
d211621f 2867 do {
7cca0d81 2868 crWaitUntilV(ispkt);
d211621f 2869 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
783415f8 2870 unsigned i = ssh2_pkt_getuint32();
2871 struct ssh_channel *c;
2872 c = find234(ssh_channels, &i, ssh_channelfind);
2873 if (!c)
2874 continue; /* nonexistent channel */
2875 c->v2.remwindow += ssh2_pkt_getuint32();
d211621f 2876 }
7cca0d81 2877 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2878 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2879 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
8d5de777 2880 bombout(("Server got confused by shell/command request"));
2881 crReturnV;
7cca0d81 2882 }
8d5de777 2883 bombout(("Server refused to start a shell/command"));
2884 crReturnV;
7cca0d81 2885 } else {
8d5de777 2886 logevent("Started a shell/command");
7cca0d81 2887 }
2888
6e48c3fe 2889 ssh_state = SSH_STATE_SESSION;
2890 if (size_needed)
2891 ssh_size();
3687d221 2892 if (eof_needed)
2893 ssh_special(TS_EOF);
6e48c3fe 2894
7cca0d81 2895 /*
2896 * Transfer data!
2897 */
0965bee0 2898 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
8ccc75b0 2899 ssh_send_ok = 1;
7cca0d81 2900 while (1) {
d211621f 2901 static int try_send;
e5574168 2902 crReturnV;
d211621f 2903 try_send = FALSE;
7cca0d81 2904 if (ispkt) {
2905 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
2906 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
2907 char *data;
2908 int length;
783415f8 2909 unsigned i = ssh2_pkt_getuint32();
2910 struct ssh_channel *c;
2911 c = find234(ssh_channels, &i, ssh_channelfind);
2912 if (!c)
2913 continue; /* nonexistent channel */
7cca0d81 2914 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
2915 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
2916 continue; /* extended but not stderr */
2917 ssh2_pkt_getstring(&data, &length);
d211621f 2918 if (data) {
783415f8 2919 switch (c->type) {
2920 case CHAN_MAINSESSION:
2921 from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
2922 data, length);
2923 break;
2924 case CHAN_X11:
2925 x11_send(c->u.x11.s, data, length);
2926 break;
2927 }
d211621f 2928 /*
783415f8 2929 * Enlarge the window again at the remote
2930 * side, just in case it ever runs down and
2931 * they fail to send us any more data.
d211621f 2932 */
2933 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
783415f8 2934 ssh2_pkt_adduint32(c->remoteid);
d211621f 2935 ssh2_pkt_adduint32(length);
2936 ssh2_pkt_send();
2937 }
7cca0d81 2938 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
2939 ssh_state = SSH_STATE_CLOSED;
d211621f 2940 logevent("Received disconnect message");
3257deae 2941 crReturnV;
7cca0d81 2942 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2943 continue; /* exit status et al; ignore (FIXME?) */
d211621f 2944 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
783415f8 2945 unsigned i = ssh2_pkt_getuint32();
2946 struct ssh_channel *c;
2947
2948 c = find234(ssh_channels, &i, ssh_channelfind);
2949 if (!c)
2950 continue; /* nonexistent channel */
2951
2952 if (c->type == CHAN_X11) {
2953 /*
2954 * Remote EOF on an X11 channel means we should
2955 * wrap up and close the channel ourselves.
2956 */
2957 x11_close(c->u.x11.s);
2958 sshfwd_close(c);
2959 }
d211621f 2960 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
783415f8 2961 unsigned i = ssh2_pkt_getuint32();
2962 struct ssh_channel *c;
2963 enum234 e;
2964
2965 c = find234(ssh_channels, &i, ssh_channelfind);
2966 if (!c)
2967 continue; /* nonexistent channel */
2968 if (c->closes == 0) {
2969 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2970 ssh2_pkt_adduint32(c->remoteid);
2971 ssh2_pkt_send();
2972 }
2973 /* Do pre-close processing on the channel. */
2974 switch (c->type) {
2975 case CHAN_MAINSESSION:
2976 break; /* nothing to see here, move along */
2977 case CHAN_X11:
2978 break;
2979 }
2980 del234(ssh_channels, c);
2981 sfree(c->v2.outbuffer);
2982 sfree(c);
2983
2984 /*
2985 * See if that was the last channel left open.
2986 */
2987 c = first234(ssh_channels, &e);
2988 if (!c) {
d211621f 2989 logevent("All channels closed. Disconnecting");
2990 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
9005f3ba 2991 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
2992 ssh2_pkt_addstring("All open channels closed");
2993 ssh2_pkt_addstring("en"); /* language tag */
d211621f 2994 ssh2_pkt_send();
cf6e59d6 2995 ssh_state = SSH_STATE_CLOSED;
3257deae 2996 crReturnV;
d211621f 2997 }
2998 continue; /* remote sends close; ignore (FIXME) */
7cca0d81 2999 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
783415f8 3000 unsigned i = ssh2_pkt_getuint32();
3001 struct ssh_channel *c;
3002 c = find234(ssh_channels, &i, ssh_channelfind);
3003 if (!c)
3004 continue; /* nonexistent channel */
3005 mainchan->v2.remwindow += ssh2_pkt_getuint32();
d211621f 3006 try_send = TRUE;
783415f8 3007 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
3008 char *type;
3009 int typelen;
3010 char *error = NULL;
3011 struct ssh_channel *c;
3012 ssh2_pkt_getstring(&type, &typelen);
3013 c = smalloc(sizeof(struct ssh_channel));
3014
3015 if (typelen == 3 && !memcmp(type, "x11", 3)) {
783415f8 3016 if (!ssh_X11_fwd_enabled)
3017 error = "X11 forwarding is not enabled";
0c6c9a70 3018 else if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
783415f8 3019 error = "Unable to open an X11 connection";
3020 } else {
3021 c->type = CHAN_X11;
3022 }
3023 } else {
3024 error = "Unsupported channel type requested";
3025 }
3026
3027 c->remoteid = ssh2_pkt_getuint32();
3028 if (error) {
3029 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
3030 ssh2_pkt_adduint32(c->remoteid);
3031 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
3032 ssh2_pkt_addstring(error);
3033 ssh2_pkt_addstring("en"); /* language tag */
3034 ssh2_pkt_send();
3035 sfree(c);
3036 } else {
3037 struct ssh_channel *d;
3038 unsigned i;
3039 enum234 e;
3040
3041 for (i=1, d = first234(ssh_channels, &e); d;
3042 d = next234(&e)) {
3043 if (d->localid > i)
3044 break; /* found a free number */
3045 i = d->localid + 1;
3046 }
3047 c->localid = i;
3048 c->closes = 0;
3049 c->v2.remwindow = ssh2_pkt_getuint32();
3050 c->v2.remmaxpkt = ssh2_pkt_getuint32();
3051 c->v2.outbuffer = NULL;
3052 c->v2.outbuflen = c->v2.outbufsize = 0;
3053 add234(ssh_channels, c);
3054 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
3055 ssh2_pkt_adduint32(c->remoteid);
3056 ssh2_pkt_adduint32(c->localid);
3057 ssh2_pkt_adduint32(0x8000UL); /* our window size */
3058 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
3059 ssh2_pkt_send();
3060 }
7cca0d81 3061 } else {
8d5de777 3062 bombout(("Strange packet received: type %d", pktin.type));
3063 crReturnV;
7cca0d81 3064 }
3065 } else {
d211621f 3066 /*
3067 * We have spare data. Add it to the channel buffer.
3068 */
783415f8 3069 ssh2_add_channel_data(mainchan, in, inlen);
d211621f 3070 try_send = TRUE;
7cca0d81 3071 }
d211621f 3072 if (try_send) {
783415f8 3073 enum234 e;
3074 struct ssh_channel *c;
d211621f 3075 /*
783415f8 3076 * Try to send data on all channels if we can.
d211621f 3077 */
783415f8 3078 for (c = first234(ssh_channels, &e); c; c = next234(&e))
3079 ssh2_try_send(c);
d211621f 3080 }
e5574168 3081 }
3082
3083 crFinishV;
3084}
3085
3086/*
7cca0d81 3087 * Handle the top-level SSH2 protocol.
3088 */
3089static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
3090{
3091 if (do_ssh2_transport(in, inlen, ispkt) == 0)
3092 return;
3093 do_ssh2_authconn(in, inlen, ispkt);
3094}
3095
3096/*
8df7a775 3097 * Called to set up the connection.
374330e2 3098 *
3099 * Returns an error message, or NULL on success.
374330e2 3100 */
8df7a775 3101static char *ssh_init (char *host, int port, char **realhost) {
fb09bf1c 3102 char *p;
8f203108 3103
3104#ifdef MSCRYPTOAPI
3105 if(crypto_startup() == 0)
3106 return "Microsoft high encryption pack not installed!";
3107#endif
374330e2 3108
8df7a775 3109 ssh_send_ok = 0;
0965bee0 3110 ssh_editing = 0;
3111 ssh_echoing = 0;
8df7a775 3112
fb09bf1c 3113 p = connect_to_host(host, port, realhost);
3114 if (p != NULL)
3115 return p;
374330e2 3116
374330e2 3117 return NULL;
3118}
3119
3120/*
374330e2 3121 * Called to send data down the Telnet connection.
3122 */
3123static void ssh_send (char *buf, int len) {
f78051a1 3124 if (s == NULL || ssh_protocol == NULL)
374330e2 3125 return;
3126
3127 ssh_protocol(buf, len, 0);
3128}
3129
3130/*
6e48c3fe 3131 * Called to set the size of the window from SSH's POV.
374330e2 3132 */
3133static void ssh_size(void) {
3134 switch (ssh_state) {
3135 case SSH_STATE_BEFORE_SIZE:
3687d221 3136 case SSH_STATE_PREPACKET:
21248260 3137 case SSH_STATE_CLOSED:
374330e2 3138 break; /* do nothing */
3139 case SSH_STATE_INTERMED:
3140 size_needed = TRUE; /* buffer for later */
3141 break;
3142 case SSH_STATE_SESSION:
fef97f43 3143 if (!cfg.nopty) {
6e48c3fe 3144 if (ssh_version == 1) {
3145 send_packet(SSH1_CMSG_WINDOW_SIZE,
3146 PKT_INT, rows, PKT_INT, cols,
3147 PKT_INT, 0, PKT_INT, 0, PKT_END);
3148 } else {
3149 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3150 ssh2_pkt_adduint32(mainchan->remoteid);
3151 ssh2_pkt_addstring("window-change");
3152 ssh2_pkt_addbool(0);
3153 ssh2_pkt_adduint32(cols);
3154 ssh2_pkt_adduint32(rows);
3155 ssh2_pkt_adduint32(0);
3156 ssh2_pkt_adduint32(0);
3157 ssh2_pkt_send();
3158 }
fef97f43 3159 }
3687d221 3160 break;
374330e2 3161 }
3162}
3163
3164/*
6abbf9e3 3165 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3166 * can send an EOF and collect resulting output (e.g. `plink
3167 * hostname sort').
374330e2 3168 */
3169static void ssh_special (Telnet_Special code) {
6abbf9e3 3170 if (code == TS_EOF) {
3687d221 3171 if (ssh_state != SSH_STATE_SESSION) {
3172 /*
3173 * Buffer the EOF in case we are pre-SESSION, so we can
3174 * send it as soon as we reach SESSION.
3175 */
3176 if (code == TS_EOF)
3177 eof_needed = TRUE;
3178 return;
3179 }
67779be7 3180 if (ssh_version == 1) {
6abbf9e3 3181 send_packet(SSH1_CMSG_EOF, PKT_END);
3182 } else {
3183 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
d211621f 3184 ssh2_pkt_adduint32(mainchan->remoteid);
6abbf9e3 3185 ssh2_pkt_send();
3186 }
67779be7 3187 logevent("Sent EOF message");
ec55b220 3188 } else if (code == TS_PING) {
3687d221 3189 if (ssh_state == SSH_STATE_CLOSED || ssh_state == SSH_STATE_PREPACKET)
3190 return;
ec55b220 3191 if (ssh_version == 1) {
3192 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
3193 } else {
3194 ssh2_pkt_init(SSH2_MSG_IGNORE);
3195 ssh2_pkt_addstring_start();
3196 ssh2_pkt_send();
3197 }
6abbf9e3 3198 } else {
3199 /* do nothing */
3200 }
374330e2 3201}
3202
8df7a775 3203static Socket ssh_socket(void) { return s; }
8ccc75b0 3204
3205static int ssh_sendok(void) { return ssh_send_ok; }
fb09bf1c 3206
0965bee0 3207static int ssh_ldisc(int option) {
3208 if (option == LD_ECHO) return ssh_echoing;
3209 if (option == LD_EDIT) return ssh_editing;
3210 return FALSE;
3211}
3212
374330e2 3213Backend ssh_backend = {
3214 ssh_init,
374330e2 3215 ssh_send,
3216 ssh_size,
4017be6d 3217 ssh_special,
8ccc75b0 3218 ssh_socket,
97db3be4 3219 ssh_sendok,
0965bee0 3220 ssh_ldisc,
97db3be4 3221 22
374330e2 3222};