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