Modify the new rsa_verify routine. We now also check the integrity of
[u/mdw/putty] / ssh.c
1 #include <windows.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <stdarg.h>
5 #include <assert.h>
6
7 #include "putty.h"
8 #include "tree234.h"
9 #include "ssh.h"
10
11 #ifndef FALSE
12 #define FALSE 0
13 #endif
14 #ifndef TRUE
15 #define TRUE 1
16 #endif
17
18 #define logevent(s) { logevent(s); \
19 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20 fprintf(stderr, "%s\n", s); }
21
22 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
23 (s ? sk_close(s), s = NULL : 0), \
24 connection_fatal msg )
25
26 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
27 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
28 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
29 #define SSH1_CMSG_USER 4 /* 0x4 */
30 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
31 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
32 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
33 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
34 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
35 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
36 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
37 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
38 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
39 #define SSH1_SMSG_FAILURE 15 /* 0xf */
40 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
41 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
42 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
43 #define SSH1_CMSG_EOF 19 /* 0x13 */
44 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
45 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
46 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
47 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
48 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
49 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
50 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
51 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
52 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
53 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
54 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
55 #define SSH1_MSG_IGNORE 32 /* 0x20 */
56 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
57 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
58 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
59 #define SSH1_MSG_DEBUG 36 /* 0x24 */
60 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
61 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
62 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
63 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
64 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
65 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
66 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
67
68 #define SSH1_AUTH_TIS 5 /* 0x5 */
69 #define SSH1_AUTH_CCARD 16 /* 0x10 */
70
71 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
72 /* Mask for protoflags we will echo back to server if seen */
73 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
74
75 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
76 #define SSH2_MSG_IGNORE 2 /* 0x2 */
77 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
78 #define SSH2_MSG_DEBUG 4 /* 0x4 */
79 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
80 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
81 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
82 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
83 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
84 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
85 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
86 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
87 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
88 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
89 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
90 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
91 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
92 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
93 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
94 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
95 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
96 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
97 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
98 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
99 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
100 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
101 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
102 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
103 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
104 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
105 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
106 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
107 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
108 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
109
110 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
111 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
112 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
113 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
114 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
115 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
116 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
117 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
118 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
119 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
120 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
121
122 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
123 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
124 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
125 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
126
127 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
128
129 /*
130 * Various remote-bug flags.
131 */
132 #define BUG_CHOKES_ON_SSH1_IGNORE 1
133 #define BUG_SSH2_HMAC 2
134
135 #define GET_32BIT(cp) \
136 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
137 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
138 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
139 ((unsigned long)(unsigned char)(cp)[3]))
140
141 #define PUT_32BIT(cp, value) { \
142 (cp)[0] = (unsigned char)((value) >> 24); \
143 (cp)[1] = (unsigned char)((value) >> 16); \
144 (cp)[2] = (unsigned char)((value) >> 8); \
145 (cp)[3] = (unsigned char)(value); }
146
147 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
148
149 /* Coroutine mechanics for the sillier bits of the code */
150 #define crBegin1 static int crLine = 0;
151 #define crBegin2 switch(crLine) { case 0:;
152 #define crBegin crBegin1; crBegin2;
153 #define crFinish(z) } crLine = 0; return (z)
154 #define crFinishV } crLine = 0; return
155 #define crReturn(z) \
156 do {\
157 crLine=__LINE__; return (z); case __LINE__:;\
158 } while (0)
159 #define crReturnV \
160 do {\
161 crLine=__LINE__; return; case __LINE__:;\
162 } while (0)
163 #define crStop(z) do{ crLine = 0; return (z); }while(0)
164 #define crStopV do{ crLine = 0; return; }while(0)
165 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
166 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
167
168 extern char *x11_init (Socket *, char *, void *);
169 extern void x11_close (Socket);
170 extern void x11_send (Socket , char *, int);
171 extern void x11_invent_auth(char *, int, char *, int);
172
173 /*
174 * Ciphers for SSH2. We miss out single-DES because it isn't
175 * supported; also 3DES and Blowfish are both done differently from
176 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
177 * endianness and different-sized keys.)
178 */
179 const static struct ssh2_ciphers *ciphers[] = {
180 &ssh2_aes,
181 &ssh2_blowfish,
182 &ssh2_3des,
183 };
184
185 const static struct ssh_kex *kex_algs[] = {
186 &ssh_diffiehellman_gex,
187 &ssh_diffiehellman };
188
189 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
190
191 static void nullmac_key(unsigned char *key) { }
192 static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
193 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
194 const static struct ssh_mac ssh_mac_none = {
195 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
196 };
197 const static struct ssh_mac *macs[] = {
198 &ssh_sha1, &ssh_md5, &ssh_mac_none };
199 const static struct ssh_mac *buggymacs[] = {
200 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none };
201
202 static void ssh_comp_none_init(void) { }
203 static int ssh_comp_none_block(unsigned char *block, int len,
204 unsigned char **outblock, int *outlen) {
205 return 0;
206 }
207 static int ssh_comp_none_disable(void) { return 0; }
208 const static struct ssh_compress ssh_comp_none = {
209 "none",
210 ssh_comp_none_init, ssh_comp_none_block,
211 ssh_comp_none_init, ssh_comp_none_block,
212 ssh_comp_none_disable
213 };
214 extern const struct ssh_compress ssh_zlib;
215 const static struct ssh_compress *compressions[] = {
216 &ssh_zlib, &ssh_comp_none };
217
218 enum { /* channel types */
219 CHAN_MAINSESSION,
220 CHAN_X11,
221 CHAN_AGENT,
222 };
223
224 /*
225 * 2-3-4 tree storing channels.
226 */
227 struct ssh_channel {
228 unsigned remoteid, localid;
229 int type;
230 int closes;
231 struct ssh2_data_channel {
232 unsigned char *outbuffer;
233 unsigned outbuflen, outbufsize;
234 unsigned remwindow, remmaxpkt;
235 } v2;
236 union {
237 struct ssh_agent_channel {
238 unsigned char *message;
239 unsigned char msglen[4];
240 int lensofar, totallen;
241 } a;
242 struct ssh_x11_channel {
243 Socket s;
244 } x11;
245 } u;
246 };
247
248 struct Packet {
249 long length;
250 int type;
251 unsigned char *data;
252 unsigned char *body;
253 long savedpos;
254 long maxlen;
255 };
256
257 static SHA_State exhash, exhashbase;
258
259 static Socket s = NULL;
260
261 static unsigned char session_key[32];
262 static int ssh1_compressing;
263 static int ssh1_remote_protoflags;
264 static int ssh1_local_protoflags;
265 static int ssh_agentfwd_enabled;
266 static int ssh_X11_fwd_enabled;
267 static int ssh_remote_bugs;
268 static const struct ssh_cipher *cipher = NULL;
269 static const struct ssh2_cipher *cscipher = NULL;
270 static const struct ssh2_cipher *sccipher = NULL;
271 static const struct ssh_mac *csmac = NULL;
272 static const struct ssh_mac *scmac = NULL;
273 static const struct ssh_compress *cscomp = NULL;
274 static const struct ssh_compress *sccomp = NULL;
275 static const struct ssh_kex *kex = NULL;
276 static const struct ssh_signkey *hostkey = NULL;
277 static unsigned char ssh2_session_id[20];
278 int (*ssh_get_line)(const char *prompt, char *str, int maxlen,
279 int is_pw) = NULL;
280
281 static char *savedhost;
282 static int savedport;
283 static int ssh_send_ok;
284 static int ssh_echoing, ssh_editing;
285
286 static tree234 *ssh_channels; /* indexed by local id */
287 static struct ssh_channel *mainchan; /* primary session channel */
288
289 static enum {
290 SSH_STATE_PREPACKET,
291 SSH_STATE_BEFORE_SIZE,
292 SSH_STATE_INTERMED,
293 SSH_STATE_SESSION,
294 SSH_STATE_CLOSED
295 } ssh_state = SSH_STATE_PREPACKET;
296
297 static int size_needed = FALSE, eof_needed = FALSE;
298
299 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
300 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
301 static unsigned char *deferred_send_data = NULL;
302 static int deferred_len = 0, deferred_size = 0;
303
304 static int ssh_version;
305 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
306 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
307 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
308 static void ssh_size(void);
309 static void ssh_special (Telnet_Special);
310 static void ssh2_try_send(struct ssh_channel *c);
311 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
312
313 static int (*s_rdpkt)(unsigned char **data, int *datalen);
314
315 static struct rdpkt1_state_tag {
316 long len, pad, biglen, to_read;
317 unsigned long realcrc, gotcrc;
318 unsigned char *p;
319 int i;
320 int chunk;
321 } rdpkt1_state;
322
323 static struct rdpkt2_state_tag {
324 long len, pad, payload, packetlen, maclen;
325 int i;
326 int cipherblk;
327 unsigned long incoming_sequence;
328 } rdpkt2_state;
329
330 static int ssh_channelcmp(void *av, void *bv) {
331 struct ssh_channel *a = (struct ssh_channel *)av;
332 struct ssh_channel *b = (struct ssh_channel *)bv;
333 if (a->localid < b->localid) return -1;
334 if (a->localid > b->localid) return +1;
335 return 0;
336 }
337 static int ssh_channelfind(void *av, void *bv) {
338 unsigned *a = (unsigned *)av;
339 struct ssh_channel *b = (struct ssh_channel *)bv;
340 if (*a < b->localid) return -1;
341 if (*a > b->localid) return +1;
342 return 0;
343 }
344
345 static void c_write (char *buf, int len) {
346 if ((flags & FLAG_STDERR)) {
347 int i;
348 for (i = 0; i < len; i++)
349 if (buf[i] != '\r')
350 fputc(buf[i], stderr);
351 return;
352 }
353 from_backend(1, buf, len);
354 }
355
356 static void c_write_untrusted(char *buf, int len) {
357 int i;
358 for (i = 0; i < len; i++) {
359 if (buf[i] == '\n')
360 c_write("\r\n", 2);
361 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
362 c_write(buf+i, 1);
363 }
364 }
365
366 static void c_write_str (char *buf) {
367 c_write(buf, strlen(buf));
368 }
369
370 /*
371 * Collect incoming data in the incoming packet buffer.
372 * Decipher and verify the packet when it is completely read.
373 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
374 * Update the *data and *datalen variables.
375 * Return the additional nr of bytes needed, or 0 when
376 * a complete packet is available.
377 */
378 static int ssh1_rdpkt(unsigned char **data, int *datalen)
379 {
380 struct rdpkt1_state_tag *st = &rdpkt1_state;
381
382 crBegin;
383
384 next_packet:
385
386 pktin.type = 0;
387 pktin.length = 0;
388
389 for (st->i = st->len = 0; st->i < 4; st->i++) {
390 while ((*datalen) == 0)
391 crReturn(4-st->i);
392 st->len = (st->len << 8) + **data;
393 (*data)++, (*datalen)--;
394 }
395
396 #ifdef FWHACK
397 if (st->len == 0x52656d6f) { /* "Remo"te server has closed ... */
398 st->len = 0x300; /* big enough to carry to end */
399 }
400 #endif
401
402 st->pad = 8 - (st->len % 8);
403 st->biglen = st->len + st->pad;
404 pktin.length = st->len - 5;
405
406 if (pktin.maxlen < st->biglen) {
407 pktin.maxlen = st->biglen;
408 pktin.data = (pktin.data == NULL ? smalloc(st->biglen+APIEXTRA) :
409 srealloc(pktin.data, st->biglen+APIEXTRA));
410 if (!pktin.data)
411 fatalbox("Out of memory");
412 }
413
414 st->to_read = st->biglen;
415 st->p = pktin.data;
416 while (st->to_read > 0) {
417 st->chunk = st->to_read;
418 while ((*datalen) == 0)
419 crReturn(st->to_read);
420 if (st->chunk > (*datalen))
421 st->chunk = (*datalen);
422 memcpy(st->p, *data, st->chunk);
423 *data += st->chunk;
424 *datalen -= st->chunk;
425 st->p += st->chunk;
426 st->to_read -= st->chunk;
427 }
428
429 if (cipher)
430 cipher->decrypt(pktin.data, st->biglen);
431 #if 0
432 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
433 for (st->i = 0; st->i < st->biglen; st->i++)
434 debug((" %02x", (unsigned char)pktin.data[st->i]));
435 debug(("\r\n"));
436 #endif
437
438 st->realcrc = crc32(pktin.data, st->biglen-4);
439 st->gotcrc = GET_32BIT(pktin.data+st->biglen-4);
440 if (st->gotcrc != st->realcrc) {
441 bombout(("Incorrect CRC received on packet"));
442 crReturn(0);
443 }
444
445 pktin.body = pktin.data + st->pad + 1;
446
447 if (ssh1_compressing) {
448 unsigned char *decompblk;
449 int decomplen;
450 #if 0
451 {
452 int i;
453 debug(("Packet payload pre-decompression:\n"));
454 for (i = -1; i < pktin.length; i++)
455 debug((" %02x", (unsigned char)pktin.body[i]));
456 debug(("\r\n"));
457 }
458 #endif
459 zlib_decompress_block(pktin.body-1, pktin.length+1,
460 &decompblk, &decomplen);
461
462 if (pktin.maxlen < st->pad + decomplen) {
463 pktin.maxlen = st->pad + decomplen;
464 pktin.data = srealloc(pktin.data, pktin.maxlen+APIEXTRA);
465 pktin.body = pktin.data + st->pad + 1;
466 if (!pktin.data)
467 fatalbox("Out of memory");
468 }
469
470 memcpy(pktin.body-1, decompblk, decomplen);
471 sfree(decompblk);
472 pktin.length = decomplen-1;
473 #if 0
474 {
475 int i;
476 debug(("Packet payload post-decompression:\n"));
477 for (i = -1; i < pktin.length; i++)
478 debug((" %02x", (unsigned char)pktin.body[i]));
479 debug(("\r\n"));
480 }
481 #endif
482 }
483
484 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
485 pktin.type == SSH1_SMSG_STDERR_DATA ||
486 pktin.type == SSH1_MSG_DEBUG ||
487 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
488 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
489 long strlen = GET_32BIT(pktin.body);
490 if (strlen + 4 != pktin.length) {
491 bombout(("Received data packet with bogus string length"));
492 crReturn(0);
493 }
494 }
495
496 pktin.type = pktin.body[-1];
497
498 if (pktin.type == SSH1_MSG_DEBUG) {
499 /* log debug message */
500 char buf[80];
501 int strlen = GET_32BIT(pktin.body);
502 strcpy(buf, "Remote: ");
503 if (strlen > 70) strlen = 70;
504 memcpy(buf+8, pktin.body+4, strlen);
505 buf[8+strlen] = '\0';
506 logevent(buf);
507 goto next_packet;
508 } else if (pktin.type == SSH1_MSG_IGNORE) {
509 /* do nothing */
510 goto next_packet;
511 }
512
513 crFinish(0);
514 }
515
516 static int ssh2_rdpkt(unsigned char **data, int *datalen)
517 {
518 struct rdpkt2_state_tag *st = &rdpkt2_state;
519
520 crBegin;
521
522 next_packet:
523 pktin.type = 0;
524 pktin.length = 0;
525 if (sccipher)
526 st->cipherblk = sccipher->blksize;
527 else
528 st->cipherblk = 8;
529 if (st->cipherblk < 8)
530 st->cipherblk = 8;
531
532 if (pktin.maxlen < st->cipherblk) {
533 pktin.maxlen = st->cipherblk;
534 pktin.data = (pktin.data == NULL ? smalloc(st->cipherblk+APIEXTRA) :
535 srealloc(pktin.data, st->cipherblk+APIEXTRA));
536 if (!pktin.data)
537 fatalbox("Out of memory");
538 }
539
540 /*
541 * Acquire and decrypt the first block of the packet. This will
542 * contain the length and padding details.
543 */
544 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
545 while ((*datalen) == 0)
546 crReturn(st->cipherblk-st->i);
547 pktin.data[st->i] = *(*data)++;
548 (*datalen)--;
549 }
550 #ifdef FWHACK
551 if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
552 /* FIXME */
553 }
554 #endif
555 if (sccipher)
556 sccipher->decrypt(pktin.data, st->cipherblk);
557
558 /*
559 * Now get the length and padding figures.
560 */
561 st->len = GET_32BIT(pktin.data);
562 st->pad = pktin.data[4];
563
564 /*
565 * This enables us to deduce the payload length.
566 */
567 st->payload = st->len - st->pad - 1;
568
569 pktin.length = st->payload + 5;
570
571 /*
572 * So now we can work out the total packet length.
573 */
574 st->packetlen = st->len + 4;
575 st->maclen = scmac ? scmac->len : 0;
576
577 /*
578 * Adjust memory allocation if packet is too big.
579 */
580 if (pktin.maxlen < st->packetlen+st->maclen) {
581 pktin.maxlen = st->packetlen+st->maclen;
582 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
583 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
584 if (!pktin.data)
585 fatalbox("Out of memory");
586 }
587
588 /*
589 * Read and decrypt the remainder of the packet.
590 */
591 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen; st->i++) {
592 while ((*datalen) == 0)
593 crReturn(st->packetlen + st->maclen - st->i);
594 pktin.data[st->i] = *(*data)++;
595 (*datalen)--;
596 }
597 /* Decrypt everything _except_ the MAC. */
598 if (sccipher)
599 sccipher->decrypt(pktin.data + st->cipherblk,
600 st->packetlen - st->cipherblk);
601
602 #if 0
603 debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
604 for (st->i = 0; st->i < st->packetlen; st->i++)
605 debug((" %02x", (unsigned char)pktin.data[st->i]));
606 debug(("\r\n"));
607 #endif
608
609 /*
610 * Check the MAC.
611 */
612 if (scmac && !scmac->verify(pktin.data, st->len+4, st->incoming_sequence)) {
613 bombout(("Incorrect MAC received on packet"));
614 crReturn(0);
615 }
616 st->incoming_sequence++; /* whether or not we MACed */
617
618 /*
619 * Decompress packet payload.
620 */
621 {
622 unsigned char *newpayload;
623 int newlen;
624 if (sccomp && sccomp->decompress(pktin.data+5, pktin.length-5,
625 &newpayload, &newlen)) {
626 if (pktin.maxlen < newlen+5) {
627 pktin.maxlen = newlen+5;
628 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
629 srealloc(pktin.data, pktin.maxlen+APIEXTRA));
630 if (!pktin.data)
631 fatalbox("Out of memory");
632 }
633 pktin.length = 5 + newlen;
634 memcpy(pktin.data+5, newpayload, newlen);
635 #if 0
636 debug(("Post-decompression payload:\r\n"));
637 for (st->i = 0; st->i < newlen; st->i++)
638 debug((" %02x", (unsigned char)pktin.data[5+st->i]));
639 debug(("\r\n"));
640 #endif
641
642 sfree(newpayload);
643 }
644 }
645
646 pktin.savedpos = 6;
647 pktin.type = pktin.data[5];
648
649 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
650 goto next_packet; /* FIXME: print DEBUG message */
651
652 crFinish(0);
653 }
654
655 static void ssh1_pktout_size(int len) {
656 int pad, biglen;
657
658 len += 5; /* type and CRC */
659 pad = 8 - (len%8);
660 biglen = len + pad;
661
662 pktout.length = len-5;
663 if (pktout.maxlen < biglen) {
664 pktout.maxlen = biglen;
665 #ifdef MSCRYPTOAPI
666 /* Allocate enough buffer space for extra block
667 * for MS CryptEncrypt() */
668 pktout.data = (pktout.data == NULL ? smalloc(biglen+12) :
669 srealloc(pktout.data, biglen+12));
670 #else
671 pktout.data = (pktout.data == NULL ? smalloc(biglen+4) :
672 srealloc(pktout.data, biglen+4));
673 #endif
674 if (!pktout.data)
675 fatalbox("Out of memory");
676 }
677 pktout.body = pktout.data+4+pad+1;
678 }
679
680 static void s_wrpkt_start(int type, int len) {
681 ssh1_pktout_size(len);
682 pktout.type = type;
683 }
684
685 static int s_wrpkt_prepare(void) {
686 int pad, len, biglen, i;
687 unsigned long crc;
688
689 pktout.body[-1] = pktout.type;
690
691 #if 0
692 debug(("Packet payload pre-compression:\n"));
693 for (i = -1; i < pktout.length; i++)
694 debug((" %02x", (unsigned char)pktout.body[i]));
695 debug(("\r\n"));
696 #endif
697
698 if (ssh1_compressing) {
699 unsigned char *compblk;
700 int complen;
701 zlib_compress_block(pktout.body-1, pktout.length+1,
702 &compblk, &complen);
703 ssh1_pktout_size(complen-1);
704 memcpy(pktout.body-1, compblk, complen);
705 sfree(compblk);
706 #if 0
707 debug(("Packet payload post-compression:\n"));
708 for (i = -1; i < pktout.length; i++)
709 debug((" %02x", (unsigned char)pktout.body[i]));
710 debug(("\r\n"));
711 #endif
712 }
713
714 len = pktout.length + 5; /* type and CRC */
715 pad = 8 - (len%8);
716 biglen = len + pad;
717
718 for (i=0; i<pad; i++)
719 pktout.data[i+4] = random_byte();
720 crc = crc32(pktout.data+4, biglen-4);
721 PUT_32BIT(pktout.data+biglen, crc);
722 PUT_32BIT(pktout.data, len);
723
724 #if 0
725 debug(("Sending packet len=%d\r\n", biglen+4));
726 for (i = 0; i < biglen+4; i++)
727 debug((" %02x", (unsigned char)pktout.data[i]));
728 debug(("\r\n"));
729 #endif
730 if (cipher)
731 cipher->encrypt(pktout.data+4, biglen);
732
733 return biglen+4;
734 }
735
736 static void s_wrpkt(void) {
737 int len;
738 len = s_wrpkt_prepare();
739 sk_write(s, pktout.data, len);
740 }
741
742 static void s_wrpkt_defer(void) {
743 int len;
744 len = s_wrpkt_prepare();
745 if (deferred_len + len > deferred_size) {
746 deferred_size = deferred_len + len + 128;
747 deferred_send_data = srealloc(deferred_send_data, deferred_size);
748 }
749 memcpy(deferred_send_data+deferred_len, pktout.data, len);
750 deferred_len += len;
751 }
752
753 /*
754 * Construct a packet with the specified contents.
755 */
756 static void construct_packet(int pkttype, va_list ap1, va_list ap2)
757 {
758 unsigned char *p, *argp, argchar;
759 unsigned long argint;
760 int pktlen, argtype, arglen;
761 Bignum bn;
762
763 pktlen = 0;
764 while ((argtype = va_arg(ap1, int)) != PKT_END) {
765 switch (argtype) {
766 case PKT_INT:
767 (void) va_arg(ap1, int);
768 pktlen += 4;
769 break;
770 case PKT_CHAR:
771 (void) va_arg(ap1, char);
772 pktlen++;
773 break;
774 case PKT_DATA:
775 (void) va_arg(ap1, unsigned char *);
776 arglen = va_arg(ap1, int);
777 pktlen += arglen;
778 break;
779 case PKT_STR:
780 argp = va_arg(ap1, unsigned char *);
781 arglen = strlen(argp);
782 pktlen += 4 + arglen;
783 break;
784 case PKT_BIGNUM:
785 bn = va_arg(ap1, Bignum);
786 pktlen += ssh1_bignum_length(bn);
787 break;
788 default:
789 assert(0);
790 }
791 }
792
793 s_wrpkt_start(pkttype, pktlen);
794 p = pktout.body;
795
796 while ((argtype = va_arg(ap2, int)) != PKT_END) {
797 switch (argtype) {
798 case PKT_INT:
799 argint = va_arg(ap2, int);
800 PUT_32BIT(p, argint);
801 p += 4;
802 break;
803 case PKT_CHAR:
804 argchar = va_arg(ap2, unsigned char);
805 *p = argchar;
806 p++;
807 break;
808 case PKT_DATA:
809 argp = va_arg(ap2, unsigned char *);
810 arglen = va_arg(ap2, int);
811 memcpy(p, argp, arglen);
812 p += arglen;
813 break;
814 case PKT_STR:
815 argp = va_arg(ap2, unsigned char *);
816 arglen = strlen(argp);
817 PUT_32BIT(p, arglen);
818 memcpy(p + 4, argp, arglen);
819 p += 4 + arglen;
820 break;
821 case PKT_BIGNUM:
822 bn = va_arg(ap2, Bignum);
823 p += ssh1_write_bignum(p, bn);
824 break;
825 }
826 }
827 }
828
829 static void send_packet(int pkttype, ...) {
830 va_list ap1, ap2;
831 va_start(ap1, pkttype);
832 va_start(ap2, pkttype);
833 construct_packet(pkttype, ap1, ap2);
834 s_wrpkt();
835 }
836
837 static void defer_packet(int pkttype, ...) {
838 va_list ap1, ap2;
839 va_start(ap1, pkttype);
840 va_start(ap2, pkttype);
841 construct_packet(pkttype, ap1, ap2);
842 s_wrpkt_defer();
843 }
844
845 static int ssh_versioncmp(char *a, char *b) {
846 char *ae, *be;
847 unsigned long av, bv;
848
849 av = strtoul(a, &ae, 10);
850 bv = strtoul(b, &be, 10);
851 if (av != bv) return (av < bv ? -1 : +1);
852 if (*ae == '.') ae++;
853 if (*be == '.') be++;
854 av = strtoul(ae, &ae, 10);
855 bv = strtoul(be, &be, 10);
856 if (av != bv) return (av < bv ? -1 : +1);
857 return 0;
858 }
859
860
861 /*
862 * Utility routines for putting an SSH-protocol `string' and
863 * `uint32' into a SHA state.
864 */
865 #include <stdio.h>
866 static void sha_string(SHA_State *s, void *str, int len) {
867 unsigned char lenblk[4];
868 PUT_32BIT(lenblk, len);
869 SHA_Bytes(s, lenblk, 4);
870 SHA_Bytes(s, str, len);
871 }
872
873 static void sha_uint32(SHA_State *s, unsigned i) {
874 unsigned char intblk[4];
875 PUT_32BIT(intblk, i);
876 SHA_Bytes(s, intblk, 4);
877 }
878
879 /*
880 * SSH2 packet construction functions.
881 */
882 static void ssh2_pkt_ensure(int length) {
883 if (pktout.maxlen < length) {
884 pktout.maxlen = length + 256;
885 pktout.data = (pktout.data == NULL ? smalloc(pktout.maxlen+APIEXTRA) :
886 srealloc(pktout.data, pktout.maxlen+APIEXTRA));
887 if (!pktout.data)
888 fatalbox("Out of memory");
889 }
890 }
891 static void ssh2_pkt_adddata(void *data, int len) {
892 pktout.length += len;
893 ssh2_pkt_ensure(pktout.length);
894 memcpy(pktout.data+pktout.length-len, data, len);
895 }
896 static void ssh2_pkt_addbyte(unsigned char byte) {
897 ssh2_pkt_adddata(&byte, 1);
898 }
899 static void ssh2_pkt_init(int pkt_type) {
900 pktout.length = 5;
901 ssh2_pkt_addbyte((unsigned char)pkt_type);
902 }
903 static void ssh2_pkt_addbool(unsigned char value) {
904 ssh2_pkt_adddata(&value, 1);
905 }
906 static void ssh2_pkt_adduint32(unsigned long value) {
907 unsigned char x[4];
908 PUT_32BIT(x, value);
909 ssh2_pkt_adddata(x, 4);
910 }
911 static void ssh2_pkt_addstring_start(void) {
912 ssh2_pkt_adduint32(0);
913 pktout.savedpos = pktout.length;
914 }
915 static void ssh2_pkt_addstring_str(char *data) {
916 ssh2_pkt_adddata(data, strlen(data));
917 PUT_32BIT(pktout.data + pktout.savedpos - 4,
918 pktout.length - pktout.savedpos);
919 }
920 static void ssh2_pkt_addstring_data(char *data, int len) {
921 ssh2_pkt_adddata(data, len);
922 PUT_32BIT(pktout.data + pktout.savedpos - 4,
923 pktout.length - pktout.savedpos);
924 }
925 static void ssh2_pkt_addstring(char *data) {
926 ssh2_pkt_addstring_start();
927 ssh2_pkt_addstring_str(data);
928 }
929 static char *ssh2_mpint_fmt(Bignum b, int *len) {
930 unsigned char *p;
931 int i, n = (ssh1_bignum_bitcount(b)+7)/8;
932 p = smalloc(n + 1);
933 if (!p)
934 fatalbox("out of memory");
935 p[0] = 0;
936 for (i = 1; i <= n; i++)
937 p[i] = bignum_byte(b, n-i);
938 i = 0;
939 while (i <= n && p[i] == 0 && (p[i+1] & 0x80) == 0)
940 i++;
941 memmove(p, p+i, n+1-i);
942 *len = n+1-i;
943 return p;
944 }
945 static void ssh2_pkt_addmp(Bignum b) {
946 unsigned char *p;
947 int len;
948 p = ssh2_mpint_fmt(b, &len);
949 ssh2_pkt_addstring_start();
950 ssh2_pkt_addstring_data(p, len);
951 sfree(p);
952 }
953
954 /*
955 * Construct an SSH2 final-form packet: compress it, encrypt it,
956 * put the MAC on it. Final packet, ready to be sent, is stored in
957 * pktout.data. Total length is returned.
958 */
959 static int ssh2_pkt_construct(void) {
960 int cipherblk, maclen, padding, i;
961 static unsigned long outgoing_sequence = 0;
962
963 /*
964 * Compress packet payload.
965 */
966 #if 0
967 debug(("Pre-compression payload:\r\n"));
968 for (i = 5; i < pktout.length; i++)
969 debug((" %02x", (unsigned char)pktout.data[i]));
970 debug(("\r\n"));
971 #endif
972 {
973 unsigned char *newpayload;
974 int newlen;
975 if (cscomp && cscomp->compress(pktout.data+5, pktout.length-5,
976 &newpayload, &newlen)) {
977 pktout.length = 5;
978 ssh2_pkt_adddata(newpayload, newlen);
979 sfree(newpayload);
980 }
981 }
982
983 /*
984 * Add padding. At least four bytes, and must also bring total
985 * length (minus MAC) up to a multiple of the block size.
986 */
987 cipherblk = cscipher ? cscipher->blksize : 8; /* block size */
988 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
989 padding = 4;
990 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
991 maclen = csmac ? csmac->len : 0;
992 ssh2_pkt_ensure(pktout.length + padding + maclen);
993 pktout.data[4] = padding;
994 for (i = 0; i < padding; i++)
995 pktout.data[pktout.length + i] = random_byte();
996 PUT_32BIT(pktout.data, pktout.length + padding - 4);
997 if (csmac)
998 csmac->generate(pktout.data, pktout.length + padding,
999 outgoing_sequence);
1000 outgoing_sequence++; /* whether or not we MACed */
1001
1002 #if 0
1003 debug(("Sending packet len=%d\r\n", pktout.length+padding));
1004 for (i = 0; i < pktout.length+padding; i++)
1005 debug((" %02x", (unsigned char)pktout.data[i]));
1006 debug(("\r\n"));
1007 #endif
1008
1009 if (cscipher)
1010 cscipher->encrypt(pktout.data, pktout.length + padding);
1011
1012 /* Ready-to-send packet starts at pktout.data. We return length. */
1013 return pktout.length + padding + maclen;
1014 }
1015
1016 /*
1017 * Construct and send an SSH2 packet immediately.
1018 */
1019 static void ssh2_pkt_send(void) {
1020 int len = ssh2_pkt_construct();
1021 sk_write(s, pktout.data, len);
1022 }
1023
1024 /*
1025 * Construct an SSH2 packet and add it to a deferred data block.
1026 * Useful for sending multiple packets in a single sk_write() call,
1027 * to prevent a traffic-analysing listener from being able to work
1028 * out the length of any particular packet (such as the password
1029 * packet).
1030 *
1031 * Note that because SSH2 sequence-numbers its packets, this can
1032 * NOT be used as an m4-style `defer' allowing packets to be
1033 * constructed in one order and sent in another.
1034 */
1035 static void ssh2_pkt_defer(void) {
1036 int len = ssh2_pkt_construct();
1037 if (deferred_len + len > deferred_size) {
1038 deferred_size = deferred_len + len + 128;
1039 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1040 }
1041 memcpy(deferred_send_data+deferred_len, pktout.data, len);
1042 deferred_len += len;
1043 }
1044
1045 /*
1046 * Send the whole deferred data block constructed by
1047 * ssh2_pkt_defer() or SSH1's defer_packet().
1048 */
1049 static void ssh_pkt_defersend(void) {
1050 sk_write(s, deferred_send_data, deferred_len);
1051 deferred_len = deferred_size = 0;
1052 sfree(deferred_send_data);
1053 deferred_send_data = NULL;
1054 }
1055
1056 #if 0
1057 void bndebug(char *string, Bignum b) {
1058 unsigned char *p;
1059 int i, len;
1060 p = ssh2_mpint_fmt(b, &len);
1061 debug(("%s", string));
1062 for (i = 0; i < len; i++)
1063 debug((" %02x", p[i]));
1064 debug(("\r\n"));
1065 sfree(p);
1066 }
1067 #endif
1068
1069 static void sha_mpint(SHA_State *s, Bignum b) {
1070 unsigned char *p;
1071 int len;
1072 p = ssh2_mpint_fmt(b, &len);
1073 sha_string(s, p, len);
1074 sfree(p);
1075 }
1076
1077 /*
1078 * SSH2 packet decode functions.
1079 */
1080 static unsigned long ssh2_pkt_getuint32(void) {
1081 unsigned long value;
1082 if (pktin.length - pktin.savedpos < 4)
1083 return 0; /* arrgh, no way to decline (FIXME?) */
1084 value = GET_32BIT(pktin.data+pktin.savedpos);
1085 pktin.savedpos += 4;
1086 return value;
1087 }
1088 static int ssh2_pkt_getbool(void) {
1089 unsigned long value;
1090 if (pktin.length - pktin.savedpos < 1)
1091 return 0; /* arrgh, no way to decline (FIXME?) */
1092 value = pktin.data[pktin.savedpos] != 0;
1093 pktin.savedpos++;
1094 return value;
1095 }
1096 static void ssh2_pkt_getstring(char **p, int *length) {
1097 *p = NULL;
1098 if (pktin.length - pktin.savedpos < 4)
1099 return;
1100 *length = GET_32BIT(pktin.data+pktin.savedpos);
1101 pktin.savedpos += 4;
1102 if (pktin.length - pktin.savedpos < *length)
1103 return;
1104 *p = pktin.data+pktin.savedpos;
1105 pktin.savedpos += *length;
1106 }
1107 static Bignum ssh2_pkt_getmp(void) {
1108 char *p;
1109 int length;
1110 Bignum b;
1111
1112 ssh2_pkt_getstring(&p, &length);
1113 if (!p)
1114 return NULL;
1115 if (p[0] & 0x80) {
1116 bombout(("internal error: Can't handle negative mpints"));
1117 return NULL;
1118 }
1119 b = bignum_from_bytes(p, length);
1120 return b;
1121 }
1122
1123 /*
1124 * Examine the remote side's version string and compare it against
1125 * a list of known buggy implementations.
1126 */
1127 static void ssh_detect_bugs(char *vstring) {
1128 char *imp; /* pointer to implementation part */
1129 imp = vstring;
1130 imp += strcspn(imp, "-");
1131 imp += strcspn(imp, "-");
1132
1133 ssh_remote_bugs = 0;
1134
1135 if (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1136 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1137 !strcmp(imp, "1.2.22")) {
1138 /*
1139 * These versions don't support SSH1_MSG_IGNORE, so we have
1140 * to use a different defence against password length
1141 * sniffing.
1142 */
1143 ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1144 logevent("We believe remote version has SSH1 ignore bug");
1145 }
1146
1147 if (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1148 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1149 !strncmp(imp, "2.1 ", 4)) {
1150 /*
1151 * These versions have the HMAC bug.
1152 */
1153 ssh_remote_bugs |= BUG_SSH2_HMAC;
1154 logevent("We believe remote version has SSH2 HMAC bug");
1155 }
1156 }
1157
1158 static int do_ssh_init(unsigned char c) {
1159 static char vslen;
1160 static char version[10];
1161 static char *vstring;
1162 static int vstrsize;
1163 static char *vlog;
1164 static int i;
1165
1166 crBegin;
1167
1168 /* Search for the string "SSH-" in the input. */
1169 i = 0;
1170 while (1) {
1171 static const int transS[] = { 1, 2, 2, 1 };
1172 static const int transH[] = { 0, 0, 3, 0 };
1173 static const int transminus[] = { 0, 0, 0, -1 };
1174 if (c == 'S') i = transS[i];
1175 else if (c == 'H') i = transH[i];
1176 else if (c == '-') i = transminus[i];
1177 else i = 0;
1178 if (i < 0)
1179 break;
1180 crReturn(1); /* get another character */
1181 }
1182
1183 vstring = smalloc(16);
1184 vstrsize = 16;
1185 strcpy(vstring, "SSH-");
1186 vslen = 4;
1187 i = 0;
1188 while (1) {
1189 crReturn(1); /* get another char */
1190 if (vslen >= vstrsize-1) {
1191 vstrsize += 16;
1192 vstring = srealloc(vstring, vstrsize);
1193 }
1194 vstring[vslen++] = c;
1195 if (i >= 0) {
1196 if (c == '-') {
1197 version[i] = '\0';
1198 i = -1;
1199 } else if (i < sizeof(version)-1)
1200 version[i++] = c;
1201 }
1202 else if (c == '\n')
1203 break;
1204 }
1205
1206 ssh_agentfwd_enabled = FALSE;
1207 rdpkt2_state.incoming_sequence = 0;
1208
1209 vstring[vslen] = 0;
1210 vlog = smalloc(20 + vslen);
1211 sprintf(vlog, "Server version: %s", vstring);
1212 ssh_detect_bugs(vstring);
1213 vlog[strcspn(vlog, "\r\n")] = '\0';
1214 logevent(vlog);
1215 sfree(vlog);
1216
1217 /*
1218 * Server version "1.99" means we can choose whether we use v1
1219 * or v2 protocol. Choice is based on cfg.sshprot.
1220 */
1221 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1222 /*
1223 * This is a v2 server. Begin v2 protocol.
1224 */
1225 char verstring[80], vlog[100];
1226 sprintf(verstring, "SSH-2.0-%s", sshver);
1227 SHA_Init(&exhashbase);
1228 /*
1229 * Hash our version string and their version string.
1230 */
1231 sha_string(&exhashbase, verstring, strlen(verstring));
1232 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1233 sprintf(vlog, "We claim version: %s", verstring);
1234 logevent(vlog);
1235 strcat(verstring, "\n");
1236 logevent("Using SSH protocol version 2");
1237 sk_write(s, verstring, strlen(verstring));
1238 ssh_protocol = ssh2_protocol;
1239 ssh_version = 2;
1240 s_rdpkt = ssh2_rdpkt;
1241 } else {
1242 /*
1243 * This is a v1 server. Begin v1 protocol.
1244 */
1245 char verstring[80], vlog[100];
1246 sprintf(verstring, "SSH-%s-%s",
1247 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"),
1248 sshver);
1249 sprintf(vlog, "We claim version: %s", verstring);
1250 logevent(vlog);
1251 strcat(verstring, "\n");
1252 logevent("Using SSH protocol version 1");
1253 sk_write(s, verstring, strlen(verstring));
1254 ssh_protocol = ssh1_protocol;
1255 ssh_version = 1;
1256 s_rdpkt = ssh1_rdpkt;
1257 }
1258 ssh_state = SSH_STATE_BEFORE_SIZE;
1259
1260 sfree(vstring);
1261
1262 crFinish(0);
1263 }
1264
1265 static void ssh_gotdata(unsigned char *data, int datalen)
1266 {
1267 crBegin;
1268
1269 /*
1270 * To begin with, feed the characters one by one to the
1271 * protocol initialisation / selection function do_ssh_init().
1272 * When that returns 0, we're done with the initial greeting
1273 * exchange and can move on to packet discipline.
1274 */
1275 while (1) {
1276 int ret;
1277 if (datalen == 0)
1278 crReturnV; /* more data please */
1279 ret = do_ssh_init(*data);
1280 data++; datalen--;
1281 if (ret == 0)
1282 break;
1283 }
1284
1285 /*
1286 * We emerge from that loop when the initial negotiation is
1287 * over and we have selected an s_rdpkt function. Now pass
1288 * everything to s_rdpkt, and then pass the resulting packets
1289 * to the proper protocol handler.
1290 */
1291 if (datalen == 0)
1292 crReturnV;
1293 while (1) {
1294 while (datalen > 0) {
1295 if ( s_rdpkt(&data, &datalen) == 0 ) {
1296 ssh_protocol(NULL, 0, 1);
1297 if (ssh_state == SSH_STATE_CLOSED) {
1298 return;
1299 }
1300 }
1301 }
1302 crReturnV;
1303 }
1304 crFinishV;
1305 }
1306
1307 static int ssh_closing (Plug plug, char *error_msg, int error_code, int calling_back) {
1308 ssh_state = SSH_STATE_CLOSED;
1309 sk_close(s);
1310 s = NULL;
1311 if (error_msg) {
1312 /* A socket error has occurred. */
1313 connection_fatal (error_msg);
1314 } else {
1315 /* Otherwise, the remote side closed the connection normally. */
1316 }
1317 return 0;
1318 }
1319
1320 static int ssh_receive(Plug plug, int urgent, char *data, int len) {
1321 ssh_gotdata (data, len);
1322 if (ssh_state == SSH_STATE_CLOSED) {
1323 if (s) {
1324 sk_close(s);
1325 s = NULL;
1326 }
1327 return 0;
1328 }
1329 return 1;
1330 }
1331
1332 /*
1333 * Connect to specified host and port.
1334 * Returns an error message, or NULL on success.
1335 * Also places the canonical host name into `realhost'.
1336 */
1337 static char *connect_to_host(char *host, int port, char **realhost)
1338 {
1339 static struct plug_function_table fn_table = {
1340 ssh_closing,
1341 ssh_receive
1342 }, *fn_table_ptr = &fn_table;
1343
1344 SockAddr addr;
1345 char *err;
1346 #ifdef FWHACK
1347 char *FWhost;
1348 int FWport;
1349 #endif
1350
1351 savedhost = smalloc(1+strlen(host));
1352 if (!savedhost)
1353 fatalbox("Out of memory");
1354 strcpy(savedhost, host);
1355
1356 if (port < 0)
1357 port = 22; /* default ssh port */
1358 savedport = port;
1359
1360 #ifdef FWHACK
1361 FWhost = host;
1362 FWport = port;
1363 host = FWSTR;
1364 port = 23;
1365 #endif
1366
1367 /*
1368 * Try to find host.
1369 */
1370 addr = sk_namelookup(host, realhost);
1371 if ( (err = sk_addr_error(addr)) )
1372 return err;
1373
1374 #ifdef FWHACK
1375 *realhost = FWhost;
1376 #endif
1377
1378 /*
1379 * Open socket.
1380 */
1381 s = sk_new(addr, port, 0, 1, &fn_table_ptr);
1382 if ( (err = sk_socket_error(s)) )
1383 return err;
1384
1385 #ifdef FWHACK
1386 sk_write(s, "connect ", 8);
1387 sk_write(s, FWhost, strlen(FWhost));
1388 {
1389 char buf[20];
1390 sprintf(buf, " %d\n", FWport);
1391 sk_write(s, buf, strlen(buf));
1392 }
1393 #endif
1394
1395 return NULL;
1396 }
1397
1398 /*
1399 * Handle the key exchange and user authentication phases.
1400 */
1401 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1402 {
1403 int i, j, len;
1404 unsigned char *rsabuf, *keystr1, *keystr2;
1405 unsigned char cookie[8];
1406 struct RSAKey servkey, hostkey;
1407 struct MD5Context md5c;
1408 static unsigned long supported_ciphers_mask, supported_auths_mask;
1409 static int tried_publickey;
1410 static unsigned char session_id[16];
1411 int cipher_type;
1412 static char username[100];
1413
1414 crBegin;
1415
1416 if (!ispkt) crWaitUntil(ispkt);
1417
1418 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1419 bombout(("Public key packet not received"));
1420 crReturn(0);
1421 }
1422
1423 logevent("Received public keys");
1424
1425 memcpy(cookie, pktin.body, 8);
1426
1427 i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1428 j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1429
1430 /*
1431 * Log the host key fingerprint.
1432 */
1433 {
1434 char logmsg[80];
1435 logevent("Host key fingerprint is:");
1436 strcpy(logmsg, " ");
1437 hostkey.comment = NULL;
1438 rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
1439 &hostkey);
1440 logevent(logmsg);
1441 }
1442
1443 ssh1_remote_protoflags = GET_32BIT(pktin.body+8+i+j);
1444 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1445 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1446
1447 ssh1_local_protoflags = ssh1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
1448 ssh1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
1449
1450 MD5Init(&md5c);
1451 MD5Update(&md5c, keystr2, hostkey.bytes);
1452 MD5Update(&md5c, keystr1, servkey.bytes);
1453 MD5Update(&md5c, pktin.body, 8);
1454 MD5Final(session_id, &md5c);
1455
1456 for (i=0; i<32; i++)
1457 session_key[i] = random_byte();
1458
1459 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1460
1461 rsabuf = smalloc(len);
1462 if (!rsabuf)
1463 fatalbox("Out of memory");
1464
1465 /*
1466 * Verify the host key.
1467 */
1468 {
1469 /*
1470 * First format the key into a string.
1471 */
1472 int len = rsastr_len(&hostkey);
1473 char fingerprint[100];
1474 char *keystr = smalloc(len);
1475 if (!keystr)
1476 fatalbox("Out of memory");
1477 rsastr_fmt(keystr, &hostkey);
1478 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
1479 verify_ssh_host_key(savedhost, savedport, "rsa", keystr, fingerprint);
1480 sfree(keystr);
1481 }
1482
1483 for (i=0; i<32; i++) {
1484 rsabuf[i] = session_key[i];
1485 if (i < 16)
1486 rsabuf[i] ^= session_id[i];
1487 }
1488
1489 if (hostkey.bytes > servkey.bytes) {
1490 rsaencrypt(rsabuf, 32, &servkey);
1491 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1492 } else {
1493 rsaencrypt(rsabuf, 32, &hostkey);
1494 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1495 }
1496
1497 logevent("Encrypted session key");
1498
1499 switch (cfg.cipher) {
1500 case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH; break;
1501 case CIPHER_DES: cipher_type = SSH_CIPHER_DES; break;
1502 case CIPHER_3DES: cipher_type = SSH_CIPHER_3DES; break;
1503 case CIPHER_AES:
1504 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1505 cipher_type = SSH_CIPHER_3DES;
1506 break;
1507 }
1508 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1509 c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
1510 cipher_type = SSH_CIPHER_3DES;
1511 }
1512 switch (cipher_type) {
1513 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1514 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1515 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1516 }
1517
1518 send_packet(SSH1_CMSG_SESSION_KEY,
1519 PKT_CHAR, cipher_type,
1520 PKT_DATA, cookie, 8,
1521 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1522 PKT_DATA, rsabuf, len,
1523 PKT_INT, ssh1_local_protoflags,
1524 PKT_END);
1525
1526 logevent("Trying to enable encryption...");
1527
1528 sfree(rsabuf);
1529
1530 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1531 cipher_type == SSH_CIPHER_DES ? &ssh_des :
1532 &ssh_3des;
1533 cipher->sesskey(session_key);
1534
1535 crWaitUntil(ispkt);
1536
1537 if (pktin.type != SSH1_SMSG_SUCCESS) {
1538 bombout(("Encryption not successfully enabled"));
1539 crReturn(0);
1540 }
1541
1542 logevent("Successfully started encryption");
1543
1544 fflush(stdout);
1545 {
1546 static int pos = 0;
1547 static char c;
1548 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1549 if (ssh_get_line) {
1550 if (!ssh_get_line("login as: ",
1551 username, sizeof(username), FALSE)) {
1552 /*
1553 * get_line failed to get a username.
1554 * Terminate.
1555 */
1556 logevent("No username provided. Abandoning session.");
1557 ssh_state = SSH_STATE_CLOSED;
1558 crReturn(1);
1559 }
1560 } else {
1561 c_write_str("login as: ");
1562 ssh_send_ok = 1;
1563 while (pos >= 0) {
1564 crWaitUntil(!ispkt);
1565 while (inlen--) switch (c = *in++) {
1566 case 10: case 13:
1567 username[pos] = 0;
1568 pos = -1;
1569 break;
1570 case 8: case 127:
1571 if (pos > 0) {
1572 c_write_str("\b \b");
1573 pos--;
1574 }
1575 break;
1576 case 21: case 27:
1577 while (pos > 0) {
1578 c_write_str("\b \b");
1579 pos--;
1580 }
1581 break;
1582 case 3: case 4:
1583 random_save_seed();
1584 exit(0);
1585 break;
1586 default:
1587 if (((c >= ' ' && c <= '~') ||
1588 ((unsigned char)c >= 160)) && pos < 40) {
1589 username[pos++] = c;
1590 c_write(&c, 1);
1591 }
1592 break;
1593 }
1594 }
1595 c_write_str("\r\n");
1596 username[strcspn(username, "\n\r")] = '\0';
1597 }
1598 } else {
1599 strncpy(username, cfg.username, 99);
1600 username[99] = '\0';
1601 }
1602
1603 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1604 {
1605 char userlog[22+sizeof(username)];
1606 sprintf(userlog, "Sent username \"%s\"", username);
1607 logevent(userlog);
1608 if (flags & FLAG_INTERACTIVE &&
1609 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
1610 strcat(userlog, "\r\n");
1611 c_write_str(userlog);
1612 }
1613 }
1614 }
1615
1616 crWaitUntil(ispkt);
1617
1618 tried_publickey = 0;
1619
1620 while (pktin.type == SSH1_SMSG_FAILURE) {
1621 static char password[100];
1622 static char prompt[200];
1623 static int pos;
1624 static char c;
1625 static int pwpkt_type;
1626 /*
1627 * Show password prompt, having first obtained it via a TIS
1628 * or CryptoCard exchange if we're doing TIS or CryptoCard
1629 * authentication.
1630 */
1631 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1632 if (agent_exists()) {
1633 /*
1634 * Attempt RSA authentication using Pageant.
1635 */
1636 static unsigned char request[5], *response, *p;
1637 static int responselen;
1638 static int i, nkeys;
1639 static int authed = FALSE;
1640 void *r;
1641
1642 logevent("Pageant is running. Requesting keys.");
1643
1644 /* Request the keys held by the agent. */
1645 PUT_32BIT(request, 1);
1646 request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
1647 agent_query(request, 5, &r, &responselen);
1648 response = (unsigned char *)r;
1649 if (response && responselen >= 5 &&
1650 response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
1651 p = response + 5;
1652 nkeys = GET_32BIT(p); p += 4;
1653 { char buf[64]; sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
1654 logevent(buf); }
1655 for (i = 0; i < nkeys; i++) {
1656 static struct RSAKey key;
1657 static Bignum challenge;
1658 static char *commentp;
1659 static int commentlen;
1660
1661 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1662 logevent(buf); }
1663 p += 4;
1664 p += ssh1_read_bignum(p, &key.exponent);
1665 p += ssh1_read_bignum(p, &key.modulus);
1666 commentlen = GET_32BIT(p); p += 4;
1667 commentp = p; p += commentlen;
1668 send_packet(SSH1_CMSG_AUTH_RSA,
1669 PKT_BIGNUM, key.modulus, PKT_END);
1670 crWaitUntil(ispkt);
1671 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1672 logevent("Key refused");
1673 continue;
1674 }
1675 logevent("Received RSA challenge");
1676 ssh1_read_bignum(pktin.body, &challenge);
1677 {
1678 char *agentreq, *q, *ret;
1679 int len, retlen;
1680 len = 1 + 4; /* message type, bit count */
1681 len += ssh1_bignum_length(key.exponent);
1682 len += ssh1_bignum_length(key.modulus);
1683 len += ssh1_bignum_length(challenge);
1684 len += 16; /* session id */
1685 len += 4; /* response format */
1686 agentreq = smalloc(4 + len);
1687 PUT_32BIT(agentreq, len);
1688 q = agentreq + 4;
1689 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
1690 PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1691 q += 4;
1692 q += ssh1_write_bignum(q, key.exponent);
1693 q += ssh1_write_bignum(q, key.modulus);
1694 q += ssh1_write_bignum(q, challenge);
1695 memcpy(q, session_id, 16); q += 16;
1696 PUT_32BIT(q, 1); /* response format */
1697 agent_query(agentreq, len+4, &ret, &retlen);
1698 sfree(agentreq);
1699 if (ret) {
1700 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
1701 logevent("Sending Pageant's response");
1702 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1703 PKT_DATA, ret+5, 16, PKT_END);
1704 sfree(ret);
1705 crWaitUntil(ispkt);
1706 if (pktin.type == SSH1_SMSG_SUCCESS) {
1707 logevent("Pageant's response accepted");
1708 if (flags & FLAG_VERBOSE) {
1709 c_write_str("Authenticated using RSA key \"");
1710 c_write(commentp, commentlen);
1711 c_write_str("\" from agent\r\n");
1712 }
1713 authed = TRUE;
1714 } else
1715 logevent("Pageant's response not accepted");
1716 } else {
1717 logevent("Pageant failed to answer challenge");
1718 sfree(ret);
1719 }
1720 } else {
1721 logevent("No reply received from Pageant");
1722 }
1723 }
1724 freebn(key.exponent);
1725 freebn(key.modulus);
1726 freebn(challenge);
1727 if (authed)
1728 break;
1729 }
1730 }
1731 if (authed)
1732 break;
1733 }
1734 if (*cfg.keyfile && !tried_publickey)
1735 pwpkt_type = SSH1_CMSG_AUTH_RSA;
1736
1737 if (pktin.type == SSH1_SMSG_FAILURE &&
1738 cfg.try_tis_auth &&
1739 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1740 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1741 logevent("Requested TIS authentication");
1742 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1743 crWaitUntil(ispkt);
1744 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1745 logevent("TIS authentication declined");
1746 if (flags & FLAG_INTERACTIVE)
1747 c_write_str("TIS authentication refused.\r\n");
1748 } else {
1749 int challengelen = ((pktin.body[0] << 24) |
1750 (pktin.body[1] << 16) |
1751 (pktin.body[2] << 8) |
1752 (pktin.body[3]));
1753 logevent("Received TIS challenge");
1754 if (challengelen > sizeof(prompt)-1)
1755 challengelen = sizeof(prompt)-1; /* prevent overrun */
1756 memcpy(prompt, pktin.body+4, challengelen);
1757 prompt[challengelen] = '\0';
1758 }
1759 }
1760 if (pktin.type == SSH1_SMSG_FAILURE &&
1761 cfg.try_tis_auth &&
1762 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1763 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1764 logevent("Requested CryptoCard authentication");
1765 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1766 crWaitUntil(ispkt);
1767 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1768 logevent("CryptoCard authentication declined");
1769 c_write_str("CryptoCard authentication refused.\r\n");
1770 } else {
1771 int challengelen = ((pktin.body[0] << 24) |
1772 (pktin.body[1] << 16) |
1773 (pktin.body[2] << 8) |
1774 (pktin.body[3]));
1775 logevent("Received CryptoCard challenge");
1776 if (challengelen > sizeof(prompt)-1)
1777 challengelen = sizeof(prompt)-1; /* prevent overrun */
1778 memcpy(prompt, pktin.body+4, challengelen);
1779 strncpy(prompt + challengelen, "\r\nResponse : ",
1780 sizeof(prompt)-challengelen);
1781 prompt[sizeof(prompt)-1] = '\0';
1782 }
1783 }
1784 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1785 sprintf(prompt, "%.90s@%.90s's password: ",
1786 username, savedhost);
1787 }
1788 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1789 char *comment = NULL;
1790 if (flags & FLAG_VERBOSE)
1791 c_write_str("Trying public key authentication.\r\n");
1792 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1793 if (flags & FLAG_VERBOSE)
1794 c_write_str("No passphrase required.\r\n");
1795 goto tryauth;
1796 }
1797 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
1798 sfree(comment);
1799 }
1800
1801 if (ssh_get_line) {
1802 if (!ssh_get_line(prompt, password, sizeof(password), TRUE)) {
1803 /*
1804 * get_line failed to get a password (for example
1805 * because one was supplied on the command line
1806 * which has already failed to work). Terminate.
1807 */
1808 logevent("No more passwords to try");
1809 ssh_state = SSH_STATE_CLOSED;
1810 crReturn(1);
1811 }
1812 } else {
1813 c_write_str(prompt);
1814 pos = 0;
1815 ssh_send_ok = 1;
1816 while (pos >= 0) {
1817 crWaitUntil(!ispkt);
1818 while (inlen--) switch (c = *in++) {
1819 case 10: case 13:
1820 password[pos] = 0;
1821 pos = -1;
1822 break;
1823 case 8: case 127:
1824 if (pos > 0)
1825 pos--;
1826 break;
1827 case 21: case 27:
1828 pos = 0;
1829 break;
1830 case 3: case 4:
1831 random_save_seed();
1832 exit(0);
1833 break;
1834 default:
1835 if (((c >= ' ' && c <= '~') ||
1836 ((unsigned char)c >= 160)) && pos < sizeof(password))
1837 password[pos++] = c;
1838 break;
1839 }
1840 }
1841 c_write_str("\r\n");
1842 }
1843
1844 tryauth:
1845 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1846 /*
1847 * Try public key authentication with the specified
1848 * key file.
1849 */
1850 static struct RSAKey pubkey;
1851 static Bignum challenge, response;
1852 static int i;
1853 static unsigned char buffer[32];
1854
1855 tried_publickey = 1;
1856 i = loadrsakey(cfg.keyfile, &pubkey, password);
1857 if (i == 0) {
1858 c_write_str("Couldn't load public key from ");
1859 c_write_str(cfg.keyfile);
1860 c_write_str(".\r\n");
1861 continue; /* go and try password */
1862 }
1863 if (i == -1) {
1864 c_write_str("Wrong passphrase.\r\n");
1865 tried_publickey = 0;
1866 continue; /* try again */
1867 }
1868
1869 /*
1870 * Send a public key attempt.
1871 */
1872 send_packet(SSH1_CMSG_AUTH_RSA,
1873 PKT_BIGNUM, pubkey.modulus, PKT_END);
1874
1875 crWaitUntil(ispkt);
1876 if (pktin.type == SSH1_SMSG_FAILURE) {
1877 c_write_str("Server refused our public key.\r\n");
1878 continue; /* go and try password */
1879 }
1880 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1881 bombout(("Bizarre response to offer of public key"));
1882 crReturn(0);
1883 }
1884 ssh1_read_bignum(pktin.body, &challenge);
1885 response = rsadecrypt(challenge, &pubkey);
1886 freebn(pubkey.private_exponent); /* burn the evidence */
1887
1888 for (i = 0; i < 32; i++) {
1889 buffer[i] = bignum_byte(response, 31-i);
1890 }
1891
1892 MD5Init(&md5c);
1893 MD5Update(&md5c, buffer, 32);
1894 MD5Update(&md5c, session_id, 16);
1895 MD5Final(buffer, &md5c);
1896
1897 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1898 PKT_DATA, buffer, 16, PKT_END);
1899
1900 crWaitUntil(ispkt);
1901 if (pktin.type == SSH1_SMSG_FAILURE) {
1902 if (flags & FLAG_VERBOSE)
1903 c_write_str("Failed to authenticate with our public key.\r\n");
1904 continue; /* go and try password */
1905 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1906 bombout(("Bizarre response to RSA authentication response"));
1907 crReturn(0);
1908 }
1909
1910 break; /* we're through! */
1911 } else {
1912 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1913 /*
1914 * Defence against traffic analysis: we send a
1915 * whole bunch of packets containing strings of
1916 * different lengths. One of these strings is the
1917 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
1918 * The others are all random data in
1919 * SSH1_MSG_IGNORE packets. This way a passive
1920 * listener can't tell which is the password, and
1921 * hence can't deduce the password length.
1922 *
1923 * Anybody with a password length greater than 16
1924 * bytes is going to have enough entropy in their
1925 * password that a listener won't find it _that_
1926 * much help to know how long it is. So what we'll
1927 * do is:
1928 *
1929 * - if password length < 16, we send 15 packets
1930 * containing string lengths 1 through 15
1931 *
1932 * - otherwise, we let N be the nearest multiple
1933 * of 8 below the password length, and send 8
1934 * packets containing string lengths N through
1935 * N+7. This won't obscure the order of
1936 * magnitude of the password length, but it will
1937 * introduce a bit of extra uncertainty.
1938 *
1939 * A few servers (the old 1.2.18 through 1.2.22)
1940 * can't deal with SSH1_MSG_IGNORE. For these
1941 * servers, we need an alternative defence. We make
1942 * use of the fact that the password is interpreted
1943 * as a C string: so we can append a NUL, then some
1944 * random data.
1945 */
1946 if (ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) {
1947 char string[64];
1948 char *s;
1949 int len;
1950
1951 len = strlen(password);
1952 if (len < sizeof(string)) {
1953 s = string;
1954 strcpy(string, password);
1955 len++; /* cover the zero byte */
1956 while (len < sizeof(string)) {
1957 string[len++] = (char)random_byte();
1958 }
1959 } else {
1960 s = password;
1961 }
1962 send_packet(pwpkt_type, PKT_INT, len,
1963 PKT_DATA, s, len, PKT_END);
1964 } else {
1965 int bottom, top, pwlen, i;
1966 char *randomstr;
1967
1968 pwlen = strlen(password);
1969 if (pwlen < 16) {
1970 bottom = 0; /* zero length passwords are OK! :-) */
1971 top = 15;
1972 } else {
1973 bottom = pwlen &~ 7;
1974 top = bottom + 7;
1975 }
1976
1977 assert(pwlen >= bottom && pwlen <= top);
1978
1979 randomstr = smalloc(top+1);
1980
1981 for (i = bottom; i <= top; i++) {
1982 if (i == pwlen)
1983 defer_packet(pwpkt_type, PKT_STR, password, PKT_END);
1984 else {
1985 for (j = 0; j < i; j++) {
1986 do {
1987 randomstr[j] = random_byte();
1988 } while (randomstr[j] == '\0');
1989 }
1990 randomstr[i] = '\0';
1991 defer_packet(SSH1_MSG_IGNORE,
1992 PKT_STR, randomstr, PKT_END);
1993 }
1994 }
1995 ssh_pkt_defersend();
1996 }
1997 } else {
1998 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1999 }
2000 }
2001 logevent("Sent password");
2002 memset(password, 0, strlen(password));
2003 crWaitUntil(ispkt);
2004 if (pktin.type == SSH1_SMSG_FAILURE) {
2005 if (flags & FLAG_VERBOSE)
2006 c_write_str("Access denied\r\n");
2007 logevent("Authentication refused");
2008 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2009 logevent("Received disconnect request");
2010 ssh_state = SSH_STATE_CLOSED;
2011 crReturn(1);
2012 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2013 bombout(("Strange packet received, type %d", pktin.type));
2014 crReturn(0);
2015 }
2016 }
2017
2018 logevent("Authentication successful");
2019
2020 crFinish(1);
2021 }
2022
2023 void sshfwd_close(struct ssh_channel *c) {
2024 if (c && !c->closes) {
2025 if (ssh_version == 1) {
2026 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END);
2027 } else {
2028 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2029 ssh2_pkt_adduint32(c->remoteid);
2030 ssh2_pkt_send();
2031 }
2032 c->closes = 1;
2033 if (c->type == CHAN_X11) {
2034 c->u.x11.s = NULL;
2035 logevent("X11 connection terminated");
2036 }
2037 }
2038 }
2039
2040 void sshfwd_write(struct ssh_channel *c, char *buf, int len) {
2041 if (ssh_version == 1) {
2042 send_packet(SSH1_MSG_CHANNEL_DATA,
2043 PKT_INT, c->remoteid,
2044 PKT_INT, len,
2045 PKT_DATA, buf, len,
2046 PKT_END);
2047 } else {
2048 ssh2_add_channel_data(c, buf, len);
2049 ssh2_try_send(c);
2050 }
2051 }
2052
2053 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
2054 crBegin;
2055
2056 random_init();
2057
2058 while (!do_ssh1_login(in, inlen, ispkt)) {
2059 crReturnV;
2060 }
2061 if (ssh_state == SSH_STATE_CLOSED)
2062 crReturnV;
2063
2064 if (cfg.agentfwd && agent_exists()) {
2065 logevent("Requesting agent forwarding");
2066 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2067 do { crReturnV; } while (!ispkt);
2068 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2069 bombout(("Protocol confusion"));
2070 crReturnV;
2071 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2072 logevent("Agent forwarding refused");
2073 } else {
2074 logevent("Agent forwarding enabled");
2075 ssh_agentfwd_enabled = TRUE;
2076 }
2077 }
2078
2079 if (cfg.x11_forward) {
2080 char proto[20], data[64];
2081 logevent("Requesting X11 forwarding");
2082 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2083 if (ssh1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
2084 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2085 PKT_STR, proto, PKT_STR, data,
2086 PKT_INT, 0,
2087 PKT_END);
2088 } else {
2089 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2090 PKT_STR, proto, PKT_STR, data,
2091 PKT_END);
2092 }
2093 do { crReturnV; } while (!ispkt);
2094 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2095 bombout(("Protocol confusion"));
2096 crReturnV;
2097 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2098 logevent("X11 forwarding refused");
2099 } else {
2100 logevent("X11 forwarding enabled");
2101 ssh_X11_fwd_enabled = TRUE;
2102 }
2103 }
2104
2105 if (!cfg.nopty) {
2106 send_packet(SSH1_CMSG_REQUEST_PTY,
2107 PKT_STR, cfg.termtype,
2108 PKT_INT, rows, PKT_INT, cols,
2109 PKT_INT, 0, PKT_INT, 0,
2110 PKT_CHAR, 0,
2111 PKT_END);
2112 ssh_state = SSH_STATE_INTERMED;
2113 do { crReturnV; } while (!ispkt);
2114 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2115 bombout(("Protocol confusion"));
2116 crReturnV;
2117 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2118 c_write_str("Server refused to allocate pty\r\n");
2119 ssh_editing = ssh_echoing = 1;
2120 }
2121 logevent("Allocated pty");
2122 } else {
2123 ssh_editing = ssh_echoing = 1;
2124 }
2125
2126 if (cfg.compression) {
2127 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
2128 do { crReturnV; } while (!ispkt);
2129 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2130 bombout(("Protocol confusion"));
2131 crReturnV;
2132 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2133 c_write_str("Server refused to compress\r\n");
2134 }
2135 logevent("Started compression");
2136 ssh1_compressing = TRUE;
2137 zlib_compress_init();
2138 zlib_decompress_init();
2139 }
2140
2141 if (*cfg.remote_cmd_ptr)
2142 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd_ptr, PKT_END);
2143 else
2144 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
2145 logevent("Started session");
2146
2147 ssh_state = SSH_STATE_SESSION;
2148 if (size_needed)
2149 ssh_size();
2150 if (eof_needed)
2151 ssh_special(TS_EOF);
2152
2153 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
2154 ssh_send_ok = 1;
2155 ssh_channels = newtree234(ssh_channelcmp);
2156 while (1) {
2157 crReturnV;
2158 if (ispkt) {
2159 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
2160 pktin.type == SSH1_SMSG_STDERR_DATA) {
2161 long len = GET_32BIT(pktin.body);
2162 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
2163 pktin.body+4, len);
2164 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2165 ssh_state = SSH_STATE_CLOSED;
2166 logevent("Received disconnect request");
2167 crReturnV;
2168 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
2169 /* Remote side is trying to open a channel to talk to our
2170 * X-Server. Give them back a local channel number. */
2171 unsigned i;
2172 struct ssh_channel *c, *d;
2173 enum234 e;
2174
2175 logevent("Received X11 connect request");
2176 /* Refuse if X11 forwarding is disabled. */
2177 if (!ssh_X11_fwd_enabled) {
2178 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2179 PKT_INT, GET_32BIT(pktin.body),
2180 PKT_END);
2181 logevent("Rejected X11 connect request");
2182 } else {
2183 c = smalloc(sizeof(struct ssh_channel));
2184
2185 if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
2186 logevent("opening X11 forward connection failed");
2187 sfree(c);
2188 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2189 PKT_INT, GET_32BIT(pktin.body),
2190 PKT_END);
2191 } else {
2192 logevent("opening X11 forward connection succeeded");
2193 for (i=1, d = first234(ssh_channels, &e); d; d = next234(&e)) {
2194 if (d->localid > i)
2195 break; /* found a free number */
2196 i = d->localid + 1;
2197 }
2198 c->remoteid = GET_32BIT(pktin.body);
2199 c->localid = i;
2200 c->closes = 0;
2201 c->type = CHAN_X11; /* identify channel type */
2202 add234(ssh_channels, c);
2203 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2204 PKT_INT, c->remoteid, PKT_INT, c->localid,
2205 PKT_END);
2206 logevent("Opened X11 forward channel");
2207 }
2208 }
2209 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
2210 /* Remote side is trying to open a channel to talk to our
2211 * agent. Give them back a local channel number. */
2212 unsigned i;
2213 struct ssh_channel *c;
2214 enum234 e;
2215
2216 /* Refuse if agent forwarding is disabled. */
2217 if (!ssh_agentfwd_enabled) {
2218 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2219 PKT_INT, GET_32BIT(pktin.body),
2220 PKT_END);
2221 } else {
2222 i = 1;
2223 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
2224 if (c->localid > i)
2225 break; /* found a free number */
2226 i = c->localid + 1;
2227 }
2228 c = smalloc(sizeof(struct ssh_channel));
2229 c->remoteid = GET_32BIT(pktin.body);
2230 c->localid = i;
2231 c->closes = 0;
2232 c->type = CHAN_AGENT; /* identify channel type */
2233 c->u.a.lensofar = 0;
2234 add234(ssh_channels, c);
2235 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2236 PKT_INT, c->remoteid, PKT_INT, c->localid,
2237 PKT_END);
2238 }
2239 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2240 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
2241 /* Remote side closes a channel. */
2242 unsigned i = GET_32BIT(pktin.body);
2243 struct ssh_channel *c;
2244 c = find234(ssh_channels, &i, ssh_channelfind);
2245 if (c) {
2246 int closetype;
2247 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2248 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
2249 if ((c->closes == 0) && (c->type == CHAN_X11)) {
2250 logevent("X11 connection closed");
2251 assert(c->u.x11.s != NULL);
2252 x11_close(c->u.x11.s);
2253 c->u.x11.s = NULL;
2254 }
2255 c->closes |= closetype;
2256 if (c->closes == 3) {
2257 del234(ssh_channels, c);
2258 sfree(c);
2259 }
2260 }
2261 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2262 /* Data sent down one of our channels. */
2263 int i = GET_32BIT(pktin.body);
2264 int len = GET_32BIT(pktin.body+4);
2265 unsigned char *p = pktin.body+8;
2266 struct ssh_channel *c;
2267 c = find234(ssh_channels, &i, ssh_channelfind);
2268 if (c) {
2269 switch(c->type) {
2270 case CHAN_X11:
2271 x11_send(c->u.x11.s, p, len);
2272 break;
2273 case CHAN_AGENT:
2274 /* Data for an agent message. Buffer it. */
2275 while (len > 0) {
2276 if (c->u.a.lensofar < 4) {
2277 int l = min(4 - c->u.a.lensofar, len);
2278 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
2279 p += l; len -= l; c->u.a.lensofar += l;
2280 }
2281 if (c->u.a.lensofar == 4) {
2282 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
2283 c->u.a.message = smalloc(c->u.a.totallen);
2284 memcpy(c->u.a.message, c->u.a.msglen, 4);
2285 }
2286 if (c->u.a.lensofar >= 4 && len > 0) {
2287 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
2288 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
2289 p += l; len -= l; c->u.a.lensofar += l;
2290 }
2291 if (c->u.a.lensofar == c->u.a.totallen) {
2292 void *reply, *sentreply;
2293 int replylen;
2294 agent_query(c->u.a.message, c->u.a.totallen,
2295 &reply, &replylen);
2296 if (reply)
2297 sentreply = reply;
2298 else {
2299 /* Fake SSH_AGENT_FAILURE. */
2300 sentreply = "\0\0\0\1\5";
2301 replylen = 5;
2302 }
2303 send_packet(SSH1_MSG_CHANNEL_DATA,
2304 PKT_INT, c->remoteid,
2305 PKT_INT, replylen,
2306 PKT_DATA, sentreply, replylen,
2307 PKT_END);
2308 if (reply)
2309 sfree(reply);
2310 sfree(c->u.a.message);
2311 c->u.a.lensofar = 0;
2312 }
2313 }
2314 break;
2315 }
2316 }
2317 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
2318 /* may be from EXEC_SHELL on some servers */
2319 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2320 /* may be from EXEC_SHELL on some servers
2321 * if no pty is available or in other odd cases. Ignore */
2322 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2323 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2324 } else {
2325 bombout(("Strange packet received: type %d", pktin.type));
2326 crReturnV;
2327 }
2328 } else {
2329 while (inlen > 0) {
2330 int len = min(inlen, 512);
2331 send_packet(SSH1_CMSG_STDIN_DATA,
2332 PKT_INT, len, PKT_DATA, in, len, PKT_END);
2333 in += len;
2334 inlen -= len;
2335 }
2336 }
2337 }
2338
2339 crFinishV;
2340 }
2341
2342 /*
2343 * Utility routine for decoding comma-separated strings in KEXINIT.
2344 */
2345 static int in_commasep_string(char *needle, char *haystack, int haylen) {
2346 int needlen = strlen(needle);
2347 while (1) {
2348 /*
2349 * Is it at the start of the string?
2350 */
2351 if (haylen >= needlen && /* haystack is long enough */
2352 !memcmp(needle, haystack, needlen) && /* initial match */
2353 (haylen == needlen || haystack[needlen] == ',')
2354 /* either , or EOS follows */
2355 )
2356 return 1;
2357 /*
2358 * If not, search for the next comma and resume after that.
2359 * If no comma found, terminate.
2360 */
2361 while (haylen > 0 && *haystack != ',')
2362 haylen--, haystack++;
2363 if (haylen == 0)
2364 return 0;
2365 haylen--, haystack++; /* skip over comma itself */
2366 }
2367 }
2368
2369 /*
2370 * SSH2 key creation method.
2371 */
2372 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr, char *keyspace) {
2373 SHA_State s;
2374 /* First 20 bytes. */
2375 SHA_Init(&s);
2376 sha_mpint(&s, K);
2377 SHA_Bytes(&s, H, 20);
2378 SHA_Bytes(&s, &chr, 1);
2379 SHA_Bytes(&s, sessid, 20);
2380 SHA_Final(&s, keyspace);
2381 /* Next 20 bytes. */
2382 SHA_Init(&s);
2383 sha_mpint(&s, K);
2384 SHA_Bytes(&s, H, 20);
2385 SHA_Bytes(&s, keyspace, 20);
2386 SHA_Final(&s, keyspace+20);
2387 }
2388
2389 /*
2390 * Handle the SSH2 transport layer.
2391 */
2392 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
2393 {
2394 static int i, j, len, nbits, pbits;
2395 static char *str;
2396 static Bignum p, g, e, f, K;
2397 static int kex_init_value, kex_reply_value;
2398 static const struct ssh_mac **maclist;
2399 static int nmacs;
2400 static const struct ssh2_cipher *cscipher_tobe = NULL;
2401 static const struct ssh2_cipher *sccipher_tobe = NULL;
2402 static const struct ssh_mac *csmac_tobe = NULL;
2403 static const struct ssh_mac *scmac_tobe = NULL;
2404 static const struct ssh_compress *cscomp_tobe = NULL;
2405 static const struct ssh_compress *sccomp_tobe = NULL;
2406 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
2407 static int hostkeylen, siglen;
2408 static void *hkey; /* actual host key */
2409 static unsigned char exchange_hash[20];
2410 static unsigned char keyspace[40];
2411 static const struct ssh2_ciphers *preferred_cipher;
2412 static const struct ssh_compress *preferred_comp;
2413 static int first_kex;
2414
2415 crBegin;
2416 random_init();
2417 first_kex = 1;
2418
2419 /*
2420 * Set up the preferred cipher and compression.
2421 */
2422 if (cfg.cipher == CIPHER_BLOWFISH) {
2423 preferred_cipher = &ssh2_blowfish;
2424 } else if (cfg.cipher == CIPHER_DES) {
2425 logevent("Single DES not supported in SSH2; using 3DES");
2426 preferred_cipher = &ssh2_3des;
2427 } else if (cfg.cipher == CIPHER_3DES) {
2428 preferred_cipher = &ssh2_3des;
2429 } else if (cfg.cipher == CIPHER_AES) {
2430 preferred_cipher = &ssh2_aes;
2431 } else {
2432 /* Shouldn't happen, but we do want to initialise to _something_. */
2433 preferred_cipher = &ssh2_3des;
2434 }
2435 if (cfg.compression)
2436 preferred_comp = &ssh_zlib;
2437 else
2438 preferred_comp = &ssh_comp_none;
2439
2440 /*
2441 * Be prepared to work around the buggy MAC problem.
2442 */
2443 if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
2444 maclist = buggymacs, nmacs = lenof(buggymacs);
2445 else
2446 maclist = macs, nmacs = lenof(macs);
2447
2448 begin_key_exchange:
2449 /*
2450 * Construct and send our key exchange packet.
2451 */
2452 ssh2_pkt_init(SSH2_MSG_KEXINIT);
2453 for (i = 0; i < 16; i++)
2454 ssh2_pkt_addbyte((unsigned char)random_byte());
2455 /* List key exchange algorithms. */
2456 ssh2_pkt_addstring_start();
2457 for (i = 0; i < lenof(kex_algs); i++) {
2458 ssh2_pkt_addstring_str(kex_algs[i]->name);
2459 if (i < lenof(kex_algs)-1)
2460 ssh2_pkt_addstring_str(",");
2461 }
2462 /* List server host key algorithms. */
2463 ssh2_pkt_addstring_start();
2464 for (i = 0; i < lenof(hostkey_algs); i++) {
2465 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
2466 if (i < lenof(hostkey_algs)-1)
2467 ssh2_pkt_addstring_str(",");
2468 }
2469 /* List client->server encryption algorithms. */
2470 ssh2_pkt_addstring_start();
2471 for (i = 0; i < lenof(ciphers)+1; i++) {
2472 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2473 for (j = 0; j < c->nciphers; j++) {
2474 ssh2_pkt_addstring_str(c->list[j]->name);
2475 if (i < lenof(ciphers) || j < c->nciphers-1)
2476 ssh2_pkt_addstring_str(",");
2477 }
2478 }
2479 /* List server->client encryption algorithms. */
2480 ssh2_pkt_addstring_start();
2481 for (i = 0; i < lenof(ciphers)+1; i++) {
2482 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2483 for (j = 0; j < c->nciphers; j++) {
2484 ssh2_pkt_addstring_str(c->list[j]->name);
2485 if (i < lenof(ciphers) || j < c->nciphers-1)
2486 ssh2_pkt_addstring_str(",");
2487 }
2488 }
2489 /* List client->server MAC algorithms. */
2490 ssh2_pkt_addstring_start();
2491 for (i = 0; i < nmacs; i++) {
2492 ssh2_pkt_addstring_str(maclist[i]->name);
2493 if (i < nmacs-1)
2494 ssh2_pkt_addstring_str(",");
2495 }
2496 /* List server->client MAC algorithms. */
2497 ssh2_pkt_addstring_start();
2498 for (i = 0; i < nmacs; i++) {
2499 ssh2_pkt_addstring_str(maclist[i]->name);
2500 if (i < nmacs-1)
2501 ssh2_pkt_addstring_str(",");
2502 }
2503 /* List client->server compression algorithms. */
2504 ssh2_pkt_addstring_start();
2505 for (i = 0; i < lenof(compressions)+1; i++) {
2506 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2507 ssh2_pkt_addstring_str(c->name);
2508 if (i < lenof(compressions))
2509 ssh2_pkt_addstring_str(",");
2510 }
2511 /* List server->client compression algorithms. */
2512 ssh2_pkt_addstring_start();
2513 for (i = 0; i < lenof(compressions)+1; i++) {
2514 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2515 ssh2_pkt_addstring_str(c->name);
2516 if (i < lenof(compressions))
2517 ssh2_pkt_addstring_str(",");
2518 }
2519 /* List client->server languages. Empty list. */
2520 ssh2_pkt_addstring_start();
2521 /* List server->client languages. Empty list. */
2522 ssh2_pkt_addstring_start();
2523 /* First KEX packet does _not_ follow, because we're not that brave. */
2524 ssh2_pkt_addbool(FALSE);
2525 /* Reserved. */
2526 ssh2_pkt_adduint32(0);
2527
2528 exhash = exhashbase;
2529 sha_string(&exhash, pktout.data+5, pktout.length-5);
2530
2531 ssh2_pkt_send();
2532
2533 if (!ispkt) crWaitUntil(ispkt);
2534 sha_string(&exhash, pktin.data+5, pktin.length-5);
2535
2536 /*
2537 * Now examine the other side's KEXINIT to see what we're up
2538 * to.
2539 */
2540 if (pktin.type != SSH2_MSG_KEXINIT) {
2541 bombout(("expected key exchange packet from server"));
2542 crReturn(0);
2543 }
2544 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
2545 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
2546 pktin.savedpos += 16; /* skip garbage cookie */
2547 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
2548 for (i = 0; i < lenof(kex_algs); i++) {
2549 if (in_commasep_string(kex_algs[i]->name, str, len)) {
2550 kex = kex_algs[i];
2551 break;
2552 }
2553 }
2554 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
2555 for (i = 0; i < lenof(hostkey_algs); i++) {
2556 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
2557 hostkey = hostkey_algs[i];
2558 break;
2559 }
2560 }
2561 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
2562 for (i = 0; i < lenof(ciphers)+1; i++) {
2563 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2564 for (j = 0; j < c->nciphers; j++) {
2565 if (in_commasep_string(c->list[j]->name, str, len)) {
2566 cscipher_tobe = c->list[j];
2567 break;
2568 }
2569 }
2570 if (cscipher_tobe)
2571 break;
2572 }
2573 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
2574 for (i = 0; i < lenof(ciphers)+1; i++) {
2575 const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2576 for (j = 0; j < c->nciphers; j++) {
2577 if (in_commasep_string(c->list[j]->name, str, len)) {
2578 sccipher_tobe = c->list[j];
2579 break;
2580 }
2581 }
2582 if (sccipher_tobe)
2583 break;
2584 }
2585 ssh2_pkt_getstring(&str, &len); /* client->server mac */
2586 for (i = 0; i < nmacs; i++) {
2587 if (in_commasep_string(maclist[i]->name, str, len)) {
2588 csmac_tobe = maclist[i];
2589 break;
2590 }
2591 }
2592 ssh2_pkt_getstring(&str, &len); /* server->client mac */
2593 for (i = 0; i < nmacs; i++) {
2594 if (in_commasep_string(maclist[i]->name, str, len)) {
2595 scmac_tobe = maclist[i];
2596 break;
2597 }
2598 }
2599 ssh2_pkt_getstring(&str, &len); /* client->server compression */
2600 for (i = 0; i < lenof(compressions)+1; i++) {
2601 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2602 if (in_commasep_string(c->name, str, len)) {
2603 cscomp_tobe = c;
2604 break;
2605 }
2606 }
2607 ssh2_pkt_getstring(&str, &len); /* server->client compression */
2608 for (i = 0; i < lenof(compressions)+1; i++) {
2609 const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2610 if (in_commasep_string(c->name, str, len)) {
2611 sccomp_tobe = c;
2612 break;
2613 }
2614 }
2615
2616 /*
2617 * Work out the number of bits of key we will need from the key
2618 * exchange. We start with the maximum key length of either
2619 * cipher...
2620 */
2621 {
2622 int csbits, scbits;
2623
2624 csbits = cscipher_tobe->keylen;
2625 scbits = sccipher_tobe->keylen;
2626 nbits = (csbits > scbits ? csbits : scbits);
2627 }
2628 /* The keys only have 160-bit entropy, since they're based on
2629 * a SHA-1 hash. So cap the key size at 160 bits. */
2630 if (nbits > 160) nbits = 160;
2631
2632 /*
2633 * If we're doing Diffie-Hellman group exchange, start by
2634 * requesting a group.
2635 */
2636 if (kex == &ssh_diffiehellman_gex) {
2637 logevent("Doing Diffie-Hellman group exchange");
2638 /*
2639 * Work out how big a DH group we will need to allow that
2640 * much data.
2641 */
2642 pbits = 512 << ((nbits-1) / 64);
2643 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
2644 ssh2_pkt_adduint32(pbits);
2645 ssh2_pkt_send();
2646
2647 crWaitUntil(ispkt);
2648 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
2649 bombout(("expected key exchange group packet from server"));
2650 crReturn(0);
2651 }
2652 p = ssh2_pkt_getmp();
2653 g = ssh2_pkt_getmp();
2654 dh_setup_group(p, g);
2655 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
2656 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
2657 } else {
2658 dh_setup_group1();
2659 kex_init_value = SSH2_MSG_KEXDH_INIT;
2660 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
2661 }
2662
2663 logevent("Doing Diffie-Hellman key exchange");
2664 /*
2665 * Now generate and send e for Diffie-Hellman.
2666 */
2667 e = dh_create_e(nbits*2);
2668 ssh2_pkt_init(kex_init_value);
2669 ssh2_pkt_addmp(e);
2670 ssh2_pkt_send();
2671
2672 crWaitUntil(ispkt);
2673 if (pktin.type != kex_reply_value) {
2674 bombout(("expected key exchange reply packet from server"));
2675 crReturn(0);
2676 }
2677 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2678 f = ssh2_pkt_getmp();
2679 ssh2_pkt_getstring(&sigdata, &siglen);
2680
2681 K = dh_find_K(f);
2682
2683 sha_string(&exhash, hostkeydata, hostkeylen);
2684 if (kex == &ssh_diffiehellman_gex) {
2685 sha_uint32(&exhash, pbits);
2686 sha_mpint(&exhash, p);
2687 sha_mpint(&exhash, g);
2688 }
2689 sha_mpint(&exhash, e);
2690 sha_mpint(&exhash, f);
2691 sha_mpint(&exhash, K);
2692 SHA_Final(&exhash, exchange_hash);
2693
2694 dh_cleanup();
2695
2696 #if 0
2697 debug(("Exchange hash is:\r\n"));
2698 for (i = 0; i < 20; i++)
2699 debug((" %02x", exchange_hash[i]));
2700 debug(("\r\n"));
2701 #endif
2702
2703 hkey = hostkey->newkey(hostkeydata, hostkeylen);
2704 if (!hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
2705 bombout(("Server failed host key check"));
2706 crReturn(0);
2707 }
2708
2709 /*
2710 * Expect SSH2_MSG_NEWKEYS from server.
2711 */
2712 crWaitUntil(ispkt);
2713 if (pktin.type != SSH2_MSG_NEWKEYS) {
2714 bombout(("expected new-keys packet from server"));
2715 crReturn(0);
2716 }
2717
2718 /*
2719 * Authenticate remote host: verify host key. (We've already
2720 * checked the signature of the exchange hash.)
2721 */
2722 keystr = hostkey->fmtkey(hkey);
2723 fingerprint = hostkey->fingerprint(hkey);
2724 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
2725 keystr, fingerprint);
2726 if (first_kex) { /* don't bother logging this in rekeys */
2727 logevent("Host key fingerprint is:");
2728 logevent(fingerprint);
2729 }
2730 sfree(fingerprint);
2731 sfree(keystr);
2732 hostkey->freekey(hkey);
2733
2734 /*
2735 * Send SSH2_MSG_NEWKEYS.
2736 */
2737 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2738 ssh2_pkt_send();
2739
2740 /*
2741 * Create and initialise session keys.
2742 */
2743 cscipher = cscipher_tobe;
2744 sccipher = sccipher_tobe;
2745 csmac = csmac_tobe;
2746 scmac = scmac_tobe;
2747 cscomp = cscomp_tobe;
2748 sccomp = sccomp_tobe;
2749 cscomp->compress_init();
2750 sccomp->decompress_init();
2751 /*
2752 * Set IVs after keys. Here we use the exchange hash from the
2753 * _first_ key exchange.
2754 */
2755 if (first_kex)
2756 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
2757 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
2758 cscipher->setcskey(keyspace);
2759 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
2760 sccipher->setsckey(keyspace);
2761 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
2762 cscipher->setcsiv(keyspace);
2763 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
2764 sccipher->setsciv(keyspace);
2765 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
2766 csmac->setcskey(keyspace);
2767 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
2768 scmac->setsckey(keyspace);
2769
2770 /*
2771 * If this is the first key exchange phase, we must pass the
2772 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2773 * wants to see it but because it will need time to initialise
2774 * itself before it sees an actual packet. In subsequent key
2775 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2776 * it would only confuse the layer above.
2777 */
2778 if (!first_kex) {
2779 crReturn(0);
2780 }
2781 first_kex = 0;
2782
2783 /*
2784 * Now we're encrypting. Begin returning 1 to the protocol main
2785 * function so that other things can run on top of the
2786 * transport. If we ever see a KEXINIT, we must go back to the
2787 * start.
2788 */
2789 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
2790 crReturn(1);
2791 }
2792 logevent("Server initiated key re-exchange");
2793 goto begin_key_exchange;
2794
2795 crFinish(1);
2796 }
2797
2798 /*
2799 * Add data to an SSH2 channel output buffer.
2800 */
2801 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len) {
2802 if (c->v2.outbufsize <
2803 c->v2.outbuflen + len) {
2804 c->v2.outbufsize =
2805 c->v2.outbuflen + len + 1024;
2806 c->v2.outbuffer = srealloc(c->v2.outbuffer,
2807 c->v2.outbufsize);
2808 }
2809 memcpy(c->v2.outbuffer + c->v2.outbuflen,
2810 buf, len);
2811 c->v2.outbuflen += len;
2812 }
2813
2814 /*
2815 * Attempt to send data on an SSH2 channel.
2816 */
2817 static void ssh2_try_send(struct ssh_channel *c) {
2818 while (c->v2.remwindow > 0 &&
2819 c->v2.outbuflen > 0) {
2820 unsigned len = c->v2.remwindow;
2821 if (len > c->v2.outbuflen)
2822 len = c->v2.outbuflen;
2823 if (len > c->v2.remmaxpkt)
2824 len = c->v2.remmaxpkt;
2825 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2826 ssh2_pkt_adduint32(c->remoteid);
2827 ssh2_pkt_addstring_start();
2828 ssh2_pkt_addstring_data(c->v2.outbuffer, len);
2829 ssh2_pkt_send();
2830 c->v2.outbuflen -= len;
2831 memmove(c->v2.outbuffer, c->v2.outbuffer+len,
2832 c->v2.outbuflen);
2833 c->v2.remwindow -= len;
2834 }
2835 }
2836
2837 /*
2838 * Handle the SSH2 userauth and connection layers.
2839 */
2840 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2841 {
2842 static unsigned long remote_winsize;
2843 static unsigned long remote_maxpkt;
2844 static enum {
2845 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE, AUTH_PASSWORD
2846 } method;
2847 static enum {
2848 AUTH_TYPE_NONE,
2849 AUTH_TYPE_PUBLICKEY,
2850 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
2851 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
2852 AUTH_TYPE_PASSWORD
2853 } type;
2854 static int gotit, need_pw, can_pubkey, can_passwd;
2855 static int tried_pubkey_config, tried_agent;
2856 static int we_are_in;
2857 static char username[100];
2858 static char pwprompt[200];
2859 static char password[100];
2860
2861 crBegin;
2862
2863 /*
2864 * Request userauth protocol, and await a response to it.
2865 */
2866 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2867 ssh2_pkt_addstring("ssh-userauth");
2868 ssh2_pkt_send();
2869 crWaitUntilV(ispkt);
2870 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2871 bombout(("Server refused user authentication protocol"));
2872 crReturnV;
2873 }
2874
2875 /*
2876 * We repeat this whole loop, including the username prompt,
2877 * until we manage a successful authentication. If the user
2878 * types the wrong _password_, they are sent back to the
2879 * beginning to try another username. (If they specify a
2880 * username in the config, they are never asked, even if they
2881 * do give a wrong password.)
2882 *
2883 * I think this best serves the needs of
2884 *
2885 * - the people who have no configuration, no keys, and just
2886 * want to try repeated (username,password) pairs until they
2887 * type both correctly
2888 *
2889 * - people who have keys and configuration but occasionally
2890 * need to fall back to passwords
2891 *
2892 * - people with a key held in Pageant, who might not have
2893 * logged in to a particular machine before; so they want to
2894 * type a username, and then _either_ their key will be
2895 * accepted, _or_ they will type a password. If they mistype
2896 * the username they will want to be able to get back and
2897 * retype it!
2898 */
2899 do {
2900 static int pos;
2901 static char c;
2902
2903 /*
2904 * Get a username.
2905 */
2906 pos = 0;
2907 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2908 if (ssh_get_line) {
2909 if (!ssh_get_line("login as: ",
2910 username, sizeof(username), FALSE)) {
2911 /*
2912 * get_line failed to get a username.
2913 * Terminate.
2914 */
2915 logevent("No username provided. Abandoning session.");
2916 ssh_state = SSH_STATE_CLOSED;
2917 crReturnV;
2918 }
2919 } else {
2920 c_write_str("login as: ");
2921 ssh_send_ok = 1;
2922 while (pos >= 0) {
2923 crWaitUntilV(!ispkt);
2924 while (inlen--) switch (c = *in++) {
2925 case 10: case 13:
2926 username[pos] = 0;
2927 pos = -1;
2928 break;
2929 case 8: case 127:
2930 if (pos > 0) {
2931 c_write_str("\b \b");
2932 pos--;
2933 }
2934 break;
2935 case 21: case 27:
2936 while (pos > 0) {
2937 c_write_str("\b \b");
2938 pos--;
2939 }
2940 break;
2941 case 3: case 4:
2942 random_save_seed();
2943 exit(0);
2944 break;
2945 default:
2946 if (((c >= ' ' && c <= '~') ||
2947 ((unsigned char)c >= 160)) && pos < 40) {
2948 username[pos++] = c;
2949 c_write(&c, 1);
2950 }
2951 break;
2952 }
2953 }
2954 }
2955 c_write_str("\r\n");
2956 username[strcspn(username, "\n\r")] = '\0';
2957 } else {
2958 char stuff[200];
2959 strncpy(username, cfg.username, 99);
2960 username[99] = '\0';
2961 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
2962 sprintf(stuff, "Using username \"%s\".\r\n", username);
2963 c_write_str(stuff);
2964 }
2965 }
2966
2967 /*
2968 * Send an authentication request using method "none": (a)
2969 * just in case it succeeds, and (b) so that we know what
2970 * authentication methods we can usefully try next.
2971 */
2972 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2973 ssh2_pkt_addstring(username);
2974 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2975 ssh2_pkt_addstring("none"); /* method */
2976 ssh2_pkt_send();
2977 type = AUTH_TYPE_NONE;
2978 gotit = FALSE;
2979 we_are_in = FALSE;
2980
2981 tried_pubkey_config = FALSE;
2982 tried_agent = FALSE;
2983
2984 while (1) {
2985 /*
2986 * Wait for the result of the last authentication request.
2987 */
2988 if (!gotit)
2989 crWaitUntilV(ispkt);
2990 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
2991 char *banner;
2992 int size;
2993 /*
2994 * Don't show the banner if we're operating in
2995 * non-verbose non-interactive mode. (It's probably
2996 * a script, which means nobody will read the
2997 * banner _anyway_, and moreover the printing of
2998 * the banner will screw up processing on the
2999 * output of (say) plink.)
3000 */
3001 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
3002 ssh2_pkt_getstring(&banner, &size);
3003 if (banner)
3004 c_write_untrusted(banner, size);
3005 }
3006 crWaitUntilV(ispkt);
3007 }
3008 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
3009 logevent("Access granted");
3010 we_are_in = TRUE;
3011 break;
3012 }
3013
3014 if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
3015 bombout(("Strange packet received during authentication: type %d",
3016 pktin.type));
3017 }
3018
3019 gotit = FALSE;
3020
3021 /*
3022 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3023 * we can look at the string in it and know what we can
3024 * helpfully try next.
3025 */
3026 {
3027 char *methods;
3028 int methlen;
3029 ssh2_pkt_getstring(&methods, &methlen);
3030 if (!ssh2_pkt_getbool()) {
3031 /*
3032 * We have received an unequivocal Access
3033 * Denied. This can translate to a variety of
3034 * messages:
3035 *
3036 * - if we'd just tried "none" authentication,
3037 * it's not worth printing anything at all
3038 *
3039 * - if we'd just tried a public key _offer_,
3040 * the message should be "Server refused our
3041 * key" (or no message at all if the key
3042 * came from Pageant)
3043 *
3044 * - if we'd just tried anything else, the
3045 * message really should be "Access denied".
3046 *
3047 * Additionally, if we'd just tried password
3048 * authentication, we should break out of this
3049 * whole loop so as to go back to the username
3050 * prompt.
3051 */
3052 if (type == AUTH_TYPE_NONE) {
3053 /* do nothing */
3054 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
3055 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
3056 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
3057 c_write_str("Server refused our key\r\n");
3058 logevent("Server refused public key");
3059 } else {
3060 c_write_str("Access denied\r\n");
3061 logevent("Access denied");
3062 if (type == AUTH_TYPE_PASSWORD) {
3063 we_are_in = FALSE;
3064 break;
3065 }
3066 }
3067 } else {
3068 c_write_str("Further authentication required\r\n");
3069 logevent("Further authentication required");
3070 }
3071
3072 can_pubkey = in_commasep_string("publickey", methods, methlen);
3073 can_passwd = in_commasep_string("password", methods, methlen);
3074 }
3075
3076 method = 0;
3077
3078 if (!method && can_pubkey && agent_exists && !tried_agent) {
3079 /*
3080 * Attempt public-key authentication using Pageant.
3081 */
3082 static unsigned char request[5], *response, *p;
3083 static int responselen;
3084 static int i, nkeys;
3085 static int authed = FALSE;
3086 void *r;
3087
3088 tried_agent = TRUE;
3089
3090 logevent("Pageant is running. Requesting keys.");
3091
3092 /* Request the keys held by the agent. */
3093 PUT_32BIT(request, 1);
3094 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
3095 agent_query(request, 5, &r, &responselen);
3096 response = (unsigned char *)r;
3097 if (response && responselen >= 5 &&
3098 response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
3099 p = response + 5;
3100 nkeys = GET_32BIT(p); p += 4;
3101 { char buf[64]; sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
3102 logevent(buf); }
3103 for (i = 0; i < nkeys; i++) {
3104 static char *pkblob, *alg, *commentp;
3105 static int pklen, alglen, commentlen;
3106 static int siglen, retlen, len;
3107 static char *q, *agentreq, *ret;
3108
3109 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
3110 logevent(buf); }
3111 pklen = GET_32BIT(p); p += 4;
3112 pkblob = p; p += pklen;
3113 alglen = GET_32BIT(pkblob);
3114 alg = pkblob + 4;
3115 commentlen = GET_32BIT(p); p += 4;
3116 commentp = p; p += commentlen;
3117 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3118 ssh2_pkt_addstring(username);
3119 ssh2_pkt_addstring("ssh-connection");/* service requested */
3120 ssh2_pkt_addstring("publickey");/* method */
3121 ssh2_pkt_addbool(FALSE); /* no signature included */
3122 ssh2_pkt_addstring_start();
3123 ssh2_pkt_addstring_data(alg, alglen);
3124 ssh2_pkt_addstring_start();
3125 ssh2_pkt_addstring_data(pkblob, pklen);
3126 ssh2_pkt_send();
3127
3128 crWaitUntilV(ispkt);
3129 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3130 logevent("Key refused");
3131 continue;
3132 }
3133
3134 if (flags & FLAG_VERBOSE) {
3135 c_write_str("Authenticating with public key \"");
3136 c_write(commentp, commentlen);
3137 c_write_str("\" from agent\r\n");
3138 }
3139
3140 /*
3141 * Server is willing to accept the key.
3142 * Construct a SIGN_REQUEST.
3143 */
3144 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3145 ssh2_pkt_addstring(username);
3146 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3147 ssh2_pkt_addstring("publickey"); /* method */
3148 ssh2_pkt_addbool(TRUE);
3149 ssh2_pkt_addstring_start();
3150 ssh2_pkt_addstring_data(alg, alglen);
3151 ssh2_pkt_addstring_start();
3152 ssh2_pkt_addstring_data(pkblob, pklen);
3153
3154 siglen = pktout.length - 5 + 4 + 20;
3155 len = 1; /* message type */
3156 len += 4 + pklen; /* key blob */
3157 len += 4 + siglen; /* data to sign */
3158 len += 4; /* flags */
3159 agentreq = smalloc(4 + len);
3160 PUT_32BIT(agentreq, len);
3161 q = agentreq + 4;
3162 *q++ = SSH2_AGENTC_SIGN_REQUEST;
3163 PUT_32BIT(q, pklen); q += 4;
3164 memcpy(q, pkblob, pklen); q += pklen;
3165 PUT_32BIT(q, siglen); q += 4;
3166 /* Now the data to be signed... */
3167 PUT_32BIT(q, 20); q += 4;
3168 memcpy(q, ssh2_session_id, 20); q += 20;
3169 memcpy(q, pktout.data+5, pktout.length-5);
3170 q += pktout.length-5;
3171 /* And finally the (zero) flags word. */
3172 PUT_32BIT(q, 0);
3173 agent_query(agentreq, len+4, &ret, &retlen);
3174 sfree(agentreq);
3175 if (ret) {
3176 if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
3177 logevent("Sending Pageant's response");
3178 ssh2_pkt_addstring_start();
3179 ssh2_pkt_addstring_data(ret+9, GET_32BIT(ret+5));
3180 ssh2_pkt_send();
3181 authed = TRUE;
3182 break;
3183 } else {
3184 logevent("Pageant failed to answer challenge");
3185 sfree(ret);
3186 }
3187 }
3188 }
3189 if (authed)
3190 continue;
3191 }
3192 }
3193
3194 if (!method && can_pubkey && *cfg.keyfile && !tried_pubkey_config) {
3195 unsigned char *pub_blob;
3196 char *algorithm, *comment;
3197 int pub_blob_len;
3198
3199 tried_pubkey_config = TRUE;
3200
3201 /*
3202 * Try the public key supplied in the configuration.
3203 *
3204 * First, offer the public blob to see if the server is
3205 * willing to accept it.
3206 */
3207 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
3208 &pub_blob_len);
3209 if (pub_blob) {
3210 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3211 ssh2_pkt_addstring(username);
3212 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3213 ssh2_pkt_addstring("publickey");/* method */
3214 ssh2_pkt_addbool(FALSE); /* no signature included */
3215 ssh2_pkt_addstring(algorithm);
3216 ssh2_pkt_addstring_start();
3217 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
3218 ssh2_pkt_send();
3219 logevent("Offered public key"); /* FIXME */
3220
3221 crWaitUntilV(ispkt);
3222 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3223 gotit = TRUE;
3224 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
3225 continue; /* key refused; give up on it */
3226 }
3227
3228 logevent("Offer of public key accepted");
3229 /*
3230 * Actually attempt a serious authentication using
3231 * the key.
3232 */
3233 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
3234 sprintf(pwprompt, "Passphrase for key \"%.100s\": ", comment);
3235 need_pw = TRUE;
3236 } else {
3237 need_pw = FALSE;
3238 }
3239 c_write_str("Authenticating with public key \"");
3240 c_write_str(comment);
3241 c_write_str("\"\r\n");
3242 method = AUTH_PUBLICKEY_FILE;
3243 }
3244 }
3245
3246 if (!method && can_passwd) {
3247 method = AUTH_PASSWORD;
3248 sprintf(pwprompt, "%.90s@%.90s's password: ", username, savedhost);
3249 need_pw = TRUE;
3250 }
3251
3252 if (need_pw) {
3253 if (ssh_get_line) {
3254 if (!ssh_get_line(pwprompt, password,
3255 sizeof(password), TRUE)) {
3256 /*
3257 * get_line failed to get a password (for
3258 * example because one was supplied on the
3259 * command line which has already failed to
3260 * work). Terminate.
3261 */
3262 logevent("No more passwords to try");
3263 ssh_state = SSH_STATE_CLOSED;
3264 crReturnV;
3265 }
3266 } else {
3267 static int pos = 0;
3268 static char c;
3269
3270 c_write_str(pwprompt);
3271 ssh_send_ok = 1;
3272
3273 pos = 0;
3274 while (pos >= 0) {
3275 crWaitUntilV(!ispkt);
3276 while (inlen--) switch (c = *in++) {
3277 case 10: case 13:
3278 password[pos] = 0;
3279 pos = -1;
3280 break;
3281 case 8: case 127:
3282 if (pos > 0)
3283 pos--;
3284 break;
3285 case 21: case 27:
3286 pos = 0;
3287 break;
3288 case 3: case 4:
3289 random_save_seed();
3290 exit(0);
3291 break;
3292 default:
3293 if (((c >= ' ' && c <= '~') ||
3294 ((unsigned char)c >= 160)) && pos < 40)
3295 password[pos++] = c;
3296 break;
3297 }
3298 }
3299 c_write_str("\r\n");
3300 }
3301 }
3302
3303 if (method == AUTH_PUBLICKEY_FILE) {
3304 /*
3305 * We have our passphrase. Now try the actual authentication.
3306 */
3307 struct ssh2_userkey *key;
3308
3309 key = ssh2_load_userkey(cfg.keyfile, password);
3310 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
3311 if (key == SSH2_WRONG_PASSPHRASE) {
3312 c_write_str("Wrong passphrase\r\n");
3313 tried_pubkey_config = FALSE;
3314 } else {
3315 c_write_str("Unable to load private key\r\n");
3316 tried_pubkey_config = TRUE;
3317 }
3318 /* Send a spurious AUTH_NONE to return to the top. */
3319 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3320 ssh2_pkt_addstring(username);
3321 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3322 ssh2_pkt_addstring("none"); /* method */
3323 ssh2_pkt_send();
3324 type = AUTH_TYPE_NONE;
3325 } else {
3326 unsigned char *blob, *sigdata;
3327 int blob_len, sigdata_len;
3328
3329 /*
3330 * We have loaded the private key and the server
3331 * has announced that it's willing to accept it.
3332 * Hallelujah. Generate a signature and send it.
3333 */
3334 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3335 ssh2_pkt_addstring(username);
3336 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3337 ssh2_pkt_addstring("publickey"); /* method */
3338 ssh2_pkt_addbool(TRUE);
3339 ssh2_pkt_addstring(key->alg->name);
3340 blob = key->alg->public_blob(key->data, &blob_len);
3341 ssh2_pkt_addstring_start();
3342 ssh2_pkt_addstring_data(blob, blob_len);
3343 sfree(blob);
3344
3345 /*
3346 * The data to be signed is:
3347 *
3348 * string session-id
3349 *
3350 * followed by everything so far placed in the
3351 * outgoing packet.
3352 */
3353 sigdata_len = pktout.length - 5 + 4 + 20;
3354 sigdata = smalloc(sigdata_len);
3355 PUT_32BIT(sigdata, 20);
3356 memcpy(sigdata+4, ssh2_session_id, 20);
3357 memcpy(sigdata+24, pktout.data+5, pktout.length-5);
3358 blob = key->alg->sign(key->data, sigdata, sigdata_len, &blob_len);
3359 ssh2_pkt_addstring_start();
3360 ssh2_pkt_addstring_data(blob, blob_len);
3361 sfree(blob);
3362 sfree(sigdata);
3363
3364 ssh2_pkt_send();
3365 type = AUTH_TYPE_PUBLICKEY;
3366 }
3367 } else if (method == AUTH_PASSWORD) {
3368 /*
3369 * We send the password packet lumped tightly together with
3370 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3371 * string long enough to make the total length of the two
3372 * packets constant. This should ensure that a passive
3373 * listener doing traffic analyis can't work out the length
3374 * of the password.
3375 *
3376 * For this to work, we need an assumption about the
3377 * maximum length of the password packet. I think 256 is
3378 * pretty conservative. Anyone using a password longer than
3379 * that probably doesn't have much to worry about from
3380 * people who find out how long their password is!
3381 */
3382 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3383 ssh2_pkt_addstring(username);
3384 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3385 ssh2_pkt_addstring("password");
3386 ssh2_pkt_addbool(FALSE);
3387 ssh2_pkt_addstring(password);
3388 ssh2_pkt_defer();
3389 /*
3390 * We'll include a string that's an exact multiple of the
3391 * cipher block size. If the cipher is NULL for some
3392 * reason, we don't do this trick at all because we gain
3393 * nothing by it.
3394 */
3395 if (cscipher) {
3396 int stringlen, i;
3397
3398 stringlen = (256 - deferred_len);
3399 stringlen += cscipher->blksize - 1;
3400 stringlen -= (stringlen % cscipher->blksize);
3401 if (cscomp) {
3402 /*
3403 * Temporarily disable actual compression,
3404 * so we can guarantee to get this string
3405 * exactly the length we want it. The
3406 * compression-disabling routine should
3407 * return an integer indicating how many
3408 * bytes we should adjust our string length
3409 * by.
3410 */
3411 stringlen -= cscomp->disable_compression();
3412 }
3413 ssh2_pkt_init(SSH2_MSG_IGNORE);
3414 ssh2_pkt_addstring_start();
3415 for (i = 0; i < stringlen; i++) {
3416 char c = (char)random_byte();
3417 ssh2_pkt_addstring_data(&c, 1);
3418 }
3419 ssh2_pkt_defer();
3420 }
3421 ssh_pkt_defersend();
3422 logevent("Sent password");
3423 type = AUTH_TYPE_PASSWORD;
3424 } else {
3425 c_write_str("No supported authentication methods left to try!\r\n");
3426 logevent("No supported authentications offered. Disconnecting");
3427 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3428 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3429 ssh2_pkt_addstring("No supported authentication methods available");
3430 ssh2_pkt_addstring("en"); /* language tag */
3431 ssh2_pkt_send();
3432 ssh_state = SSH_STATE_CLOSED;
3433 crReturnV;
3434 }
3435 }
3436 } while (!we_are_in);
3437
3438 /*
3439 * Now we're authenticated for the connection protocol. The
3440 * connection protocol will automatically have started at this
3441 * point; there's no need to send SERVICE_REQUEST.
3442 */
3443
3444 /*
3445 * So now create a channel with a session in it.
3446 */
3447 mainchan = smalloc(sizeof(struct ssh_channel));
3448 mainchan->localid = 100; /* as good as any */
3449 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
3450 ssh2_pkt_addstring("session");
3451 ssh2_pkt_adduint32(mainchan->localid);
3452 ssh2_pkt_adduint32(0x8000UL); /* our window size */
3453 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
3454 ssh2_pkt_send();
3455 crWaitUntilV(ispkt);
3456 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
3457 bombout(("Server refused to open a session"));
3458 crReturnV;
3459 /* FIXME: error data comes back in FAILURE packet */
3460 }
3461 if (ssh2_pkt_getuint32() != mainchan->localid) {
3462 bombout(("Server's channel confirmation cited wrong channel"));
3463 crReturnV;
3464 }
3465 mainchan->remoteid = ssh2_pkt_getuint32();
3466 mainchan->type = CHAN_MAINSESSION;
3467 mainchan->closes = 0;
3468 mainchan->v2.remwindow = ssh2_pkt_getuint32();
3469 mainchan->v2.remmaxpkt = ssh2_pkt_getuint32();
3470 mainchan->v2.outbuffer = NULL;
3471 mainchan->v2.outbuflen = mainchan->v2.outbufsize = 0;
3472 ssh_channels = newtree234(ssh_channelcmp);
3473 add234(ssh_channels, mainchan);
3474 logevent("Opened channel for session");
3475
3476 /*
3477 * Potentially enable X11 forwarding.
3478 */
3479 if (cfg.x11_forward) {
3480 char proto[20], data[64];
3481 logevent("Requesting X11 forwarding");
3482 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3483 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3484 ssh2_pkt_adduint32(mainchan->remoteid);
3485 ssh2_pkt_addstring("x11-req");
3486 ssh2_pkt_addbool(1); /* want reply */
3487 ssh2_pkt_addbool(0); /* many connections */
3488 ssh2_pkt_addstring(proto);
3489 ssh2_pkt_addstring(data);
3490 ssh2_pkt_adduint32(0); /* screen number */
3491 ssh2_pkt_send();
3492
3493 do {
3494 crWaitUntilV(ispkt);
3495 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3496 unsigned i = ssh2_pkt_getuint32();
3497 struct ssh_channel *c;
3498 c = find234(ssh_channels, &i, ssh_channelfind);
3499 if (!c)
3500 continue; /* nonexistent channel */
3501 c->v2.remwindow += ssh2_pkt_getuint32();
3502 }
3503 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3504
3505 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3506 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3507 bombout(("Server got confused by X11 forwarding request"));
3508 crReturnV;
3509 }
3510 logevent("X11 forwarding refused");
3511 } else {
3512 logevent("X11 forwarding enabled");
3513 ssh_X11_fwd_enabled = TRUE;
3514 }
3515 }
3516
3517 /*
3518 * Potentially enable agent forwarding.
3519 */
3520 if (cfg.agentfwd && agent_exists()) {
3521 logevent("Requesting OpenSSH-style agent forwarding");
3522 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3523 ssh2_pkt_adduint32(mainchan->remoteid);
3524 ssh2_pkt_addstring("auth-agent-req@openssh.com");
3525 ssh2_pkt_addbool(1); /* want reply */
3526 ssh2_pkt_send();
3527
3528 do {
3529 crWaitUntilV(ispkt);
3530 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3531 unsigned i = ssh2_pkt_getuint32();
3532 struct ssh_channel *c;
3533 c = find234(ssh_channels, &i, ssh_channelfind);
3534 if (!c)
3535 continue; /* nonexistent channel */
3536 c->v2.remwindow += ssh2_pkt_getuint32();
3537 }
3538 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3539
3540 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3541 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3542 bombout(("Server got confused by agent forwarding request"));
3543 crReturnV;
3544 }
3545 logevent("Agent forwarding refused");
3546 } else {
3547 logevent("Agent forwarding enabled");
3548 ssh_agentfwd_enabled = TRUE;
3549 }
3550 }
3551
3552 /*
3553 * Now allocate a pty for the session.
3554 */
3555 if (!cfg.nopty) {
3556 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3557 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
3558 ssh2_pkt_addstring("pty-req");
3559 ssh2_pkt_addbool(1); /* want reply */
3560 ssh2_pkt_addstring(cfg.termtype);
3561 ssh2_pkt_adduint32(cols);
3562 ssh2_pkt_adduint32(rows);
3563 ssh2_pkt_adduint32(0); /* pixel width */
3564 ssh2_pkt_adduint32(0); /* pixel height */
3565 ssh2_pkt_addstring_start();
3566 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3567 ssh2_pkt_send();
3568 ssh_state = SSH_STATE_INTERMED;
3569
3570 do {
3571 crWaitUntilV(ispkt);
3572 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3573 unsigned i = ssh2_pkt_getuint32();
3574 struct ssh_channel *c;
3575 c = find234(ssh_channels, &i, ssh_channelfind);
3576 if (!c)
3577 continue; /* nonexistent channel */
3578 c->v2.remwindow += ssh2_pkt_getuint32();
3579 }
3580 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3581
3582 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3583 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3584 bombout(("Server got confused by pty request"));
3585 crReturnV;
3586 }
3587 c_write_str("Server refused to allocate pty\r\n");
3588 ssh_editing = ssh_echoing = 1;
3589 } else {
3590 logevent("Allocated pty");
3591 }
3592 } else {
3593 ssh_editing = ssh_echoing = 1;
3594 }
3595
3596 /*
3597 * Start a shell or a remote command.
3598 */
3599 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3600 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
3601 if (cfg.ssh_subsys) {
3602 ssh2_pkt_addstring("subsystem");
3603 ssh2_pkt_addbool(1); /* want reply */
3604 ssh2_pkt_addstring(cfg.remote_cmd_ptr);
3605 } else if (*cfg.remote_cmd_ptr) {
3606 ssh2_pkt_addstring("exec");
3607 ssh2_pkt_addbool(1); /* want reply */
3608 ssh2_pkt_addstring(cfg.remote_cmd_ptr);
3609 } else {
3610 ssh2_pkt_addstring("shell");
3611 ssh2_pkt_addbool(1); /* want reply */
3612 }
3613 ssh2_pkt_send();
3614 do {
3615 crWaitUntilV(ispkt);
3616 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3617 unsigned i = ssh2_pkt_getuint32();
3618 struct ssh_channel *c;
3619 c = find234(ssh_channels, &i, ssh_channelfind);
3620 if (!c)
3621 continue; /* nonexistent channel */
3622 c->v2.remwindow += ssh2_pkt_getuint32();
3623 }
3624 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3625 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3626 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3627 bombout(("Server got confused by shell/command request"));
3628 crReturnV;
3629 }
3630 bombout(("Server refused to start a shell/command"));
3631 crReturnV;
3632 } else {
3633 logevent("Started a shell/command");
3634 }
3635
3636 ssh_state = SSH_STATE_SESSION;
3637 if (size_needed)
3638 ssh_size();
3639 if (eof_needed)
3640 ssh_special(TS_EOF);
3641
3642 /*
3643 * Transfer data!
3644 */
3645 ldisc_send(NULL, 0); /* cause ldisc to notice changes */
3646 ssh_send_ok = 1;
3647 while (1) {
3648 static int try_send;
3649 crReturnV;
3650 try_send = FALSE;
3651 if (ispkt) {
3652 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
3653 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
3654 char *data;
3655 int length;
3656 unsigned i = ssh2_pkt_getuint32();
3657 struct ssh_channel *c;
3658 c = find234(ssh_channels, &i, ssh_channelfind);
3659 if (!c)
3660 continue; /* nonexistent channel */
3661 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
3662 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
3663 continue; /* extended but not stderr */
3664 ssh2_pkt_getstring(&data, &length);
3665 if (data) {
3666 switch (c->type) {
3667 case CHAN_MAINSESSION:
3668 from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
3669 data, length);
3670 break;
3671 case CHAN_X11:
3672 x11_send(c->u.x11.s, data, length);
3673 break;
3674 case CHAN_AGENT:
3675 while (length > 0) {
3676 if (c->u.a.lensofar < 4) {
3677 int l = min(4 - c->u.a.lensofar, length);
3678 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
3679 data += l; length -= l; c->u.a.lensofar += l;
3680 }
3681 if (c->u.a.lensofar == 4) {
3682 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
3683 c->u.a.message = smalloc(c->u.a.totallen);
3684 memcpy(c->u.a.message, c->u.a.msglen, 4);
3685 }
3686 if (c->u.a.lensofar >= 4 && length > 0) {
3687 int l = min(c->u.a.totallen - c->u.a.lensofar,
3688 length);
3689 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
3690 data += l; length -= l; c->u.a.lensofar += l;
3691 }
3692 if (c->u.a.lensofar == c->u.a.totallen) {
3693 void *reply, *sentreply;
3694 int replylen;
3695 agent_query(c->u.a.message, c->u.a.totallen,
3696 &reply, &replylen);
3697 if (reply)
3698 sentreply = reply;
3699 else {
3700 /* Fake SSH_AGENT_FAILURE. */
3701 sentreply = "\0\0\0\1\5";
3702 replylen = 5;
3703 }
3704 ssh2_add_channel_data(c, sentreply, replylen);
3705 try_send = TRUE;
3706 if (reply)
3707 sfree(reply);
3708 sfree(c->u.a.message);
3709 c->u.a.lensofar = 0;
3710 }
3711 }
3712 break;
3713 }
3714 /*
3715 * Enlarge the window again at the remote
3716 * side, just in case it ever runs down and
3717 * they fail to send us any more data.
3718 */
3719 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3720 ssh2_pkt_adduint32(c->remoteid);
3721 ssh2_pkt_adduint32(length);
3722 ssh2_pkt_send();
3723 }
3724 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
3725 ssh_state = SSH_STATE_CLOSED;
3726 logevent("Received disconnect message");
3727 crReturnV;
3728 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
3729 continue; /* exit status et al; ignore (FIXME?) */
3730 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
3731 unsigned i = ssh2_pkt_getuint32();
3732 struct ssh_channel *c;
3733
3734 c = find234(ssh_channels, &i, ssh_channelfind);
3735 if (!c)
3736 continue; /* nonexistent channel */
3737
3738 if (c->type == CHAN_X11) {
3739 /*
3740 * Remote EOF on an X11 channel means we should
3741 * wrap up and close the channel ourselves.
3742 */
3743 x11_close(c->u.x11.s);
3744 sshfwd_close(c);
3745 } else if (c->type == CHAN_AGENT) {
3746 sshfwd_close(c);
3747 }
3748 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
3749 unsigned i = ssh2_pkt_getuint32();
3750 struct ssh_channel *c;
3751 enum234 e;
3752
3753 c = find234(ssh_channels, &i, ssh_channelfind);
3754 if (!c)
3755 continue; /* nonexistent channel */
3756 if (c->closes == 0) {
3757 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3758 ssh2_pkt_adduint32(c->remoteid);
3759 ssh2_pkt_send();
3760 }
3761 /* Do pre-close processing on the channel. */
3762 switch (c->type) {
3763 case CHAN_MAINSESSION:
3764 break; /* nothing to see here, move along */
3765 case CHAN_X11:
3766 break;
3767 case CHAN_AGENT:
3768 break;
3769 }
3770 del234(ssh_channels, c);
3771 sfree(c->v2.outbuffer);
3772 sfree(c);
3773
3774 /*
3775 * See if that was the last channel left open.
3776 */
3777 c = first234(ssh_channels, &e);
3778 if (!c) {
3779 logevent("All channels closed. Disconnecting");
3780 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3781 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3782 ssh2_pkt_addstring("All open channels closed");
3783 ssh2_pkt_addstring("en"); /* language tag */
3784 ssh2_pkt_send();
3785 ssh_state = SSH_STATE_CLOSED;
3786 crReturnV;
3787 }
3788 continue; /* remote sends close; ignore (FIXME) */
3789 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3790 unsigned i = ssh2_pkt_getuint32();
3791 struct ssh_channel *c;
3792 c = find234(ssh_channels, &i, ssh_channelfind);
3793 if (!c)
3794 continue; /* nonexistent channel */
3795 c->v2.remwindow += ssh2_pkt_getuint32();
3796 try_send = TRUE;
3797 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
3798 char *type;
3799 int typelen;
3800 char *error = NULL;
3801 struct ssh_channel *c;
3802 ssh2_pkt_getstring(&type, &typelen);
3803 c = smalloc(sizeof(struct ssh_channel));
3804
3805 if (typelen == 3 && !memcmp(type, "x11", 3)) {
3806 if (!ssh_X11_fwd_enabled)
3807 error = "X11 forwarding is not enabled";
3808 else if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
3809 error = "Unable to open an X11 connection";
3810 } else {
3811 c->type = CHAN_X11;
3812 }
3813 } else if (typelen == 22 &&
3814 !memcmp(type, "auth-agent@openssh.com", 3)) {
3815 if (!ssh_agentfwd_enabled)
3816 error = "Agent forwarding is not enabled";
3817 else {
3818 c->type = CHAN_AGENT; /* identify channel type */
3819 c->u.a.lensofar = 0;
3820 }
3821 } else {
3822 error = "Unsupported channel type requested";
3823 }
3824
3825 c->remoteid = ssh2_pkt_getuint32();
3826 if (error) {
3827 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
3828 ssh2_pkt_adduint32(c->remoteid);
3829 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
3830 ssh2_pkt_addstring(error);
3831 ssh2_pkt_addstring("en"); /* language tag */
3832 ssh2_pkt_send();
3833 sfree(c);
3834 } else {
3835 struct ssh_channel *d;
3836 unsigned i;
3837 enum234 e;
3838
3839 for (i=1, d = first234(ssh_channels, &e); d;
3840 d = next234(&e)) {
3841 if (d->localid > i)
3842 break; /* found a free number */
3843 i = d->localid + 1;
3844 }
3845 c->localid = i;
3846 c->closes = 0;
3847 c->v2.remwindow = ssh2_pkt_getuint32();
3848 c->v2.remmaxpkt = ssh2_pkt_getuint32();
3849 c->v2.outbuffer = NULL;
3850 c->v2.outbuflen = c->v2.outbufsize = 0;
3851 add234(ssh_channels, c);
3852 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
3853 ssh2_pkt_adduint32(c->remoteid);
3854 ssh2_pkt_adduint32(c->localid);
3855 ssh2_pkt_adduint32(0x8000UL); /* our window size */
3856 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
3857 ssh2_pkt_send();
3858 }
3859 } else {
3860 bombout(("Strange packet received: type %d", pktin.type));
3861 crReturnV;
3862 }
3863 } else {
3864 /*
3865 * We have spare data. Add it to the channel buffer.
3866 */
3867 ssh2_add_channel_data(mainchan, in, inlen);
3868 try_send = TRUE;
3869 }
3870 if (try_send) {
3871 enum234 e;
3872 struct ssh_channel *c;
3873 /*
3874 * Try to send data on all channels if we can.
3875 */
3876 for (c = first234(ssh_channels, &e); c; c = next234(&e))
3877 ssh2_try_send(c);
3878 }
3879 }
3880
3881 crFinishV;
3882 }
3883
3884 /*
3885 * Handle the top-level SSH2 protocol.
3886 */
3887 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
3888 {
3889 if (do_ssh2_transport(in, inlen, ispkt) == 0)
3890 return;
3891 do_ssh2_authconn(in, inlen, ispkt);
3892 }
3893
3894 /*
3895 * Called to set up the connection.
3896 *
3897 * Returns an error message, or NULL on success.
3898 */
3899 static char *ssh_init (char *host, int port, char **realhost) {
3900 char *p;
3901
3902 #ifdef MSCRYPTOAPI
3903 if(crypto_startup() == 0)
3904 return "Microsoft high encryption pack not installed!";
3905 #endif
3906
3907 ssh_send_ok = 0;
3908 ssh_editing = 0;
3909 ssh_echoing = 0;
3910
3911 p = connect_to_host(host, port, realhost);
3912 if (p != NULL)
3913 return p;
3914
3915 return NULL;
3916 }
3917
3918 /*
3919 * Called to send data down the Telnet connection.
3920 */
3921 static void ssh_send (char *buf, int len) {
3922 if (s == NULL || ssh_protocol == NULL)
3923 return;
3924
3925 ssh_protocol(buf, len, 0);
3926 }
3927
3928 /*
3929 * Called to set the size of the window from SSH's POV.
3930 */
3931 static void ssh_size(void) {
3932 switch (ssh_state) {
3933 case SSH_STATE_BEFORE_SIZE:
3934 case SSH_STATE_PREPACKET:
3935 case SSH_STATE_CLOSED:
3936 break; /* do nothing */
3937 case SSH_STATE_INTERMED:
3938 size_needed = TRUE; /* buffer for later */
3939 break;
3940 case SSH_STATE_SESSION:
3941 if (!cfg.nopty) {
3942 if (ssh_version == 1) {
3943 send_packet(SSH1_CMSG_WINDOW_SIZE,
3944 PKT_INT, rows, PKT_INT, cols,
3945 PKT_INT, 0, PKT_INT, 0, PKT_END);
3946 } else {
3947 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3948 ssh2_pkt_adduint32(mainchan->remoteid);
3949 ssh2_pkt_addstring("window-change");
3950 ssh2_pkt_addbool(0);
3951 ssh2_pkt_adduint32(cols);
3952 ssh2_pkt_adduint32(rows);
3953 ssh2_pkt_adduint32(0);
3954 ssh2_pkt_adduint32(0);
3955 ssh2_pkt_send();
3956 }
3957 }
3958 break;
3959 }
3960 }
3961
3962 /*
3963 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3964 * can send an EOF and collect resulting output (e.g. `plink
3965 * hostname sort').
3966 */
3967 static void ssh_special (Telnet_Special code) {
3968 if (code == TS_EOF) {
3969 if (ssh_state != SSH_STATE_SESSION) {
3970 /*
3971 * Buffer the EOF in case we are pre-SESSION, so we can
3972 * send it as soon as we reach SESSION.
3973 */
3974 if (code == TS_EOF)
3975 eof_needed = TRUE;
3976 return;
3977 }
3978 if (ssh_version == 1) {
3979 send_packet(SSH1_CMSG_EOF, PKT_END);
3980 } else {
3981 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
3982 ssh2_pkt_adduint32(mainchan->remoteid);
3983 ssh2_pkt_send();
3984 }
3985 logevent("Sent EOF message");
3986 } else if (code == TS_PING) {
3987 if (ssh_state == SSH_STATE_CLOSED || ssh_state == SSH_STATE_PREPACKET)
3988 return;
3989 if (ssh_version == 1) {
3990 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
3991 } else {
3992 ssh2_pkt_init(SSH2_MSG_IGNORE);
3993 ssh2_pkt_addstring_start();
3994 ssh2_pkt_send();
3995 }
3996 } else {
3997 /* do nothing */
3998 }
3999 }
4000
4001 static Socket ssh_socket(void) { return s; }
4002
4003 static int ssh_sendok(void) { return ssh_send_ok; }
4004
4005 static int ssh_ldisc(int option) {
4006 if (option == LD_ECHO) return ssh_echoing;
4007 if (option == LD_EDIT) return ssh_editing;
4008 return FALSE;
4009 }
4010
4011 Backend ssh_backend = {
4012 ssh_init,
4013 ssh_send,
4014 ssh_size,
4015 ssh_special,
4016 ssh_socket,
4017 ssh_sendok,
4018 ssh_ldisc,
4019 22
4020 };