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