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