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