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