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