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