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