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