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