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