1 /* $NetBSD: clientloop.c,v 1.43 2025/04/09 15:49:32 christos Exp $ */
2 /* $OpenBSD: clientloop.c,v 1.410 2024/12/03 22:30:03 jsg Exp $ */
3
4 /*
5 * Author: Tatu Ylonen <ylo@cs.hut.fi>
6 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * All rights reserved
8 * The main loop for the interactive session (client side).
9 *
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
15 *
16 *
17 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
18 *
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
21 * are met:
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 *
39 *
40 * SSH2 support added by Markus Friedl.
41 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 *
52 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
53 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
54 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
55 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
56 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
57 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
58 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
59 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
60 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
61 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
62 */
63
64 #include "includes.h"
65 __RCSID("$NetBSD: clientloop.c,v 1.43 2025/04/09 15:49:32 christos Exp $");
66
67 #include <sys/types.h>
68 #include <sys/ioctl.h>
69 #include <sys/stat.h>
70 #include <sys/socket.h>
71 #include <sys/time.h>
72 #include <sys/queue.h>
73
74 #include <ctype.h>
75 #include <errno.h>
76 #include <paths.h>
77 #include <poll.h>
78 #include <signal.h>
79 #include <stdio.h>
80 #include <stdlib.h>
81 #include <string.h>
82 #include <stdarg.h>
83 #include <termios.h>
84 #include <pwd.h>
85 #include <unistd.h>
86 #include <limits.h>
87
88 #include "xmalloc.h"
89 #include "ssh.h"
90 #include "ssh2.h"
91 #include "packet.h"
92 #include "sshbuf.h"
93 #include "compat.h"
94 #include "channels.h"
95 #include "dispatch.h"
96 #include "sshkey.h"
97 #include "cipher.h"
98 #include "kex.h"
99 #include "myproposal.h"
100 #include "log.h"
101 #include "misc.h"
102 #include "readconf.h"
103 #include "clientloop.h"
104 #include "sshconnect.h"
105 #include "authfd.h"
106 #include "atomicio.h"
107 #include "sshpty.h"
108 #include "match.h"
109 #include "msg.h"
110 #include "getpeereid.h"
111 #include "ssherr.h"
112 #include "hostfile.h"
113
114 /* Permitted RSA signature algorithms for UpdateHostkeys proofs */
115 #define HOSTKEY_PROOF_RSA_ALGS "rsa-sha2-512,rsa-sha2-256"
116
117 /* Uncertainty (in percent) of keystroke timing intervals */
118 #define SSH_KEYSTROKE_TIMING_FUZZ 10
119
120 /* import options */
121 extern Options options;
122
123 /* Control socket */
124 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
125
126 /*
127 * Name of the host we are connecting to. This is the name given on the
128 * command line, or the Hostname specified for the user-supplied name in a
129 * configuration file.
130 */
131 extern char *host;
132
133 /*
134 * If this field is not NULL, the ForwardAgent socket is this path and different
135 * instead of SSH_AUTH_SOCK.
136 */
137 extern char *forward_agent_sock_path;
138
139 /*
140 * Flag to indicate that we have received a window change signal which has
141 * not yet been processed. This will cause a message indicating the new
142 * window size to be sent to the server a little later. This is volatile
143 * because this is updated in a signal handler.
144 */
145 static volatile sig_atomic_t received_window_change_signal = 0;
146 static volatile sig_atomic_t received_signal = 0;
147
148 /* Time when backgrounded control master using ControlPersist should exit */
149 static time_t control_persist_exit_time = 0;
150
151 /* Common data for the client loop code. */
152 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
153 static int last_was_cr; /* Last character was a newline. */
154 static int exit_status; /* Used to store the command exit status. */
155 static int connection_in; /* Connection to server (input). */
156 static int connection_out; /* Connection to server (output). */
157 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
158 static int session_closed; /* In SSH2: login session closed. */
159 static time_t x11_refuse_time; /* If >0, refuse x11 opens after this time. */
160 static time_t server_alive_time; /* Time to do server_alive_check */
161 static int hostkeys_update_complete;
162 static int session_setup_complete;
163
164 static void client_init_dispatch(struct ssh *ssh);
165 int session_ident = -1;
166
167 /* Track escape per proto2 channel */
168 struct escape_filter_ctx {
169 int escape_pending;
170 int escape_char;
171 };
172
173 /* Context for channel confirmation replies */
174 struct channel_reply_ctx {
175 const char *request_type;
176 int id;
177 enum confirm_action action;
178 };
179
180 /* Global request success/failure callbacks */
181 /* XXX move to struct ssh? */
182 struct global_confirm {
183 TAILQ_ENTRY(global_confirm) entry;
184 global_confirm_cb *cb;
185 void *ctx;
186 int ref_count;
187 };
188 TAILQ_HEAD(global_confirms, global_confirm);
189 static struct global_confirms global_confirms =
190 TAILQ_HEAD_INITIALIZER(global_confirms);
191
192 static void quit_message(const char *fmt, ...)
193 __attribute__((__format__ (printf, 1, 2)));
194
195 static void
quit_message(const char * fmt,...)196 quit_message(const char *fmt, ...)
197 {
198 char *msg, *fmt2;
199 va_list args;
200 xasprintf(&fmt2, "%s\r\n", fmt);
201
202 va_start(args, fmt);
203 #pragma GCC diagnostic push
204 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
205 xvasprintf(&msg, fmt2, args);
206 #pragma GCC diagnostic pop
207 va_end(args);
208
209 (void)atomicio(vwrite, STDERR_FILENO, msg, strlen(msg));
210 free(msg);
211 free(fmt2);
212
213 quit_pending = 1;
214 }
215
216 /*
217 * Signal handler for the window change signal (SIGWINCH). This just sets a
218 * flag indicating that the window has changed.
219 */
220 static void
window_change_handler(int sig)221 window_change_handler(int sig)
222 {
223 received_window_change_signal = 1;
224 }
225
226 /*
227 * Signal handler for signals that cause the program to terminate. These
228 * signals must be trapped to restore terminal modes.
229 */
230 static void
signal_handler(int sig)231 signal_handler(int sig)
232 {
233 received_signal = sig;
234 quit_pending = 1;
235 }
236
237 /*
238 * Sets control_persist_exit_time to the absolute time when the
239 * backgrounded control master should exit due to expiry of the
240 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
241 * control master process, or if there is no ControlPersist timeout.
242 */
243 static void
set_control_persist_exit_time(struct ssh * ssh)244 set_control_persist_exit_time(struct ssh *ssh)
245 {
246 if (muxserver_sock == -1 || !options.control_persist
247 || options.control_persist_timeout == 0) {
248 /* not using a ControlPersist timeout */
249 control_persist_exit_time = 0;
250 } else if (channel_still_open(ssh)) {
251 /* some client connections are still open */
252 if (control_persist_exit_time > 0)
253 debug2_f("cancel scheduled exit");
254 control_persist_exit_time = 0;
255 } else if (control_persist_exit_time <= 0) {
256 /* a client connection has recently closed */
257 control_persist_exit_time = monotime() +
258 (time_t)options.control_persist_timeout;
259 debug2_f("schedule exit in %d seconds",
260 options.control_persist_timeout);
261 }
262 /* else we are already counting down to the timeout */
263 }
264
265 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
266 static int
client_x11_display_valid(const char * display)267 client_x11_display_valid(const char *display)
268 {
269 size_t i, dlen;
270
271 if (display == NULL)
272 return 0;
273
274 dlen = strlen(display);
275 for (i = 0; i < dlen; i++) {
276 if (!isalnum((u_char)display[i]) &&
277 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
278 debug("Invalid character '%c' in DISPLAY", display[i]);
279 return 0;
280 }
281 }
282 return 1;
283 }
284
285 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
286 #define X11_TIMEOUT_SLACK 60
287 int
client_x11_get_proto(struct ssh * ssh,const char * display,const char * xauth_path,u_int trusted,u_int timeout,char ** _proto,char ** _data)288 client_x11_get_proto(struct ssh *ssh, const char *display,
289 const char *xauth_path, u_int trusted, u_int timeout,
290 char **_proto, char **_data)
291 {
292 char *cmd, line[512], xdisplay[512];
293 char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
294 static char proto[512], data[512];
295 FILE *f;
296 int got_data = 0, generated = 0, do_unlink = 0, r;
297 struct stat st;
298 u_int now, x11_timeout_real;
299
300 *_proto = proto;
301 *_data = data;
302 proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
303
304 if (!client_x11_display_valid(display)) {
305 if (display != NULL)
306 logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
307 display);
308 return -1;
309 }
310 if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
311 debug("No xauth program.");
312 xauth_path = NULL;
313 }
314
315 if (xauth_path != NULL) {
316 /*
317 * Handle FamilyLocal case where $DISPLAY does
318 * not match an authorization entry. For this we
319 * just try "xauth list unix:displaynum.screennum".
320 * XXX: "localhost" match to determine FamilyLocal
321 * is not perfect.
322 */
323 if (strncmp(display, "localhost:", 10) == 0) {
324 if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
325 display + 10)) < 0 ||
326 (size_t)r >= sizeof(xdisplay)) {
327 error_f("display name too long");
328 return -1;
329 }
330 display = xdisplay;
331 }
332 if (trusted == 0) {
333 /*
334 * Generate an untrusted X11 auth cookie.
335 *
336 * The authentication cookie should briefly outlive
337 * ssh's willingness to forward X11 connections to
338 * avoid nasty fail-open behaviour in the X server.
339 */
340 mktemp_proto(xauthdir, sizeof(xauthdir));
341 if (mkdtemp(xauthdir) == NULL) {
342 error_f("mkdtemp: %s", strerror(errno));
343 return -1;
344 }
345 do_unlink = 1;
346 if ((r = snprintf(xauthfile, sizeof(xauthfile),
347 "%s/xauthfile", xauthdir)) < 0 ||
348 (size_t)r >= sizeof(xauthfile)) {
349 error_f("xauthfile path too long");
350 rmdir(xauthdir);
351 return -1;
352 }
353
354 if (timeout == 0) {
355 /* auth doesn't time out */
356 xasprintf(&cmd, "%s -f %s generate %s %s "
357 "untrusted 2>%s",
358 xauth_path, xauthfile, display,
359 SSH_X11_PROTO, _PATH_DEVNULL);
360 } else {
361 /* Add some slack to requested expiry */
362 if (timeout < UINT_MAX - X11_TIMEOUT_SLACK)
363 x11_timeout_real = timeout +
364 X11_TIMEOUT_SLACK;
365 else {
366 /* Don't overflow on long timeouts */
367 x11_timeout_real = UINT_MAX;
368 }
369 xasprintf(&cmd, "%s -f %s generate %s %s "
370 "untrusted timeout %u 2>%s",
371 xauth_path, xauthfile, display,
372 SSH_X11_PROTO, x11_timeout_real,
373 _PATH_DEVNULL);
374 }
375 debug2_f("xauth command: %s", cmd);
376
377 if (timeout != 0 && x11_refuse_time == 0) {
378 now = monotime() + 1;
379 if (SSH_TIME_T_MAX - timeout < now)
380 x11_refuse_time = SSH_TIME_T_MAX;
381 else
382 x11_refuse_time = now + timeout;
383 channel_set_x11_refuse_time(ssh,
384 x11_refuse_time);
385 }
386 if (system(cmd) == 0)
387 generated = 1;
388 free(cmd);
389 }
390
391 /*
392 * When in untrusted mode, we read the cookie only if it was
393 * successfully generated as an untrusted one in the step
394 * above.
395 */
396 if (trusted || generated) {
397 xasprintf(&cmd,
398 "%s %s%s list %s 2>" _PATH_DEVNULL,
399 xauth_path,
400 generated ? "-f " : "" ,
401 generated ? xauthfile : "",
402 display);
403 debug2("x11_get_proto: %s", cmd);
404 f = popen(cmd, "r");
405 if (f && fgets(line, sizeof(line), f) &&
406 sscanf(line, "%*s %511s %511s", proto, data) == 2)
407 got_data = 1;
408 if (f)
409 pclose(f);
410 free(cmd);
411 }
412 }
413
414 if (do_unlink) {
415 unlink(xauthfile);
416 rmdir(xauthdir);
417 }
418
419 /* Don't fall back to fake X11 data for untrusted forwarding */
420 if (!trusted && !got_data) {
421 error("Warning: untrusted X11 forwarding setup failed: "
422 "xauth key data not generated");
423 return -1;
424 }
425
426 /*
427 * If we didn't get authentication data, just make up some
428 * data. The forwarding code will check the validity of the
429 * response anyway, and substitute this data. The X11
430 * server, however, will ignore this fake data and use
431 * whatever authentication mechanisms it was using otherwise
432 * for the local connection.
433 */
434 if (!got_data) {
435 u_int8_t rnd[16];
436 u_int i;
437
438 logit("Warning: No xauth data; "
439 "using fake authentication data for X11 forwarding.");
440 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
441 arc4random_buf(rnd, sizeof(rnd));
442 for (i = 0; i < sizeof(rnd); i++) {
443 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
444 rnd[i]);
445 }
446 }
447
448 return 0;
449 }
450
451 /*
452 * Checks if the client window has changed, and sends a packet about it to
453 * the server if so. The actual change is detected elsewhere (by a software
454 * interrupt on Unix); this just checks the flag and sends a message if
455 * appropriate.
456 */
457
458 static void
client_check_window_change(struct ssh * ssh)459 client_check_window_change(struct ssh *ssh)
460 {
461 if (!received_window_change_signal)
462 return;
463 received_window_change_signal = 0;
464 debug2_f("changed");
465 channel_send_window_changes(ssh);
466 }
467
468 static int
client_global_request_reply(int type,u_int32_t seq,struct ssh * ssh)469 client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
470 {
471 struct global_confirm *gc;
472
473 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
474 return 0;
475 if (gc->cb != NULL)
476 gc->cb(ssh, type, seq, gc->ctx);
477 if (--gc->ref_count <= 0) {
478 TAILQ_REMOVE(&global_confirms, gc, entry);
479 freezero(gc, sizeof(*gc));
480 }
481
482 ssh_packet_set_alive_timeouts(ssh, 0);
483 return 0;
484 }
485
486 static void
schedule_server_alive_check(void)487 schedule_server_alive_check(void)
488 {
489 if (options.server_alive_interval > 0)
490 server_alive_time = monotime() + options.server_alive_interval;
491 }
492
493 static void
server_alive_check(struct ssh * ssh)494 server_alive_check(struct ssh *ssh)
495 {
496 int r;
497
498 if (ssh_packet_inc_alive_timeouts(ssh) > options.server_alive_count_max) {
499 logit("Timeout, server %s not responding.", host);
500 cleanup_exit(255);
501 }
502 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
503 (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) != 0 ||
504 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* boolean: want reply */
505 (r = sshpkt_send(ssh)) != 0)
506 fatal_fr(r, "send packet");
507 /* Insert an empty placeholder to maintain ordering */
508 client_register_global_confirm(NULL, NULL);
509 schedule_server_alive_check();
510 }
511
512 /* Try to send a dummy keystroke */
513 static int
send_chaff(struct ssh * ssh)514 send_chaff(struct ssh *ssh)
515 {
516 int r;
517
518 if (ssh->kex == NULL || (ssh->kex->flags & KEX_HAS_PING) == 0)
519 return 0;
520 /* XXX probabilistically send chaff? */
521 /*
522 * a SSH2_MSG_CHANNEL_DATA payload is 9 bytes:
523 * 4 bytes channel ID + 4 bytes string length + 1 byte string data
524 * simulate that here.
525 */
526 if ((r = sshpkt_start(ssh, SSH2_MSG_PING)) != 0 ||
527 (r = sshpkt_put_cstring(ssh, "PING!")) != 0 ||
528 (r = sshpkt_send(ssh)) != 0)
529 fatal_fr(r, "send packet");
530 return 1;
531 }
532
533 /* Sets the next interval to send a keystroke or chaff packet */
534 static void
set_next_interval(const struct timespec * now,struct timespec * next_interval,u_int interval_ms,int starting)535 set_next_interval(const struct timespec *now, struct timespec *next_interval,
536 u_int interval_ms, int starting)
537 {
538 struct timespec tmp;
539 long long interval_ns, fuzz_ns;
540 static long long rate_fuzz;
541
542 interval_ns = interval_ms * (1000LL * 1000);
543 fuzz_ns = (interval_ns * SSH_KEYSTROKE_TIMING_FUZZ) / 100;
544 /* Center fuzz around requested interval */
545 if (fuzz_ns > INT_MAX)
546 fuzz_ns = INT_MAX;
547 if (fuzz_ns > interval_ns) {
548 /* Shouldn't happen */
549 fatal_f("internal error: fuzz %u%% %lldns > interval %lldns",
550 SSH_KEYSTROKE_TIMING_FUZZ, fuzz_ns, interval_ns);
551 }
552 /*
553 * Randomise the keystroke/chaff intervals in two ways:
554 * 1. Each interval has some random jitter applied to make the
555 * interval-to-interval time unpredictable.
556 * 2. The overall interval rate is also randomly perturbed for each
557 * chaffing session to make the average rate unpredictable.
558 */
559 if (starting)
560 rate_fuzz = arc4random_uniform(fuzz_ns);
561 interval_ns -= fuzz_ns;
562 interval_ns += arc4random_uniform(fuzz_ns) + rate_fuzz;
563
564 tmp.tv_sec = interval_ns / (1000 * 1000 * 1000);
565 tmp.tv_nsec = interval_ns % (1000 * 1000 * 1000);
566
567 timespecadd(now, &tmp, next_interval);
568 }
569
570 /*
571 * Performs keystroke timing obfuscation. Returns non-zero if the
572 * output fd should be polled.
573 */
574 static int
obfuscate_keystroke_timing(struct ssh * ssh,struct timespec * timeout,int channel_did_enqueue)575 obfuscate_keystroke_timing(struct ssh *ssh, struct timespec *timeout,
576 int channel_did_enqueue)
577 {
578 static int active;
579 static struct timespec next_interval, chaff_until;
580 struct timespec now, tmp;
581 int just_started = 0, had_keystroke = 0;
582 static unsigned long long nchaff;
583 const char *stop_reason = NULL;
584 long long n;
585
586 monotime_ts(&now);
587
588 if (options.obscure_keystroke_timing_interval <= 0)
589 return 1; /* disabled in config */
590
591 if (!channel_tty_open(ssh) || quit_pending) {
592 /* Stop if no channels left of we're waiting for one to close */
593 stop_reason = "no active channels";
594 } else if (ssh_packet_is_rekeying(ssh)) {
595 /* Stop if we're rekeying */
596 stop_reason = "rekeying started";
597 } else if (!ssh_packet_interactive_data_to_write(ssh) &&
598 ssh_packet_have_data_to_write(ssh)) {
599 /* Stop if the output buffer has more than a few keystrokes */
600 stop_reason = "output buffer filling";
601 } else if (active && channel_did_enqueue &&
602 ssh_packet_have_data_to_write(ssh)) {
603 /* Still in active mode and have a keystroke queued. */
604 had_keystroke = 1;
605 } else if (active) {
606 if (timespeccmp(&now, &chaff_until, >=)) {
607 /* Stop if there have been no keystrokes for a while */
608 stop_reason = "chaff time expired";
609 } else if (timespeccmp(&now, &next_interval, >=) &&
610 !ssh_packet_have_data_to_write(ssh)) {
611 /* If due to send but have no data, then send chaff */
612 if (send_chaff(ssh))
613 nchaff++;
614 }
615 }
616
617 if (stop_reason != NULL) {
618 if (active) {
619 debug3_f("stopping: %s (%llu chaff packets sent)",
620 stop_reason, nchaff);
621 active = 0;
622 }
623 return 1;
624 }
625
626 /*
627 * If we're in interactive mode, and only have a small amount
628 * of outbound data, then we assume that the user is typing
629 * interactively. In this case, start quantising outbound packets to
630 * fixed time intervals to hide inter-keystroke timing.
631 */
632 if (!active && ssh_packet_interactive_data_to_write(ssh) &&
633 channel_did_enqueue && ssh_packet_have_data_to_write(ssh)) {
634 debug3_f("starting: interval ~%dms",
635 options.obscure_keystroke_timing_interval);
636 just_started = had_keystroke = active = 1;
637 nchaff = 0;
638 set_next_interval(&now, &next_interval,
639 options.obscure_keystroke_timing_interval, 1);
640 }
641
642 /* Don't hold off if obfuscation inactive */
643 if (!active)
644 return 1;
645
646 if (had_keystroke) {
647 /*
648 * Arrange to send chaff packets for a random interval after
649 * the last keystroke was sent.
650 */
651 ms_to_timespec(&tmp, SSH_KEYSTROKE_CHAFF_MIN_MS +
652 arc4random_uniform(SSH_KEYSTROKE_CHAFF_RNG_MS));
653 timespecadd(&now, &tmp, &chaff_until);
654 }
655
656 ptimeout_deadline_monotime_tsp(timeout, &next_interval);
657
658 if (just_started)
659 return 1;
660
661 /* Don't arm output fd for poll until the timing interval has elapsed... */
662 if (timespeccmp(&now, &next_interval, <))
663 /* ...unless there's x11 communication happening */
664 return x11_channel_used_recently(ssh);
665
666 /* Calculate number of intervals missed since the last check */
667 n = (now.tv_sec - next_interval.tv_sec) * 1000LL * 1000 * 1000;
668 n += now.tv_nsec - next_interval.tv_nsec;
669 n /= options.obscure_keystroke_timing_interval * 1000LL * 1000;
670 n = (n < 0) ? 1 : n + 1;
671
672 /* Advance to the next interval */
673 set_next_interval(&now, &next_interval,
674 options.obscure_keystroke_timing_interval * n, 0);
675 return 1;
676 }
677
678 /*
679 * Waits until the client can do something (some data becomes available on
680 * one of the file descriptors).
681 */
682 static void
client_wait_until_can_do_something(struct ssh * ssh,struct pollfd ** pfdp,u_int * npfd_allocp,u_int * npfd_activep,int channel_did_enqueue,sigset_t * sigsetp,int * conn_in_readyp,int * conn_out_readyp)683 client_wait_until_can_do_something(struct ssh *ssh, struct pollfd **pfdp,
684 u_int *npfd_allocp, u_int *npfd_activep, int channel_did_enqueue,
685 sigset_t *sigsetp, int *conn_in_readyp, int *conn_out_readyp)
686 {
687 struct timespec timeout;
688 int ret, oready;
689 u_int p;
690
691 *conn_in_readyp = *conn_out_readyp = 0;
692
693 /* Prepare channel poll. First two pollfd entries are reserved */
694 ptimeout_init(&timeout);
695 channel_prepare_poll(ssh, pfdp, npfd_allocp, npfd_activep, 2, &timeout);
696 if (*npfd_activep < 2)
697 fatal_f("bad npfd %u", *npfd_activep); /* shouldn't happen */
698
699 /* channel_prepare_poll could have closed the last channel */
700 if (session_closed && !channel_still_open(ssh) &&
701 !ssh_packet_have_data_to_write(ssh)) {
702 /* clear events since we did not call poll() */
703 for (p = 0; p < *npfd_activep; p++)
704 (*pfdp)[p].revents = 0;
705 return;
706 }
707
708 oready = obfuscate_keystroke_timing(ssh, &timeout, channel_did_enqueue);
709
710 /* Monitor server connection on reserved pollfd entries */
711 (*pfdp)[0].fd = connection_in;
712 (*pfdp)[0].events = POLLIN;
713 (*pfdp)[1].fd = connection_out;
714 (*pfdp)[1].events = (oready && ssh_packet_have_data_to_write(ssh)) ?
715 POLLOUT : 0;
716
717 /*
718 * Wait for something to happen. This will suspend the process until
719 * some polled descriptor can be read, written, or has some other
720 * event pending, or a timeout expires.
721 */
722 set_control_persist_exit_time(ssh);
723 if (control_persist_exit_time > 0)
724 ptimeout_deadline_monotime(&timeout, control_persist_exit_time);
725 if (options.server_alive_interval > 0)
726 ptimeout_deadline_monotime(&timeout, server_alive_time);
727 if (options.rekey_interval > 0 && !ssh_packet_is_rekeying(ssh)) {
728 ptimeout_deadline_sec(&timeout,
729 ssh_packet_get_rekey_timeout(ssh));
730 }
731
732 ret = ppoll(*pfdp, *npfd_activep, ptimeout_get_tsp(&timeout), sigsetp);
733
734 if (ret == -1) {
735 /*
736 * We have to clear the events because we return.
737 * We have to return, because the mainloop checks for the flags
738 * set by the signal handlers.
739 */
740 for (p = 0; p < *npfd_activep; p++)
741 (*pfdp)[p].revents = 0;
742 if (errno == EINTR)
743 return;
744 /* Note: we might still have data in the buffers. */
745 quit_message("poll: %s", strerror(errno));
746 return;
747 }
748
749 *conn_in_readyp = (*pfdp)[0].revents != 0;
750 *conn_out_readyp = (*pfdp)[1].revents != 0;
751
752 if (options.server_alive_interval > 0 && !*conn_in_readyp &&
753 monotime() >= server_alive_time) {
754 /*
755 * ServerAlive check is needed. We can't rely on the poll
756 * timing out since traffic on the client side such as port
757 * forwards can keep waking it up.
758 */
759 server_alive_check(ssh);
760 }
761 }
762
763 static void
client_suspend_self(struct sshbuf * bin,struct sshbuf * bout,struct sshbuf * berr)764 client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr)
765 {
766 /* Flush stdout and stderr buffers. */
767 if (sshbuf_len(bout) > 0)
768 atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout),
769 sshbuf_len(bout));
770 if (sshbuf_len(berr) > 0)
771 atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr),
772 sshbuf_len(berr));
773
774 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
775
776 sshbuf_reset(bin);
777 sshbuf_reset(bout);
778 sshbuf_reset(berr);
779
780 /* Send the suspend signal to the program itself. */
781 kill(getpid(), SIGTSTP);
782
783 /* Reset window sizes in case they have changed */
784 received_window_change_signal = 1;
785
786 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
787 }
788
789 static void
client_process_net_input(struct ssh * ssh)790 client_process_net_input(struct ssh *ssh)
791 {
792 int r;
793
794 /*
795 * Read input from the server, and add any such data to the buffer of
796 * the packet subsystem.
797 */
798 schedule_server_alive_check();
799 if ((r = ssh_packet_process_read(ssh, connection_in)) == 0)
800 return; /* success */
801 if (r == SSH_ERR_SYSTEM_ERROR) {
802 if (errno == EAGAIN || errno == EINTR)
803 return;
804 if (errno == EPIPE) {
805 quit_message("Connection to %s closed by remote host.",
806 host);
807 return;
808 }
809 }
810 quit_message("Read from remote host %s: %s", host, ssh_err(r));
811 }
812
813 static void
client_status_confirm(struct ssh * ssh,int type,Channel * c,void * ctx)814 client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
815 {
816 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
817 char errmsg[256];
818 int r, tochan;
819
820 /*
821 * If a TTY was explicitly requested, then a failure to allocate
822 * one is fatal.
823 */
824 if (cr->action == CONFIRM_TTY &&
825 (options.request_tty == REQUEST_TTY_FORCE ||
826 options.request_tty == REQUEST_TTY_YES))
827 cr->action = CONFIRM_CLOSE;
828
829 /* XXX suppress on mux _client_ quietmode */
830 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
831 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
832
833 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
834 debug2("%s request accepted on channel %d",
835 cr->request_type, c->self);
836 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
837 if (tochan) {
838 snprintf(errmsg, sizeof(errmsg),
839 "%s request failed\r\n", cr->request_type);
840 } else {
841 snprintf(errmsg, sizeof(errmsg),
842 "%s request failed on channel %d",
843 cr->request_type, c->self);
844 }
845 /* If error occurred on primary session channel, then exit */
846 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
847 fatal("%s", errmsg);
848 /*
849 * If error occurred on mux client, append to
850 * their stderr.
851 */
852 if (tochan) {
853 debug3_f("channel %d: mux request: %s", c->self,
854 cr->request_type);
855 if ((r = sshbuf_put(c->extended, errmsg,
856 strlen(errmsg))) != 0)
857 fatal_fr(r, "sshbuf_put");
858 } else
859 error("%s", errmsg);
860 if (cr->action == CONFIRM_TTY) {
861 /*
862 * If a TTY allocation error occurred, then arrange
863 * for the correct TTY to leave raw mode.
864 */
865 if (c->self == session_ident)
866 leave_raw_mode(0);
867 else
868 mux_tty_alloc_failed(ssh, c);
869 } else if (cr->action == CONFIRM_CLOSE) {
870 chan_read_failed(ssh, c);
871 chan_write_failed(ssh, c);
872 }
873 }
874 free(cr);
875 }
876
877 static void
client_abandon_status_confirm(struct ssh * ssh,Channel * c,void * ctx)878 client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
879 {
880 free(ctx);
881 }
882
883 void
client_expect_confirm(struct ssh * ssh,int id,const char * request,enum confirm_action action)884 client_expect_confirm(struct ssh *ssh, int id, const char *request,
885 enum confirm_action action)
886 {
887 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
888
889 cr->request_type = request;
890 cr->action = action;
891
892 channel_register_status_confirm(ssh, id, client_status_confirm,
893 client_abandon_status_confirm, cr);
894 }
895
896 void
client_register_global_confirm(global_confirm_cb * cb,void * ctx)897 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
898 {
899 struct global_confirm *gc, *last_gc;
900
901 /* Coalesce identical callbacks */
902 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
903 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
904 if (++last_gc->ref_count >= INT_MAX)
905 fatal_f("last_gc->ref_count = %d",
906 last_gc->ref_count);
907 return;
908 }
909
910 gc = xcalloc(1, sizeof(*gc));
911 gc->cb = cb;
912 gc->ctx = ctx;
913 gc->ref_count = 1;
914 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
915 }
916
917 /*
918 * Returns non-zero if the client is able to handle a hostkeys-00@openssh.com
919 * hostkey update request.
920 */
921 static int
can_update_hostkeys(void)922 can_update_hostkeys(void)
923 {
924 if (hostkeys_update_complete)
925 return 0;
926 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
927 options.batch_mode)
928 return 0; /* won't ask in batchmode, so don't even try */
929 if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
930 return 0;
931 return 1;
932 }
933
934 static void
client_repledge(void)935 client_repledge(void)
936 {
937 debug3_f("enter");
938
939 /* Might be able to tighten pledge now that session is established */
940 if (options.control_master || options.control_path != NULL ||
941 options.forward_x11 || options.fork_after_authentication ||
942 can_update_hostkeys() ||
943 (session_ident != -1 && !session_setup_complete)) {
944 /* Can't tighten */
945 return;
946 }
947 #ifdef __OpenBSD__
948 /*
949 * LocalCommand and UpdateHostkeys have finished, so can get rid of
950 * filesystem.
951 *
952 * XXX protocol allows a server can to change hostkeys during the
953 * connection at rekey time that could trigger a hostkeys update
954 * but AFAIK no implementations support this. Could improve by
955 * forcing known_hosts to be read-only or via unveil(2).
956 */
957 if (options.num_local_forwards != 0 ||
958 options.num_remote_forwards != 0 ||
959 options.num_permitted_remote_opens != 0 ||
960 options.enable_escape_commandline != 0) {
961 /* rfwd needs inet */
962 debug("pledge: network");
963 if (pledge("stdio unix inet dns proc tty", NULL) == -1)
964 fatal_f("pledge(): %s", strerror(errno));
965 } else if (options.forward_agent != 0) {
966 /* agent forwarding needs to open $SSH_AUTH_SOCK at will */
967 debug("pledge: agent");
968 if (pledge("stdio unix proc tty", NULL) == -1)
969 fatal_f("pledge(): %s", strerror(errno));
970 } else {
971 debug("pledge: fork");
972 if (pledge("stdio proc tty", NULL) == -1)
973 fatal_f("pledge(): %s", strerror(errno));
974 }
975 #endif
976 /* XXX further things to do:
977 *
978 * - might be able to get rid of proc if we kill ~^Z
979 * - ssh -N (no session)
980 * - stdio forwarding
981 * - sessions without tty
982 */
983 }
984
985 static void
process_cmdline(struct ssh * ssh)986 process_cmdline(struct ssh *ssh)
987 {
988 void (*handler)(int);
989 char *s, *cmd;
990 int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
991 struct Forward fwd;
992
993 memset(&fwd, 0, sizeof(fwd));
994
995 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
996 handler = ssh_signal(SIGINT, SIG_IGN);
997 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
998 if (s == NULL)
999 goto out;
1000 while (isspace((u_char)*s))
1001 s++;
1002 if (*s == '-')
1003 s++; /* Skip cmdline '-', if any */
1004 if (*s == '\0')
1005 goto out;
1006
1007 if (*s == 'h' || *s == 'H' || *s == '?') {
1008 logit("Commands:");
1009 logit(" -L[bind_address:]port:host:hostport "
1010 "Request local forward");
1011 logit(" -R[bind_address:]port:host:hostport "
1012 "Request remote forward");
1013 logit(" -D[bind_address:]port "
1014 "Request dynamic forward");
1015 logit(" -KL[bind_address:]port "
1016 "Cancel local forward");
1017 logit(" -KR[bind_address:]port "
1018 "Cancel remote forward");
1019 logit(" -KD[bind_address:]port "
1020 "Cancel dynamic forward");
1021 if (!options.permit_local_command)
1022 goto out;
1023 logit(" !args "
1024 "Execute local command");
1025 goto out;
1026 }
1027
1028 if (*s == '!' && options.permit_local_command) {
1029 s++;
1030 ssh_local_cmd(s);
1031 goto out;
1032 }
1033
1034 if (*s == 'K') {
1035 delete = 1;
1036 s++;
1037 }
1038 if (*s == 'L')
1039 local = 1;
1040 else if (*s == 'R')
1041 remote = 1;
1042 else if (*s == 'D')
1043 dynamic = 1;
1044 else {
1045 logit("Invalid command.");
1046 goto out;
1047 }
1048
1049 while (isspace((u_char)*++s))
1050 ;
1051
1052 /* XXX update list of forwards in options */
1053 if (delete) {
1054 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
1055 if (!parse_forward(&fwd, s, 1, 0)) {
1056 logit("Bad forwarding close specification.");
1057 goto out;
1058 }
1059 if (remote)
1060 ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
1061 else if (dynamic)
1062 ok = channel_cancel_lport_listener(ssh, &fwd,
1063 0, &options.fwd_opts) > 0;
1064 else
1065 ok = channel_cancel_lport_listener(ssh, &fwd,
1066 CHANNEL_CANCEL_PORT_STATIC,
1067 &options.fwd_opts) > 0;
1068 if (!ok) {
1069 logit("Unknown port forwarding.");
1070 goto out;
1071 }
1072 logit("Canceled forwarding.");
1073 } else {
1074 /* -R specs can be both dynamic or not, so check both. */
1075 if (remote) {
1076 if (!parse_forward(&fwd, s, 0, remote) &&
1077 !parse_forward(&fwd, s, 1, remote)) {
1078 logit("Bad remote forwarding specification.");
1079 goto out;
1080 }
1081 } else if (!parse_forward(&fwd, s, dynamic, remote)) {
1082 logit("Bad local forwarding specification.");
1083 goto out;
1084 }
1085 if (local || dynamic) {
1086 if (!channel_setup_local_fwd_listener(ssh, &fwd,
1087 &options.fwd_opts)) {
1088 logit("Port forwarding failed.");
1089 goto out;
1090 }
1091 } else {
1092 if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
1093 logit("Port forwarding failed.");
1094 goto out;
1095 }
1096 }
1097 logit("Forwarding port.");
1098 }
1099
1100 out:
1101 ssh_signal(SIGINT, handler);
1102 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1103 free(cmd);
1104 free(fwd.listen_host);
1105 free(fwd.listen_path);
1106 free(fwd.connect_host);
1107 free(fwd.connect_path);
1108 }
1109
1110 /* reasons to suppress output of an escape command in help output */
1111 #define SUPPRESS_NEVER 0 /* never suppress, always show */
1112 #define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */
1113 #define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */
1114 #define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */
1115 #define SUPPRESS_NOCMDLINE 8 /* don't show when cmdline disabled*/
1116 struct escape_help_text {
1117 const char *cmd;
1118 const char *text;
1119 unsigned int flags;
1120 };
1121 static struct escape_help_text esc_txt[] = {
1122 {".", "terminate session", SUPPRESS_MUXMASTER},
1123 {".", "terminate connection (and any multiplexed sessions)",
1124 SUPPRESS_MUXCLIENT},
1125 {"B", "send a BREAK to the remote system", SUPPRESS_NEVER},
1126 {"C", "open a command line", SUPPRESS_MUXCLIENT|SUPPRESS_NOCMDLINE},
1127 {"R", "request rekey", SUPPRESS_NEVER},
1128 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1129 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
1130 {"#", "list forwarded connections", SUPPRESS_NEVER},
1131 {"&", "background ssh (when waiting for connections to terminate)",
1132 SUPPRESS_MUXCLIENT},
1133 {"?", "this message", SUPPRESS_NEVER},
1134 };
1135
1136 static void
print_escape_help(struct sshbuf * b,int escape_char,int mux_client,int using_stderr)1137 print_escape_help(struct sshbuf *b, int escape_char, int mux_client,
1138 int using_stderr)
1139 {
1140 unsigned int i, suppress_flags;
1141 int r;
1142
1143 if ((r = sshbuf_putf(b,
1144 "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0)
1145 fatal_fr(r, "sshbuf_putf");
1146
1147 suppress_flags =
1148 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
1149 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1150 (using_stderr ? 0 : SUPPRESS_SYSLOG) |
1151 (options.enable_escape_commandline == 0 ? SUPPRESS_NOCMDLINE : 0);
1152
1153 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
1154 if (esc_txt[i].flags & suppress_flags)
1155 continue;
1156 if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n",
1157 escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0)
1158 fatal_fr(r, "sshbuf_putf");
1159 }
1160
1161 if ((r = sshbuf_putf(b,
1162 " %c%c - send the escape character by typing it twice\r\n"
1163 "(Note that escapes are only recognized immediately after "
1164 "newline.)\r\n", escape_char, escape_char)) != 0)
1165 fatal_fr(r, "sshbuf_putf");
1166 }
1167
1168 /*
1169 * Process the characters one by one.
1170 */
1171 static int
process_escapes(struct ssh * ssh,Channel * c,struct sshbuf * bin,struct sshbuf * bout,struct sshbuf * berr,const char * buf,int len)1172 process_escapes(struct ssh *ssh, Channel *c,
1173 struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr,
1174 const char *buf, int len)
1175 {
1176 pid_t pid;
1177 int r, bytes = 0;
1178 u_int i;
1179 u_char ch;
1180 char *s;
1181 struct escape_filter_ctx *efc;
1182
1183 if (c == NULL || c->filter_ctx == NULL || len <= 0)
1184 return 0;
1185
1186 efc = (struct escape_filter_ctx *)c->filter_ctx;
1187
1188 for (i = 0; i < (u_int)len; i++) {
1189 /* Get one character at a time. */
1190 ch = buf[i];
1191
1192 if (efc->escape_pending) {
1193 /* We have previously seen an escape character. */
1194 /* Clear the flag now. */
1195 efc->escape_pending = 0;
1196
1197 /* Process the escaped character. */
1198 switch (ch) {
1199 case '.':
1200 /* Terminate the connection. */
1201 if ((r = sshbuf_putf(berr, "%c.\r\n",
1202 efc->escape_char)) != 0)
1203 fatal_fr(r, "sshbuf_putf");
1204 if (c && c->ctl_chan != -1) {
1205 channel_force_close(ssh, c, 1);
1206 return 0;
1207 } else
1208 quit_pending = 1;
1209 return -1;
1210
1211 case 'Z' - 64:
1212 /* XXX support this for mux clients */
1213 if (c && c->ctl_chan != -1) {
1214 char b[16];
1215 noescape:
1216 if (ch == 'Z' - 64)
1217 snprintf(b, sizeof b, "^Z");
1218 else
1219 snprintf(b, sizeof b, "%c", ch);
1220 if ((r = sshbuf_putf(berr,
1221 "%c%s escape not available to "
1222 "multiplexed sessions\r\n",
1223 efc->escape_char, b)) != 0)
1224 fatal_fr(r, "sshbuf_putf");
1225 continue;
1226 }
1227 /* Suspend the program. Inform the user */
1228 if ((r = sshbuf_putf(berr,
1229 "%c^Z [suspend ssh]\r\n",
1230 efc->escape_char)) != 0)
1231 fatal_fr(r, "sshbuf_putf");
1232
1233 /* Restore terminal modes and suspend. */
1234 client_suspend_self(bin, bout, berr);
1235
1236 /* We have been continued. */
1237 continue;
1238
1239 case 'B':
1240 if ((r = sshbuf_putf(berr,
1241 "%cB\r\n", efc->escape_char)) != 0)
1242 fatal_fr(r, "sshbuf_putf");
1243 channel_request_start(ssh, c->self, "break", 0);
1244 if ((r = sshpkt_put_u32(ssh, 1000)) != 0 ||
1245 (r = sshpkt_send(ssh)) != 0)
1246 fatal_fr(r, "send packet");
1247 continue;
1248
1249 case 'R':
1250 if (ssh->compat & SSH_BUG_NOREKEY)
1251 logit("Server does not "
1252 "support re-keying");
1253 else
1254 need_rekeying = 1;
1255 continue;
1256
1257 case 'V':
1258 /* FALLTHROUGH */
1259 case 'v':
1260 if (c && c->ctl_chan != -1)
1261 goto noescape;
1262 if (!log_is_on_stderr()) {
1263 if ((r = sshbuf_putf(berr,
1264 "%c%c [Logging to syslog]\r\n",
1265 efc->escape_char, ch)) != 0)
1266 fatal_fr(r, "sshbuf_putf");
1267 continue;
1268 }
1269 if (ch == 'V' && options.log_level >
1270 SYSLOG_LEVEL_QUIET)
1271 log_change_level(--options.log_level);
1272 if (ch == 'v' && options.log_level <
1273 SYSLOG_LEVEL_DEBUG3)
1274 log_change_level(++options.log_level);
1275 if ((r = sshbuf_putf(berr,
1276 "%c%c [LogLevel %s]\r\n",
1277 efc->escape_char, ch,
1278 log_level_name(options.log_level))) != 0)
1279 fatal_fr(r, "sshbuf_putf");
1280 continue;
1281
1282 case '&':
1283 if (c->ctl_chan != -1)
1284 goto noescape;
1285 /*
1286 * Detach the program (continue to serve
1287 * connections, but put in background and no
1288 * more new connections).
1289 */
1290 /* Restore tty modes. */
1291 leave_raw_mode(
1292 options.request_tty == REQUEST_TTY_FORCE);
1293
1294 /* Stop listening for new connections. */
1295 channel_stop_listening(ssh);
1296
1297 if ((r = sshbuf_putf(berr, "%c& "
1298 "[backgrounded]\n", efc->escape_char)) != 0)
1299 fatal_fr(r, "sshbuf_putf");
1300
1301 /* Fork into background. */
1302 pid = fork();
1303 if (pid == -1) {
1304 error("fork: %.100s", strerror(errno));
1305 continue;
1306 }
1307 if (pid != 0) { /* This is the parent. */
1308 /* The parent just exits. */
1309 exit(0);
1310 }
1311 /* The child continues serving connections. */
1312 /* fake EOF on stdin */
1313 if ((r = sshbuf_put_u8(bin, 4)) != 0)
1314 fatal_fr(r, "sshbuf_put_u8");
1315 return -1;
1316 case '?':
1317 print_escape_help(berr, efc->escape_char,
1318 (c && c->ctl_chan != -1),
1319 log_is_on_stderr());
1320 continue;
1321
1322 case '#':
1323 if ((r = sshbuf_putf(berr, "%c#\r\n",
1324 efc->escape_char)) != 0)
1325 fatal_fr(r, "sshbuf_putf");
1326 s = channel_open_message(ssh);
1327 if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
1328 fatal_fr(r, "sshbuf_put");
1329 free(s);
1330 continue;
1331
1332 case 'C':
1333 if (c && c->ctl_chan != -1)
1334 goto noescape;
1335 if (options.enable_escape_commandline == 0) {
1336 if ((r = sshbuf_putf(berr,
1337 "commandline disabled\r\n")) != 0)
1338 fatal_fr(r, "sshbuf_putf");
1339 continue;
1340 }
1341 process_cmdline(ssh);
1342 continue;
1343
1344 default:
1345 if (ch != efc->escape_char) {
1346 if ((r = sshbuf_put_u8(bin,
1347 efc->escape_char)) != 0)
1348 fatal_fr(r, "sshbuf_put_u8");
1349 bytes++;
1350 }
1351 /* Escaped characters fall through here */
1352 break;
1353 }
1354 } else {
1355 /*
1356 * The previous character was not an escape char.
1357 * Check if this is an escape.
1358 */
1359 if (last_was_cr && ch == efc->escape_char) {
1360 /*
1361 * It is. Set the flag and continue to
1362 * next character.
1363 */
1364 efc->escape_pending = 1;
1365 continue;
1366 }
1367 }
1368
1369 /*
1370 * Normal character. Record whether it was a newline,
1371 * and append it to the buffer.
1372 */
1373 last_was_cr = (ch == '\r' || ch == '\n');
1374 if ((r = sshbuf_put_u8(bin, ch)) != 0)
1375 fatal_fr(r, "sshbuf_put_u8");
1376 bytes++;
1377 }
1378 return bytes;
1379 }
1380
1381 /*
1382 * Get packets from the connection input buffer, and process them as long as
1383 * there are packets available.
1384 *
1385 * Any unknown packets received during the actual
1386 * session cause the session to terminate. This is
1387 * intended to make debugging easier since no
1388 * confirmations are sent. Any compatible protocol
1389 * extensions must be negotiated during the
1390 * preparatory phase.
1391 */
1392
1393 static void
client_process_buffered_input_packets(struct ssh * ssh)1394 client_process_buffered_input_packets(struct ssh *ssh)
1395 {
1396 ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, &quit_pending);
1397 }
1398
1399 /* scan buf[] for '~' before sending data to the peer */
1400
1401 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1402 void *
client_new_escape_filter_ctx(int escape_char)1403 client_new_escape_filter_ctx(int escape_char)
1404 {
1405 struct escape_filter_ctx *ret;
1406
1407 ret = xcalloc(1, sizeof(*ret));
1408 ret->escape_pending = 0;
1409 ret->escape_char = escape_char;
1410 return (void *)ret;
1411 }
1412
1413 /* Free the escape filter context on channel free */
1414 void
client_filter_cleanup(struct ssh * ssh,int cid,void * ctx)1415 client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
1416 {
1417 free(ctx);
1418 }
1419
1420 int
client_simple_escape_filter(struct ssh * ssh,Channel * c,const char * buf,int len)1421 client_simple_escape_filter(struct ssh *ssh, Channel *c, const char *buf,
1422 int len)
1423 {
1424 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1425 return 0;
1426
1427 return process_escapes(ssh, c, c->input, c->output, c->extended,
1428 buf, len);
1429 }
1430
1431 static void
client_channel_closed(struct ssh * ssh,int id,int force,void * arg)1432 client_channel_closed(struct ssh *ssh, int id, int force, void *arg)
1433 {
1434 channel_cancel_cleanup(ssh, id);
1435 session_closed = 1;
1436 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1437 }
1438
1439 /*
1440 * Implements the interactive session with the server. This is called after
1441 * the user has been authenticated, and a command has been started on the
1442 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1443 * used as an escape character for terminating or suspending the session.
1444 */
1445 int
client_loop(struct ssh * ssh,int have_pty,int escape_char_arg,int ssh2_chan_id)1446 client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
1447 int ssh2_chan_id)
1448 {
1449 struct pollfd *pfd = NULL;
1450 u_int npfd_alloc = 0, npfd_active = 0;
1451 double start_time, total_time;
1452 int channel_did_enqueue = 0, r;
1453 u_int64_t ibytes, obytes;
1454 int conn_in_ready, conn_out_ready;
1455 sigset_t bsigset, osigset;
1456
1457 debug("Entering interactive session.");
1458 session_ident = ssh2_chan_id;
1459
1460 #ifdef __OpenBSD__
1461 if (options.control_master &&
1462 !option_clear_or_none(options.control_path)) {
1463 debug("pledge: id");
1464 if (pledge("stdio rpath wpath cpath unix inet dns recvfd sendfd proc exec id tty",
1465 NULL) == -1)
1466 fatal_f("pledge(): %s", strerror(errno));
1467
1468 } else if (options.forward_x11 || options.permit_local_command) {
1469 debug("pledge: exec");
1470 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1471 NULL) == -1)
1472 fatal_f("pledge(): %s", strerror(errno));
1473
1474 } else if (options.update_hostkeys) {
1475 debug("pledge: filesystem");
1476 if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1477 NULL) == -1)
1478 fatal_f("pledge(): %s", strerror(errno));
1479
1480 } else if (!option_clear_or_none(options.proxy_command) ||
1481 options.fork_after_authentication) {
1482 debug("pledge: proc");
1483 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1484 fatal_f("pledge(): %s", strerror(errno));
1485
1486 } else {
1487 debug("pledge: network");
1488 if (pledge("stdio unix inet dns proc tty", NULL) == -1)
1489 fatal_f("pledge(): %s", strerror(errno));
1490 }
1491 #endif
1492
1493 /* might be able to tighten now */
1494 client_repledge();
1495
1496 start_time = monotime_double();
1497
1498 /* Initialize variables. */
1499 last_was_cr = 1;
1500 exit_status = -1;
1501 connection_in = ssh_packet_get_connection_in(ssh);
1502 connection_out = ssh_packet_get_connection_out(ssh);
1503
1504 quit_pending = 0;
1505
1506 client_init_dispatch(ssh);
1507
1508 /*
1509 * Set signal handlers, (e.g. to restore non-blocking mode)
1510 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1511 */
1512 if (ssh_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1513 ssh_signal(SIGHUP, signal_handler);
1514 if (ssh_signal(SIGINT, SIG_IGN) != SIG_IGN)
1515 ssh_signal(SIGINT, signal_handler);
1516 if (ssh_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1517 ssh_signal(SIGQUIT, signal_handler);
1518 if (ssh_signal(SIGTERM, SIG_IGN) != SIG_IGN)
1519 ssh_signal(SIGTERM, signal_handler);
1520 ssh_signal(SIGWINCH, window_change_handler);
1521
1522 if (have_pty)
1523 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1524
1525 if (session_ident != -1) {
1526 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1527 channel_register_filter(ssh, session_ident,
1528 client_simple_escape_filter, NULL,
1529 client_filter_cleanup,
1530 client_new_escape_filter_ctx(
1531 escape_char_arg));
1532 }
1533 channel_register_cleanup(ssh, session_ident,
1534 client_channel_closed, 0);
1535 }
1536
1537 schedule_server_alive_check();
1538
1539 if (sigemptyset(&bsigset) == -1 ||
1540 sigaddset(&bsigset, SIGHUP) == -1 ||
1541 sigaddset(&bsigset, SIGINT) == -1 ||
1542 sigaddset(&bsigset, SIGQUIT) == -1 ||
1543 sigaddset(&bsigset, SIGTERM) == -1)
1544 error_f("bsigset setup: %s", strerror(errno));
1545
1546 /* Main loop of the client for the interactive session mode. */
1547 while (!quit_pending) {
1548 channel_did_enqueue = 0;
1549
1550 /* Process buffered packets sent by the server. */
1551 client_process_buffered_input_packets(ssh);
1552
1553 if (session_closed && !channel_still_open(ssh))
1554 break;
1555
1556 if (ssh_packet_is_rekeying(ssh)) {
1557 debug("rekeying in progress");
1558 } else if (need_rekeying) {
1559 /* manual rekey request */
1560 debug("need rekeying");
1561 if ((r = kex_start_rekex(ssh)) != 0)
1562 fatal_fr(r, "kex_start_rekex");
1563 need_rekeying = 0;
1564 } else {
1565 /*
1566 * Make packets from buffered channel data, and
1567 * enqueue them for sending to the server.
1568 */
1569 if (ssh_packet_not_very_much_data_to_write(ssh))
1570 channel_did_enqueue = channel_output_poll(ssh);
1571
1572 /*
1573 * Check if the window size has changed, and buffer a
1574 * message about it to the server if so.
1575 */
1576 client_check_window_change(ssh);
1577 }
1578 /*
1579 * Wait until we have something to do (something becomes
1580 * available on one of the descriptors).
1581 */
1582 if (sigprocmask(SIG_BLOCK, &bsigset, &osigset) == -1)
1583 error_f("bsigset sigprocmask: %s", strerror(errno));
1584 if (quit_pending)
1585 break;
1586 client_wait_until_can_do_something(ssh, &pfd, &npfd_alloc,
1587 &npfd_active, channel_did_enqueue, &osigset,
1588 &conn_in_ready, &conn_out_ready);
1589 if (sigprocmask(SIG_SETMASK, &osigset, NULL) == -1)
1590 error_f("osigset sigprocmask: %s", strerror(errno));
1591
1592 if (quit_pending)
1593 break;
1594
1595 /* Do channel operations. */
1596 channel_after_poll(ssh, pfd, npfd_active);
1597
1598 /* Buffer input from the connection. */
1599 if (conn_in_ready)
1600 client_process_net_input(ssh);
1601
1602 if (quit_pending)
1603 break;
1604
1605 /* A timeout may have triggered rekeying */
1606 if ((r = ssh_packet_check_rekey(ssh)) != 0)
1607 fatal_fr(r, "cannot start rekeying");
1608
1609 /*
1610 * Send as much buffered packet data as possible to the
1611 * sender.
1612 */
1613 if (conn_out_ready) {
1614 if ((r = ssh_packet_write_poll(ssh)) < 0) {
1615 sshpkt_fatal(ssh, r,
1616 "%s: ssh_packet_write_poll", __func__);
1617 }
1618 }
1619
1620 /*
1621 * If we are a backgrounded control master, and the
1622 * timeout has expired without any active client
1623 * connections, then quit.
1624 */
1625 if (control_persist_exit_time > 0) {
1626 if (monotime() >= control_persist_exit_time) {
1627 debug("ControlPersist timeout expired");
1628 break;
1629 }
1630 }
1631 }
1632 free(pfd);
1633
1634 /* Terminate the session. */
1635
1636 /*
1637 * In interactive mode (with pseudo tty) display a message indicating
1638 * that the connection has been closed.
1639 */
1640 if (have_pty && options.log_level >= SYSLOG_LEVEL_INFO)
1641 quit_message("Connection to %s closed.", host);
1642
1643
1644 /* Stop watching for window change. */
1645 ssh_signal(SIGWINCH, SIG_DFL);
1646
1647 if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
1648 (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_BY_APPLICATION)) != 0 ||
1649 (r = sshpkt_put_cstring(ssh, "disconnected by user")) != 0 ||
1650 (r = sshpkt_put_cstring(ssh, "")) != 0 || /* language tag */
1651 (r = sshpkt_send(ssh)) != 0 ||
1652 (r = ssh_packet_write_wait(ssh)) < 0)
1653 fatal_fr(r, "send disconnect");
1654
1655 channel_free_all(ssh);
1656
1657 if (have_pty)
1658 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1659
1660 /*
1661 * If there was no shell or command requested, there will be no remote
1662 * exit status to be returned. In that case, clear error code if the
1663 * connection was deliberately terminated at this end.
1664 */
1665 if (options.session_type == SESSION_TYPE_NONE &&
1666 received_signal == SIGTERM) {
1667 received_signal = 0;
1668 exit_status = 0;
1669 }
1670
1671 if (received_signal) {
1672 verbose("Killed by signal %d.", (int) received_signal);
1673 cleanup_exit(255);
1674 }
1675
1676 /* Report bytes transferred, and transfer rates. */
1677 total_time = monotime_double() - start_time;
1678 ssh_packet_get_bytes(ssh, &ibytes, &obytes);
1679 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1680 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1681 if (total_time > 0)
1682 verbose("Bytes per second: sent %.1f, received %.1f",
1683 obytes / total_time, ibytes / total_time);
1684 /* Return the exit status of the program. */
1685 debug("Exit status %d", exit_status);
1686 return exit_status;
1687 }
1688
1689 /*********/
1690
1691 static Channel *
client_request_forwarded_tcpip(struct ssh * ssh,const char * request_type,int rchan,u_int rwindow,u_int rmaxpack)1692 client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
1693 int rchan, u_int rwindow, u_int rmaxpack)
1694 {
1695 Channel *c = NULL;
1696 struct sshbuf *b = NULL;
1697 char *listen_address, *originator_address;
1698 u_int listen_port, originator_port;
1699 int r;
1700
1701 /* Get rest of the packet */
1702 if ((r = sshpkt_get_cstring(ssh, &listen_address, NULL)) != 0 ||
1703 (r = sshpkt_get_u32(ssh, &listen_port)) != 0 ||
1704 (r = sshpkt_get_cstring(ssh, &originator_address, NULL)) != 0 ||
1705 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1706 (r = sshpkt_get_end(ssh)) != 0)
1707 fatal_fr(r, "parse packet");
1708
1709 debug_f("listen %s port %d, originator %s port %d",
1710 listen_address, listen_port, originator_address, originator_port);
1711
1712 if (listen_port > 0xffff)
1713 error_f("invalid listen port");
1714 else if (originator_port > 0xffff)
1715 error_f("invalid originator port");
1716 else {
1717 c = channel_connect_by_listen_address(ssh,
1718 listen_address, listen_port, "forwarded-tcpip",
1719 originator_address);
1720 }
1721
1722 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1723 if ((b = sshbuf_new()) == NULL) {
1724 error_f("alloc reply");
1725 goto out;
1726 }
1727 /* reconstruct and send to muxclient */
1728 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
1729 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1730 (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1731 (r = sshbuf_put_u32(b, rchan)) != 0 ||
1732 (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1733 (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1734 (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1735 (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1736 (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1737 (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1738 (r = sshbuf_put_stringb(c->output, b)) != 0) {
1739 error_fr(r, "compose for muxclient");
1740 goto out;
1741 }
1742 }
1743
1744 out:
1745 sshbuf_free(b);
1746 free(originator_address);
1747 free(listen_address);
1748 return c;
1749 }
1750
1751 static Channel *
client_request_forwarded_streamlocal(struct ssh * ssh,const char * request_type,int rchan)1752 client_request_forwarded_streamlocal(struct ssh *ssh,
1753 const char *request_type, int rchan)
1754 {
1755 Channel *c = NULL;
1756 char *listen_path;
1757 int r;
1758
1759 /* Get the remote path. */
1760 if ((r = sshpkt_get_cstring(ssh, &listen_path, NULL)) != 0 ||
1761 (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 || /* reserved */
1762 (r = sshpkt_get_end(ssh)) != 0)
1763 fatal_fr(r, "parse packet");
1764
1765 debug_f("request: %s", listen_path);
1766
1767 c = channel_connect_by_listen_path(ssh, listen_path,
1768 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1769 free(listen_path);
1770 return c;
1771 }
1772
1773 static Channel *
client_request_x11(struct ssh * ssh,const char * request_type,int rchan)1774 client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
1775 {
1776 Channel *c = NULL;
1777 char *originator;
1778 u_int originator_port;
1779 int r, sock;
1780
1781 if (!options.forward_x11) {
1782 error("Warning: ssh server tried X11 forwarding.");
1783 error("Warning: this is probably a break-in attempt by a "
1784 "malicious server.");
1785 return NULL;
1786 }
1787 if (x11_refuse_time != 0 && monotime() >= x11_refuse_time) {
1788 verbose("Rejected X11 connection after ForwardX11Timeout "
1789 "expired");
1790 return NULL;
1791 }
1792 if ((r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
1793 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1794 (r = sshpkt_get_end(ssh)) != 0)
1795 fatal_fr(r, "parse packet");
1796 /* XXX check permission */
1797 /* XXX range check originator port? */
1798 debug("client_request_x11: request from %s %u", originator,
1799 originator_port);
1800 free(originator);
1801 sock = x11_connect_display(ssh);
1802 if (sock < 0)
1803 return NULL;
1804 /* again is this really necessary for X11? */
1805 if (options.hpn_disabled)
1806 c = channel_new(ssh, "x11-connection",
1807 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1808 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1809 else
1810 c = channel_new(ssh, "x11-connection",
1811 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1812 options.hpn_buffer_size, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1813 c->force_drain = 1;
1814 return c;
1815 }
1816
1817 static Channel *
client_request_agent(struct ssh * ssh,const char * request_type,int rchan)1818 client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
1819 {
1820 Channel *c = NULL;
1821 int r, sock;
1822
1823 if (!options.forward_agent) {
1824 error("Warning: ssh server tried agent forwarding.");
1825 error("Warning: this is probably a break-in attempt by a "
1826 "malicious server.");
1827 return NULL;
1828 }
1829 if (forward_agent_sock_path == NULL) {
1830 r = ssh_get_authentication_socket(&sock);
1831 } else {
1832 r = ssh_get_authentication_socket_path(forward_agent_sock_path, &sock);
1833 }
1834 if (r != 0) {
1835 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1836 debug_fr(r, "ssh_get_authentication_socket");
1837 return NULL;
1838 }
1839 if ((r = ssh_agent_bind_hostkey(sock, ssh->kex->initial_hostkey,
1840 ssh->kex->session_id, ssh->kex->initial_sig, 1)) == 0)
1841 debug_f("bound agent to hostkey");
1842 else
1843 debug2_fr(r, "ssh_agent_bind_hostkey");
1844
1845 if (options.hpn_disabled)
1846 c = channel_new(ssh, "agent-connection",
1847 SSH_CHANNEL_OPEN, sock, sock, -1,
1848 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1849 "authentication agent connection", 1);
1850 else
1851 c = channel_new(ssh, "agent connection",
1852 SSH_CHANNEL_OPEN, sock, sock, -1,
1853 options.hpn_buffer_size, options.hpn_buffer_size, 0,
1854 "authentication agent connection", 1);
1855 c->force_drain = 1;
1856 return c;
1857 }
1858
1859 char *
client_request_tun_fwd(struct ssh * ssh,int tun_mode,int local_tun,int remote_tun,channel_open_fn * cb,void * cbctx)1860 client_request_tun_fwd(struct ssh *ssh, int tun_mode,
1861 int local_tun, int remote_tun, channel_open_fn *cb, void *cbctx)
1862 {
1863 Channel *c;
1864 int r, fd;
1865 char *ifname = NULL;
1866
1867 if (tun_mode == SSH_TUNMODE_NO)
1868 return 0;
1869
1870 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1871
1872 /* Open local tunnel device */
1873 if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) {
1874 error("Tunnel device open failed.");
1875 return NULL;
1876 }
1877 debug("Tunnel forwarding using interface %s", ifname);
1878
1879 if(options.hpn_disabled)
1880 c = channel_new(ssh, "tun-connection", SSH_CHANNEL_OPENING, fd, fd, -1,
1881 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1882 else
1883 c = channel_new(ssh, "tun-connection", SSH_CHANNEL_OPENING, fd, fd, -1,
1884 options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1885 c->datagram = 1;
1886
1887 if (cb != NULL)
1888 channel_register_open_confirm(ssh, c->self, cb, cbctx);
1889
1890 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1891 (r = sshpkt_put_cstring(ssh, "tun@openssh.com")) != 0 ||
1892 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1893 (r = sshpkt_put_u32(ssh, c->local_window_max)) != 0 ||
1894 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1895 (r = sshpkt_put_u32(ssh, tun_mode)) != 0 ||
1896 (r = sshpkt_put_u32(ssh, remote_tun)) != 0 ||
1897 (r = sshpkt_send(ssh)) != 0)
1898 sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1899
1900 return ifname;
1901 }
1902
1903 /* XXXX move to generic input handler */
1904 static int
client_input_channel_open(int type,u_int32_t seq,struct ssh * ssh)1905 client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
1906 {
1907 Channel *c = NULL;
1908 char *ctype = NULL;
1909 int r;
1910 u_int rchan;
1911 size_t len;
1912 u_int rmaxpack, rwindow;
1913
1914 if ((r = sshpkt_get_cstring(ssh, &ctype, &len)) != 0 ||
1915 (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
1916 (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
1917 (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
1918 goto out;
1919
1920 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1921 ctype, rchan, rwindow, rmaxpack);
1922
1923 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1924 c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1925 rmaxpack);
1926 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1927 c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
1928 } else if (strcmp(ctype, "x11") == 0) {
1929 c = client_request_x11(ssh, ctype, rchan);
1930 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1931 c = client_request_agent(ssh, ctype, rchan);
1932 }
1933 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1934 debug3("proxied to downstream: %s", ctype);
1935 } else if (c != NULL) {
1936 debug("confirm %s", ctype);
1937 c->remote_id = rchan;
1938 c->have_remote_id = 1;
1939 c->remote_window = rwindow;
1940 c->remote_maxpacket = rmaxpack;
1941 if (c->type != SSH_CHANNEL_CONNECTING) {
1942 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1943 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1944 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1945 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1946 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1947 (r = sshpkt_send(ssh)) != 0)
1948 sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1949 }
1950 } else {
1951 debug("failure %s", ctype);
1952 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1953 (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
1954 (r = sshpkt_put_u32(ssh, SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED)) != 0 ||
1955 (r = sshpkt_put_cstring(ssh, "open failed")) != 0 ||
1956 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1957 (r = sshpkt_send(ssh)) != 0)
1958 sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1959 }
1960 r = 0;
1961 out:
1962 free(ctype);
1963 return r;
1964 }
1965
1966 static int
client_input_channel_req(int type,u_int32_t seq,struct ssh * ssh)1967 client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
1968 {
1969 Channel *c = NULL;
1970 char *rtype = NULL;
1971 u_char reply;
1972 u_int id, exitval;
1973 int r, success = 0;
1974
1975 if ((r = sshpkt_get_u32(ssh, &id)) != 0)
1976 return r;
1977 if (id <= INT_MAX)
1978 c = channel_lookup(ssh, id);
1979 if (channel_proxy_upstream(c, type, seq, ssh))
1980 return 0;
1981 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
1982 (r = sshpkt_get_u8(ssh, &reply)) != 0)
1983 goto out;
1984
1985 debug("client_input_channel_req: channel %u rtype %s reply %d",
1986 id, rtype, reply);
1987
1988 if (c == NULL) {
1989 error("client_input_channel_req: channel %d: "
1990 "unknown channel", id);
1991 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1992 if ((r = sshpkt_get_end(ssh)) != 0)
1993 goto out;
1994 chan_rcvd_eow(ssh, c);
1995 } else if (strcmp(rtype, "exit-status") == 0) {
1996 if ((r = sshpkt_get_u32(ssh, &exitval)) != 0)
1997 goto out;
1998 if (c->ctl_chan != -1) {
1999 mux_exit_message(ssh, c, exitval);
2000 success = 1;
2001 } else if ((int)id == session_ident) {
2002 /* Record exit value of local session */
2003 success = 1;
2004 exit_status = exitval;
2005 } else {
2006 /* Probably for a mux channel that has already closed */
2007 debug_f("no sink for exit-status on channel %d",
2008 id);
2009 }
2010 if ((r = sshpkt_get_end(ssh)) != 0)
2011 goto out;
2012 }
2013 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
2014 if (!c->have_remote_id)
2015 fatal_f("channel %d: no remote_id", c->self);
2016 if ((r = sshpkt_start(ssh, success ?
2017 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
2018 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2019 (r = sshpkt_send(ssh)) != 0)
2020 sshpkt_fatal(ssh, r, "%s: send failure", __func__);
2021 }
2022 r = 0;
2023 out:
2024 free(rtype);
2025 return r;
2026 }
2027
2028 struct hostkeys_update_ctx {
2029 /* The hostname and (optionally) IP address string for the server */
2030 char *host_str, *ip_str;
2031
2032 /*
2033 * Keys received from the server and a flag for each indicating
2034 * whether they already exist in known_hosts.
2035 * keys_match is filled in by hostkeys_find() and later (for new
2036 * keys) by client_global_hostkeys_prove_confirm().
2037 */
2038 struct sshkey **keys;
2039 u_int *keys_match; /* mask of HKF_MATCH_* from hostfile.h */
2040 int *keys_verified; /* flag for new keys verified by server */
2041 size_t nkeys, nnew, nincomplete; /* total, new keys, incomplete match */
2042
2043 /*
2044 * Keys that are in known_hosts, but were not present in the update
2045 * from the server (i.e. scheduled to be deleted).
2046 * Filled in by hostkeys_find().
2047 */
2048 struct sshkey **old_keys;
2049 size_t nold;
2050
2051 /* Various special cases. */
2052 int complex_hostspec; /* wildcard or manual pattern-list host name */
2053 int ca_available; /* saw CA key for this host */
2054 int old_key_seen; /* saw old key with other name/addr */
2055 int other_name_seen; /* saw key with other name/addr */
2056 };
2057
2058 static void
hostkeys_update_ctx_free(struct hostkeys_update_ctx * ctx)2059 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
2060 {
2061 size_t i;
2062
2063 if (ctx == NULL)
2064 return;
2065 for (i = 0; i < ctx->nkeys; i++)
2066 sshkey_free(ctx->keys[i]);
2067 free(ctx->keys);
2068 free(ctx->keys_match);
2069 free(ctx->keys_verified);
2070 for (i = 0; i < ctx->nold; i++)
2071 sshkey_free(ctx->old_keys[i]);
2072 free(ctx->old_keys);
2073 free(ctx->host_str);
2074 free(ctx->ip_str);
2075 free(ctx);
2076 }
2077
2078 /*
2079 * Returns non-zero if a known_hosts hostname list is not of a form that
2080 * can be handled by UpdateHostkeys. These include wildcard hostnames and
2081 * hostnames lists that do not follow the form host[,ip].
2082 */
2083 static int
hostspec_is_complex(const char * hosts)2084 hostspec_is_complex(const char *hosts)
2085 {
2086 char *cp;
2087
2088 /* wildcard */
2089 if (strchr(hosts, '*') != NULL || strchr(hosts, '?') != NULL)
2090 return 1;
2091 /* single host/ip = ok */
2092 if ((cp = strchr(hosts, ',')) == NULL)
2093 return 0;
2094 /* more than two entries on the line */
2095 if (strchr(cp + 1, ',') != NULL)
2096 return 1;
2097 /* XXX maybe parse cp+1 and ensure it is an IP? */
2098 return 0;
2099 }
2100
2101 /* callback to search for ctx->keys in known_hosts */
2102 static int
hostkeys_find(struct hostkey_foreach_line * l,void * _ctx)2103 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
2104 {
2105 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2106 size_t i;
2107 struct sshkey **tmp;
2108
2109 if (l->key == NULL)
2110 return 0;
2111 if (l->status != HKF_STATUS_MATCHED) {
2112 /* Record if one of the keys appears on a non-matching line */
2113 for (i = 0; i < ctx->nkeys; i++) {
2114 if (sshkey_equal(l->key, ctx->keys[i])) {
2115 ctx->other_name_seen = 1;
2116 debug3_f("found %s key under different "
2117 "name/addr at %s:%ld",
2118 sshkey_ssh_name(ctx->keys[i]),
2119 l->path, l->linenum);
2120 return 0;
2121 }
2122 }
2123 return 0;
2124 }
2125 /* Don't proceed if revocation or CA markers are present */
2126 /* XXX relax this */
2127 if (l->marker != MRK_NONE) {
2128 debug3_f("hostkeys file %s:%ld has CA/revocation marker",
2129 l->path, l->linenum);
2130 ctx->complex_hostspec = 1;
2131 return 0;
2132 }
2133
2134 /* If CheckHostIP is enabled, then check for mismatched hostname/addr */
2135 if (ctx->ip_str != NULL && strchr(l->hosts, ',') != NULL) {
2136 if ((l->match & HKF_MATCH_HOST) == 0) {
2137 /* Record if address matched a different hostname. */
2138 ctx->other_name_seen = 1;
2139 debug3_f("found address %s against different hostname "
2140 "at %s:%ld", ctx->ip_str, l->path, l->linenum);
2141 return 0;
2142 } else if ((l->match & HKF_MATCH_IP) == 0) {
2143 /* Record if hostname matched a different address. */
2144 ctx->other_name_seen = 1;
2145 debug3_f("found hostname %s against different address "
2146 "at %s:%ld", ctx->host_str, l->path, l->linenum);
2147 }
2148 }
2149
2150 /*
2151 * UpdateHostkeys is skipped for wildcard host names and hostnames
2152 * that contain more than two entries (ssh never writes these).
2153 */
2154 if (hostspec_is_complex(l->hosts)) {
2155 debug3_f("hostkeys file %s:%ld complex host specification",
2156 l->path, l->linenum);
2157 ctx->complex_hostspec = 1;
2158 return 0;
2159 }
2160
2161 /* Mark off keys we've already seen for this host */
2162 for (i = 0; i < ctx->nkeys; i++) {
2163 if (!sshkey_equal(l->key, ctx->keys[i]))
2164 continue;
2165 debug3_f("found %s key at %s:%ld",
2166 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
2167 ctx->keys_match[i] |= l->match;
2168 return 0;
2169 }
2170 /* This line contained a key that not offered by the server */
2171 debug3_f("deprecated %s key at %s:%ld", sshkey_ssh_name(l->key),
2172 l->path, l->linenum);
2173 if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
2174 sizeof(*ctx->old_keys))) == NULL)
2175 fatal_f("recallocarray failed nold = %zu", ctx->nold);
2176 ctx->old_keys = tmp;
2177 ctx->old_keys[ctx->nold++] = l->key;
2178 l->key = NULL;
2179
2180 return 0;
2181 }
2182
2183 /* callback to search for ctx->old_keys in known_hosts under other names */
2184 static int
hostkeys_check_old(struct hostkey_foreach_line * l,void * _ctx)2185 hostkeys_check_old(struct hostkey_foreach_line *l, void *_ctx)
2186 {
2187 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2188 size_t i;
2189 int hashed;
2190
2191 /* only care about lines that *don't* match the active host spec */
2192 if (l->status == HKF_STATUS_MATCHED || l->key == NULL)
2193 return 0;
2194
2195 hashed = l->match & (HKF_MATCH_HOST_HASHED|HKF_MATCH_IP_HASHED);
2196 for (i = 0; i < ctx->nold; i++) {
2197 if (!sshkey_equal(l->key, ctx->old_keys[i]))
2198 continue;
2199 debug3_f("found deprecated %s key at %s:%ld as %s",
2200 sshkey_ssh_name(ctx->old_keys[i]), l->path, l->linenum,
2201 hashed ? "[HASHED]" : l->hosts);
2202 ctx->old_key_seen = 1;
2203 break;
2204 }
2205 return 0;
2206 }
2207
2208 /*
2209 * Check known_hosts files for deprecated keys under other names. Returns 0
2210 * on success or -1 on failure. Updates ctx->old_key_seen if deprecated keys
2211 * exist under names other than the active hostname/IP.
2212 */
2213 static int
check_old_keys_othernames(struct hostkeys_update_ctx * ctx)2214 check_old_keys_othernames(struct hostkeys_update_ctx *ctx)
2215 {
2216 size_t i;
2217 int r;
2218
2219 debug2_f("checking for %zu deprecated keys", ctx->nold);
2220 for (i = 0; i < options.num_user_hostfiles; i++) {
2221 debug3_f("searching %s for %s / %s",
2222 options.user_hostfiles[i], ctx->host_str,
2223 ctx->ip_str ? ctx->ip_str : "(none)");
2224 if ((r = hostkeys_foreach(options.user_hostfiles[i],
2225 hostkeys_check_old, ctx, ctx->host_str, ctx->ip_str,
2226 HKF_WANT_PARSE_KEY, 0)) != 0) {
2227 if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
2228 debug_f("hostkeys file %s does not exist",
2229 options.user_hostfiles[i]);
2230 continue;
2231 }
2232 error_fr(r, "hostkeys_foreach failed for %s",
2233 options.user_hostfiles[i]);
2234 return -1;
2235 }
2236 }
2237 return 0;
2238 }
2239
2240 static void
hostkey_change_preamble(LogLevel loglevel)2241 hostkey_change_preamble(LogLevel loglevel)
2242 {
2243 do_log2(loglevel, "The server has updated its host keys.");
2244 do_log2(loglevel, "These changes were verified by the server's "
2245 "existing trusted key.");
2246 }
2247
2248 static void
update_known_hosts(struct hostkeys_update_ctx * ctx)2249 update_known_hosts(struct hostkeys_update_ctx *ctx)
2250 {
2251 int r, was_raw = 0, first = 1;
2252 int asking = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK;
2253 LogLevel loglevel = asking ? SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
2254 char *fp, *response;
2255 size_t i;
2256 struct stat sb;
2257
2258 for (i = 0; i < ctx->nkeys; i++) {
2259 if (!ctx->keys_verified[i])
2260 continue;
2261 if ((fp = sshkey_fingerprint(ctx->keys[i],
2262 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2263 fatal_f("sshkey_fingerprint failed");
2264 if (first && asking)
2265 hostkey_change_preamble(loglevel);
2266 do_log2(loglevel, "Learned new hostkey: %s %s",
2267 sshkey_type(ctx->keys[i]), fp);
2268 first = 0;
2269 free(fp);
2270 }
2271 for (i = 0; i < ctx->nold; i++) {
2272 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
2273 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2274 fatal_f("sshkey_fingerprint failed");
2275 if (first && asking)
2276 hostkey_change_preamble(loglevel);
2277 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
2278 sshkey_type(ctx->old_keys[i]), fp);
2279 first = 0;
2280 free(fp);
2281 }
2282 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
2283 if (get_saved_tio() != NULL) {
2284 leave_raw_mode(1);
2285 was_raw = 1;
2286 }
2287 response = NULL;
2288 for (i = 0; !quit_pending && i < 3; i++) {
2289 free(response);
2290 response = read_passphrase("Accept updated hostkeys? "
2291 "(yes/no): ", RP_ECHO);
2292 if (response != NULL && strcasecmp(response, "yes") == 0)
2293 break;
2294 else if (quit_pending || response == NULL ||
2295 strcasecmp(response, "no") == 0) {
2296 options.update_hostkeys = 0;
2297 break;
2298 } else {
2299 do_log2(loglevel, "Please enter "
2300 "\"yes\" or \"no\"");
2301 }
2302 }
2303 if (quit_pending || i >= 3 || response == NULL)
2304 options.update_hostkeys = 0;
2305 free(response);
2306 if (was_raw)
2307 enter_raw_mode(1);
2308 }
2309 if (options.update_hostkeys == 0)
2310 return;
2311 /*
2312 * Now that all the keys are verified, we can go ahead and replace
2313 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
2314 * cancel the operation).
2315 */
2316 for (i = 0; i < options.num_user_hostfiles; i++) {
2317 /*
2318 * NB. keys are only added to hostfiles[0], for the rest we
2319 * just delete the hostname entries.
2320 */
2321 if (stat(options.user_hostfiles[i], &sb) != 0) {
2322 if (errno == ENOENT) {
2323 debug_f("known hosts file %s does not "
2324 "exist", options.user_hostfiles[i]);
2325 } else {
2326 error_f("known hosts file %s "
2327 "inaccessible: %s",
2328 options.user_hostfiles[i], strerror(errno));
2329 }
2330 continue;
2331 }
2332 if ((r = hostfile_replace_entries(options.user_hostfiles[i],
2333 ctx->host_str, ctx->ip_str,
2334 i == 0 ? ctx->keys : NULL, i == 0 ? ctx->nkeys : 0,
2335 options.hash_known_hosts, 0,
2336 options.fingerprint_hash)) != 0) {
2337 error_fr(r, "hostfile_replace_entries failed for %s",
2338 options.user_hostfiles[i]);
2339 }
2340 }
2341 }
2342
2343 static void
client_global_hostkeys_prove_confirm(struct ssh * ssh,int type,u_int32_t seq,void * _ctx)2344 client_global_hostkeys_prove_confirm(struct ssh *ssh, int type,
2345 u_int32_t seq, void *_ctx)
2346 {
2347 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2348 size_t i, ndone;
2349 struct sshbuf *signdata;
2350 int r, plaintype;
2351 const u_char *sig;
2352 const char *rsa_kexalg = NULL;
2353 char *alg = NULL;
2354 size_t siglen;
2355
2356 if (ctx->nnew == 0)
2357 fatal_f("ctx->nnew == 0"); /* sanity */
2358 if (type != SSH2_MSG_REQUEST_SUCCESS) {
2359 error("Server failed to confirm ownership of "
2360 "private host keys");
2361 hostkeys_update_ctx_free(ctx);
2362 return;
2363 }
2364 if (sshkey_type_plain(sshkey_type_from_name(
2365 ssh->kex->hostkey_alg)) == KEY_RSA)
2366 rsa_kexalg = ssh->kex->hostkey_alg;
2367 if ((signdata = sshbuf_new()) == NULL)
2368 fatal_f("sshbuf_new failed");
2369 /*
2370 * Expect a signature for each of the ctx->nnew private keys we
2371 * haven't seen before. They will be in the same order as the
2372 * ctx->keys where the corresponding ctx->keys_match[i] == 0.
2373 */
2374 for (ndone = i = 0; i < ctx->nkeys; i++) {
2375 if (ctx->keys_match[i])
2376 continue;
2377 plaintype = sshkey_type_plain(ctx->keys[i]->type);
2378 /* Prepare data to be signed: session ID, unique string, key */
2379 sshbuf_reset(signdata);
2380 if ( (r = sshbuf_put_cstring(signdata,
2381 "hostkeys-prove-00@openssh.com")) != 0 ||
2382 (r = sshbuf_put_stringb(signdata,
2383 ssh->kex->session_id)) != 0 ||
2384 (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
2385 fatal_fr(r, "compose signdata");
2386 /* Extract and verify signature */
2387 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
2388 error_fr(r, "parse sig");
2389 goto out;
2390 }
2391 if ((r = sshkey_get_sigtype(sig, siglen, &alg)) != 0) {
2392 error_fr(r, "server gave unintelligible signature "
2393 "for %s key %zu", sshkey_type(ctx->keys[i]), i);
2394 goto out;
2395 }
2396 /*
2397 * Special case for RSA keys: if a RSA hostkey was negotiated,
2398 * then use its signature type for verification of RSA hostkey
2399 * proofs. Otherwise, accept only RSA-SHA256/512 signatures.
2400 */
2401 if (plaintype == KEY_RSA && rsa_kexalg == NULL &&
2402 match_pattern_list(alg, HOSTKEY_PROOF_RSA_ALGS, 0) != 1) {
2403 debug_f("server used untrusted RSA signature algorithm "
2404 "%s for key %zu, disregarding", alg, i);
2405 free(alg);
2406 /* zap the key from the list */
2407 sshkey_free(ctx->keys[i]);
2408 ctx->keys[i] = NULL;
2409 ndone++;
2410 continue;
2411 }
2412 debug3_f("verify %s key %zu using sigalg %s",
2413 sshkey_type(ctx->keys[i]), i, alg);
2414 free(alg);
2415 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
2416 sshbuf_ptr(signdata), sshbuf_len(signdata),
2417 plaintype == KEY_RSA ? rsa_kexalg : NULL, 0, NULL)) != 0) {
2418 error_fr(r, "server gave bad signature for %s key %zu",
2419 sshkey_type(ctx->keys[i]), i);
2420 goto out;
2421 }
2422 /* Key is good. Mark it as 'seen' */
2423 ctx->keys_verified[i] = 1;
2424 ndone++;
2425 }
2426 /* Shouldn't happen */
2427 if (ndone != ctx->nnew)
2428 fatal_f("ndone != ctx->nnew (%zu / %zu)", ndone, ctx->nnew);
2429 if ((r = sshpkt_get_end(ssh)) != 0) {
2430 error_f("protocol error");
2431 goto out;
2432 }
2433
2434 /* Make the edits to known_hosts */
2435 update_known_hosts(ctx);
2436 out:
2437 hostkeys_update_ctx_free(ctx);
2438 hostkeys_update_complete = 1;
2439 client_repledge();
2440 }
2441
2442 /*
2443 * Handle hostkeys-00@openssh.com global request to inform the client of all
2444 * the server's hostkeys. The keys are checked against the user's
2445 * HostkeyAlgorithms preference before they are accepted.
2446 */
2447 static int
client_input_hostkeys(struct ssh * ssh)2448 client_input_hostkeys(struct ssh *ssh)
2449 {
2450 const u_char *blob = NULL;
2451 size_t i, len = 0;
2452 struct sshbuf *buf = NULL;
2453 struct sshkey *key = NULL, **tmp;
2454 int r, prove_sent = 0;
2455 char *fp;
2456 static int hostkeys_seen = 0; /* XXX use struct ssh */
2457 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
2458 struct hostkeys_update_ctx *ctx = NULL;
2459 u_int want;
2460
2461 if (hostkeys_seen)
2462 fatal_f("server already sent hostkeys");
2463 if (!can_update_hostkeys())
2464 return 1;
2465 hostkeys_seen = 1;
2466
2467 ctx = xcalloc(1, sizeof(*ctx));
2468 while (ssh_packet_remaining(ssh) > 0) {
2469 sshkey_free(key);
2470 key = NULL;
2471 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2472 error_fr(r, "parse key");
2473 goto out;
2474 }
2475 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2476 do_log2_fr(r, r == SSH_ERR_KEY_TYPE_UNKNOWN ?
2477 SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_ERROR,
2478 "convert key");
2479 continue;
2480 }
2481 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2482 SSH_FP_DEFAULT);
2483 debug3_f("received %s key %s", sshkey_type(key), fp);
2484 free(fp);
2485
2486 if (!hostkey_accepted_by_hostkeyalgs(key)) {
2487 debug3_f("%s key not permitted by "
2488 "HostkeyAlgorithms", sshkey_ssh_name(key));
2489 continue;
2490 }
2491 /* Skip certs */
2492 if (sshkey_is_cert(key)) {
2493 debug3_f("%s key is a certificate; skipping",
2494 sshkey_ssh_name(key));
2495 continue;
2496 }
2497 /* Ensure keys are unique */
2498 for (i = 0; i < ctx->nkeys; i++) {
2499 if (sshkey_equal(key, ctx->keys[i])) {
2500 error_f("received duplicated %s host key",
2501 sshkey_ssh_name(key));
2502 goto out;
2503 }
2504 }
2505 /* Key is good, record it */
2506 if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
2507 sizeof(*ctx->keys))) == NULL)
2508 fatal_f("recallocarray failed nkeys = %zu",
2509 ctx->nkeys);
2510 ctx->keys = tmp;
2511 ctx->keys[ctx->nkeys++] = key;
2512 key = NULL;
2513 }
2514
2515 if (ctx->nkeys == 0) {
2516 debug_f("server sent no hostkeys");
2517 goto out;
2518 }
2519
2520 if ((ctx->keys_match = calloc(ctx->nkeys,
2521 sizeof(*ctx->keys_match))) == NULL ||
2522 (ctx->keys_verified = calloc(ctx->nkeys,
2523 sizeof(*ctx->keys_verified))) == NULL)
2524 fatal_f("calloc failed");
2525
2526 get_hostfile_hostname_ipaddr(host,
2527 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2528 options.port, &ctx->host_str,
2529 options.check_host_ip ? &ctx->ip_str : NULL);
2530
2531 /* Find which keys we already know about. */
2532 for (i = 0; i < options.num_user_hostfiles; i++) {
2533 debug_f("searching %s for %s / %s",
2534 options.user_hostfiles[i], ctx->host_str,
2535 ctx->ip_str ? ctx->ip_str : "(none)");
2536 if ((r = hostkeys_foreach(options.user_hostfiles[i],
2537 hostkeys_find, ctx, ctx->host_str, ctx->ip_str,
2538 HKF_WANT_PARSE_KEY, 0)) != 0) {
2539 if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
2540 debug_f("hostkeys file %s does not exist",
2541 options.user_hostfiles[i]);
2542 continue;
2543 }
2544 error_fr(r, "hostkeys_foreach failed for %s",
2545 options.user_hostfiles[i]);
2546 goto out;
2547 }
2548 }
2549
2550 /* Figure out if we have any new keys to add */
2551 ctx->nnew = ctx->nincomplete = 0;
2552 want = HKF_MATCH_HOST | ( options.check_host_ip ? HKF_MATCH_IP : 0);
2553 for (i = 0; i < ctx->nkeys; i++) {
2554 if (ctx->keys_match[i] == 0)
2555 ctx->nnew++;
2556 if ((ctx->keys_match[i] & want) != want)
2557 ctx->nincomplete++;
2558 }
2559
2560 debug3_f("%zu server keys: %zu new, %zu retained, "
2561 "%zu incomplete match. %zu to remove", ctx->nkeys, ctx->nnew,
2562 ctx->nkeys - ctx->nnew - ctx->nincomplete,
2563 ctx->nincomplete, ctx->nold);
2564
2565 if (ctx->nnew == 0 && ctx->nold == 0) {
2566 debug_f("no new or deprecated keys from server");
2567 goto out;
2568 }
2569
2570 /* Various reasons why we cannot proceed with the update */
2571 if (ctx->complex_hostspec) {
2572 debug_f("CA/revocation marker, manual host list or wildcard "
2573 "host pattern found, skipping UserKnownHostsFile update");
2574 goto out;
2575 }
2576 if (ctx->other_name_seen) {
2577 debug_f("host key found matching a different name/address, "
2578 "skipping UserKnownHostsFile update");
2579 goto out;
2580 }
2581 /*
2582 * If removing keys, check whether they appear under different
2583 * names/addresses and refuse to proceed if they do. This avoids
2584 * cases such as hosts with multiple names becoming inconsistent
2585 * with regards to CheckHostIP entries.
2586 * XXX UpdateHostkeys=force to override this (and other) checks?
2587 */
2588 if (ctx->nold != 0) {
2589 if (check_old_keys_othernames(ctx) != 0)
2590 goto out; /* error already logged */
2591 if (ctx->old_key_seen) {
2592 debug_f("key(s) for %s%s%s exist under other names; "
2593 "skipping UserKnownHostsFile update",
2594 ctx->host_str, ctx->ip_str == NULL ? "" : ",",
2595 ctx->ip_str == NULL ? "" : ctx->ip_str);
2596 goto out;
2597 }
2598 }
2599
2600 if (ctx->nnew == 0) {
2601 /*
2602 * We have some keys to remove or fix matching for.
2603 * We can proceed to do this without requiring a fresh proof
2604 * from the server.
2605 */
2606 update_known_hosts(ctx);
2607 goto out;
2608 }
2609 /*
2610 * We have received previously-unseen keys from the server.
2611 * Ask the server to confirm ownership of the private halves.
2612 */
2613 debug3_f("asking server to prove ownership for %zu keys", ctx->nnew);
2614 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2615 (r = sshpkt_put_cstring(ssh,
2616 "hostkeys-prove-00@openssh.com")) != 0 ||
2617 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2618 fatal_fr(r, "prepare hostkeys-prove");
2619 if ((buf = sshbuf_new()) == NULL)
2620 fatal_f("sshbuf_new");
2621 for (i = 0; i < ctx->nkeys; i++) {
2622 if (ctx->keys_match[i])
2623 continue;
2624 sshbuf_reset(buf);
2625 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0 ||
2626 (r = sshpkt_put_stringb(ssh, buf)) != 0)
2627 fatal_fr(r, "assemble hostkeys-prove");
2628 }
2629 if ((r = sshpkt_send(ssh)) != 0)
2630 fatal_fr(r, "send hostkeys-prove");
2631 client_register_global_confirm(
2632 client_global_hostkeys_prove_confirm, ctx);
2633 ctx = NULL; /* will be freed in callback */
2634 prove_sent = 1;
2635
2636 /* Success */
2637 out:
2638 hostkeys_update_ctx_free(ctx);
2639 sshkey_free(key);
2640 sshbuf_free(buf);
2641 if (!prove_sent) {
2642 /* UpdateHostkeys handling completed */
2643 hostkeys_update_complete = 1;
2644 client_repledge();
2645 }
2646 /*
2647 * NB. Return success for all cases. The server doesn't need to know
2648 * what the client does with its hosts file.
2649 */
2650 return 1;
2651 }
2652
2653 static int
client_input_global_request(int type,u_int32_t seq,struct ssh * ssh)2654 client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
2655 {
2656 char *rtype;
2657 u_char want_reply;
2658 int r, success = 0;
2659
2660 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
2661 (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
2662 goto out;
2663 debug("client_input_global_request: rtype %s want_reply %d",
2664 rtype, want_reply);
2665 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2666 success = client_input_hostkeys(ssh);
2667 if (want_reply) {
2668 if ((r = sshpkt_start(ssh, success ? SSH2_MSG_REQUEST_SUCCESS :
2669 SSH2_MSG_REQUEST_FAILURE)) != 0 ||
2670 (r = sshpkt_send(ssh)) != 0 ||
2671 (r = ssh_packet_write_wait(ssh)) != 0)
2672 goto out;
2673 }
2674 r = 0;
2675 out:
2676 free(rtype);
2677 return r;
2678 }
2679
2680 static void
client_send_env(struct ssh * ssh,int id,const char * name,const char * val)2681 client_send_env(struct ssh *ssh, int id, const char *name, const char *val)
2682 {
2683 int r;
2684
2685 debug("channel %d: setting env %s = \"%s\"", id, name, val);
2686 channel_request_start(ssh, id, "env", 0);
2687 if ((r = sshpkt_put_cstring(ssh, name)) != 0 ||
2688 (r = sshpkt_put_cstring(ssh, val)) != 0 ||
2689 (r = sshpkt_send(ssh)) != 0)
2690 fatal_fr(r, "send setenv");
2691 }
2692
2693 void
client_session2_setup(struct ssh * ssh,int id,int want_tty,int want_subsystem,const char * term,struct termios * tiop,int in_fd,struct sshbuf * cmd,char ** env)2694 client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
2695 const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd,
2696 char **env)
2697 {
2698 size_t i, j, len;
2699 int matched, r;
2700 char *name, *val;
2701 Channel *c = NULL;
2702
2703 debug2_f("id %d", id);
2704
2705 if ((c = channel_lookup(ssh, id)) == NULL)
2706 fatal_f("channel %d: unknown channel", id);
2707
2708 ssh_packet_set_interactive(ssh, want_tty,
2709 options.ip_qos_interactive, options.ip_qos_bulk);
2710
2711 if (want_tty) {
2712 struct winsize ws;
2713
2714 /* Store window size in the packet. */
2715 if (ioctl(in_fd, TIOCGWINSZ, &ws) == -1)
2716 memset(&ws, 0, sizeof(ws));
2717
2718 channel_request_start(ssh, id, "pty-req", 1);
2719 client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
2720 if ((r = sshpkt_put_cstring(ssh, term != NULL ? term : ""))
2721 != 0 ||
2722 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
2723 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
2724 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
2725 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0)
2726 fatal_fr(r, "build pty-req");
2727 if (tiop == NULL)
2728 tiop = get_saved_tio();
2729 ssh_tty_make_modes(ssh, -1, tiop);
2730 if ((r = sshpkt_send(ssh)) != 0)
2731 fatal_fr(r, "send pty-req");
2732 /* XXX wait for reply */
2733 c->client_tty = 1;
2734 }
2735
2736 /* Transfer any environment variables from client to server */
2737 if (options.num_send_env != 0 && env != NULL) {
2738 debug("Sending environment.");
2739 for (i = 0; env[i] != NULL; i++) {
2740 /* Split */
2741 name = xstrdup(env[i]);
2742 if ((val = strchr(name, '=')) == NULL) {
2743 free(name);
2744 continue;
2745 }
2746 *val++ = '\0';
2747
2748 matched = 0;
2749 for (j = 0; j < options.num_send_env; j++) {
2750 if (match_pattern(name, options.send_env[j])) {
2751 matched = 1;
2752 break;
2753 }
2754 }
2755 if (!matched) {
2756 debug3("Ignored env %s", name);
2757 free(name);
2758 continue;
2759 }
2760 client_send_env(ssh, id, name, val);
2761 free(name);
2762 }
2763 }
2764 for (i = 0; i < options.num_setenv; i++) {
2765 /* Split */
2766 name = xstrdup(options.setenv[i]);
2767 if ((val = strchr(name, '=')) == NULL) {
2768 free(name);
2769 continue;
2770 }
2771 *val++ = '\0';
2772 client_send_env(ssh, id, name, val);
2773 free(name);
2774 }
2775
2776 len = sshbuf_len(cmd);
2777 if (len > 0) {
2778 if (len > 900)
2779 len = 900;
2780 if (want_subsystem) {
2781 debug("Sending subsystem: %.*s",
2782 (int)len, (const u_char*)sshbuf_ptr(cmd));
2783 channel_request_start(ssh, id, "subsystem", 1);
2784 client_expect_confirm(ssh, id, "subsystem",
2785 CONFIRM_CLOSE);
2786 } else {
2787 debug("Sending command: %.*s",
2788 (int)len, (const u_char*)sshbuf_ptr(cmd));
2789 channel_request_start(ssh, id, "exec", 1);
2790 client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
2791 }
2792 if ((r = sshpkt_put_stringb(ssh, cmd)) != 0 ||
2793 (r = sshpkt_send(ssh)) != 0)
2794 fatal_fr(r, "send command");
2795 } else {
2796 channel_request_start(ssh, id, "shell", 1);
2797 client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
2798 if ((r = sshpkt_send(ssh)) != 0)
2799 fatal_fr(r, "send shell");
2800 }
2801
2802 session_setup_complete = 1;
2803 client_repledge();
2804 }
2805
2806 static void
client_init_dispatch(struct ssh * ssh)2807 client_init_dispatch(struct ssh *ssh)
2808 {
2809 ssh_dispatch_init(ssh, &dispatch_protocol_error);
2810
2811 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2812 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2813 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2814 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2815 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2816 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2817 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2818 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2819 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2820 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2821 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2822 ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2823
2824 /* rekeying */
2825 ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
2826
2827 /* global request reply messages */
2828 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2829 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2830 }
2831
2832 void
client_stop_mux(void)2833 client_stop_mux(void)
2834 {
2835 if (options.control_path != NULL && muxserver_sock != -1)
2836 unlink(options.control_path);
2837 /*
2838 * If we are in persist mode, or don't have a shell, signal that we
2839 * should close when all active channels are closed.
2840 */
2841 if (options.control_persist || options.session_type == SESSION_TYPE_NONE) {
2842 session_closed = 1;
2843 setproctitle("[stopped mux]");
2844 }
2845 }
2846
2847 /* client specific fatal cleanup */
2848 void
cleanup_exit(int i)2849 cleanup_exit(int i)
2850 {
2851 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2852 if (options.control_path != NULL && muxserver_sock != -1)
2853 unlink(options.control_path);
2854 ssh_kill_proxy_command();
2855 _exit(i);
2856 }
2857