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