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