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