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