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