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