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