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