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