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