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