xref: /dflybsd-src/crypto/openssh/clientloop.c (revision ba1276acd1c8c22d225b1bcf370a14c878644f44)
1*ba1276acSMatthew Dillon /* $OpenBSD: clientloop.c,v 1.408 2024/07/01 04:31:17 djm Exp $ */
218de8d7fSPeter Avalos /*
318de8d7fSPeter Avalos  * Author: Tatu Ylonen <ylo@cs.hut.fi>
418de8d7fSPeter Avalos  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
518de8d7fSPeter Avalos  *                    All rights reserved
618de8d7fSPeter Avalos  * The main loop for the interactive session (client side).
718de8d7fSPeter Avalos  *
818de8d7fSPeter Avalos  * As far as I am concerned, the code I have written for this software
918de8d7fSPeter Avalos  * can be used freely for any purpose.  Any derived versions of this
1018de8d7fSPeter Avalos  * software must be clearly marked as such, and if the derived work is
1118de8d7fSPeter Avalos  * incompatible with the protocol description in the RFC file, it must be
1218de8d7fSPeter Avalos  * called by a name other than "ssh" or "Secure Shell".
1318de8d7fSPeter Avalos  *
1418de8d7fSPeter Avalos  *
1518de8d7fSPeter Avalos  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
1618de8d7fSPeter Avalos  *
1718de8d7fSPeter Avalos  * Redistribution and use in source and binary forms, with or without
1818de8d7fSPeter Avalos  * modification, are permitted provided that the following conditions
1918de8d7fSPeter Avalos  * are met:
2018de8d7fSPeter Avalos  * 1. Redistributions of source code must retain the above copyright
2118de8d7fSPeter Avalos  *    notice, this list of conditions and the following disclaimer.
2218de8d7fSPeter Avalos  * 2. Redistributions in binary form must reproduce the above copyright
2318de8d7fSPeter Avalos  *    notice, this list of conditions and the following disclaimer in the
2418de8d7fSPeter Avalos  *    documentation and/or other materials provided with the distribution.
2518de8d7fSPeter Avalos  *
2618de8d7fSPeter Avalos  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
2718de8d7fSPeter Avalos  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
2818de8d7fSPeter Avalos  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
2918de8d7fSPeter Avalos  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
3018de8d7fSPeter Avalos  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
3118de8d7fSPeter Avalos  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3218de8d7fSPeter Avalos  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3318de8d7fSPeter Avalos  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3418de8d7fSPeter Avalos  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
3518de8d7fSPeter Avalos  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3618de8d7fSPeter Avalos  *
3718de8d7fSPeter Avalos  *
3818de8d7fSPeter Avalos  * SSH2 support added by Markus Friedl.
3918de8d7fSPeter Avalos  * Copyright (c) 1999, 2000, 2001 Markus Friedl.  All rights reserved.
4018de8d7fSPeter Avalos  *
4118de8d7fSPeter Avalos  * Redistribution and use in source and binary forms, with or without
4218de8d7fSPeter Avalos  * modification, are permitted provided that the following conditions
4318de8d7fSPeter Avalos  * are met:
4418de8d7fSPeter Avalos  * 1. Redistributions of source code must retain the above copyright
4518de8d7fSPeter Avalos  *    notice, this list of conditions and the following disclaimer.
4618de8d7fSPeter Avalos  * 2. Redistributions in binary form must reproduce the above copyright
4718de8d7fSPeter Avalos  *    notice, this list of conditions and the following disclaimer in the
4818de8d7fSPeter Avalos  *    documentation and/or other materials provided with the distribution.
4918de8d7fSPeter Avalos  *
5018de8d7fSPeter Avalos  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
5118de8d7fSPeter Avalos  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
5218de8d7fSPeter Avalos  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
5318de8d7fSPeter Avalos  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
5418de8d7fSPeter Avalos  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
5518de8d7fSPeter Avalos  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5618de8d7fSPeter Avalos  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5718de8d7fSPeter Avalos  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5818de8d7fSPeter Avalos  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
5918de8d7fSPeter Avalos  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6018de8d7fSPeter Avalos  */
6118de8d7fSPeter Avalos 
6218de8d7fSPeter Avalos #include "includes.h"
6318de8d7fSPeter Avalos 
6418de8d7fSPeter Avalos #include <sys/types.h>
6518de8d7fSPeter Avalos #include <sys/ioctl.h>
6618de8d7fSPeter Avalos #ifdef HAVE_SYS_STAT_H
6718de8d7fSPeter Avalos # include <sys/stat.h>
6818de8d7fSPeter Avalos #endif
6918de8d7fSPeter Avalos #ifdef HAVE_SYS_TIME_H
7018de8d7fSPeter Avalos # include <sys/time.h>
7118de8d7fSPeter Avalos #endif
7218de8d7fSPeter Avalos #include <sys/socket.h>
7318de8d7fSPeter Avalos 
7418de8d7fSPeter Avalos #include <ctype.h>
7518de8d7fSPeter Avalos #include <errno.h>
7618de8d7fSPeter Avalos #ifdef HAVE_PATHS_H
7718de8d7fSPeter Avalos #include <paths.h>
7818de8d7fSPeter Avalos #endif
79ee116499SAntonio Huete Jimenez #ifdef HAVE_POLL_H
80ee116499SAntonio Huete Jimenez #include <poll.h>
81ee116499SAntonio Huete Jimenez #endif
8218de8d7fSPeter Avalos #include <signal.h>
8318de8d7fSPeter Avalos #include <stdio.h>
8418de8d7fSPeter Avalos #include <stdlib.h>
8518de8d7fSPeter Avalos #include <string.h>
860cbfa66cSDaniel Fojt #include <stdarg.h>
8718de8d7fSPeter Avalos #include <termios.h>
8818de8d7fSPeter Avalos #include <pwd.h>
8918de8d7fSPeter Avalos #include <unistd.h>
90e9778795SPeter Avalos #include <limits.h>
9118de8d7fSPeter Avalos 
9218de8d7fSPeter Avalos #include "openbsd-compat/sys-queue.h"
9318de8d7fSPeter Avalos #include "xmalloc.h"
9418de8d7fSPeter Avalos #include "ssh.h"
9518de8d7fSPeter Avalos #include "ssh2.h"
9618de8d7fSPeter Avalos #include "packet.h"
97664f4763Szrj #include "sshbuf.h"
9818de8d7fSPeter Avalos #include "compat.h"
9918de8d7fSPeter Avalos #include "channels.h"
10018de8d7fSPeter Avalos #include "dispatch.h"
101664f4763Szrj #include "sshkey.h"
10218de8d7fSPeter Avalos #include "cipher.h"
10318de8d7fSPeter Avalos #include "kex.h"
104e9778795SPeter Avalos #include "myproposal.h"
10518de8d7fSPeter Avalos #include "log.h"
10636e94dc5SPeter Avalos #include "misc.h"
10718de8d7fSPeter Avalos #include "readconf.h"
10818de8d7fSPeter Avalos #include "clientloop.h"
10918de8d7fSPeter Avalos #include "sshconnect.h"
11018de8d7fSPeter Avalos #include "authfd.h"
11118de8d7fSPeter Avalos #include "atomicio.h"
11218de8d7fSPeter Avalos #include "sshpty.h"
11318de8d7fSPeter Avalos #include "match.h"
11418de8d7fSPeter Avalos #include "msg.h"
115e9778795SPeter Avalos #include "ssherr.h"
116e9778795SPeter Avalos #include "hostfile.h"
11718de8d7fSPeter Avalos 
118ee116499SAntonio Huete Jimenez /* Permitted RSA signature algorithms for UpdateHostkeys proofs */
119ee116499SAntonio Huete Jimenez #define HOSTKEY_PROOF_RSA_ALGS	"rsa-sha2-512,rsa-sha2-256"
120ee116499SAntonio Huete Jimenez 
121*ba1276acSMatthew Dillon /* Uncertainty (in percent) of keystroke timing intervals */
122*ba1276acSMatthew Dillon #define SSH_KEYSTROKE_TIMING_FUZZ 10
123*ba1276acSMatthew Dillon 
12418de8d7fSPeter Avalos /* import options */
12518de8d7fSPeter Avalos extern Options options;
12618de8d7fSPeter Avalos 
12718de8d7fSPeter Avalos /* Control socket */
128856ea928SPeter Avalos extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
12918de8d7fSPeter Avalos 
13018de8d7fSPeter Avalos /*
13118de8d7fSPeter Avalos  * Name of the host we are connecting to.  This is the name given on the
1320cbfa66cSDaniel Fojt  * command line, or the Hostname specified for the user-supplied name in a
13318de8d7fSPeter Avalos  * configuration file.
13418de8d7fSPeter Avalos  */
13518de8d7fSPeter Avalos extern char *host;
13618de8d7fSPeter Avalos 
13718de8d7fSPeter Avalos /*
1380cbfa66cSDaniel Fojt  * If this field is not NULL, the ForwardAgent socket is this path and different
1390cbfa66cSDaniel Fojt  * instead of SSH_AUTH_SOCK.
1400cbfa66cSDaniel Fojt  */
1410cbfa66cSDaniel Fojt extern char *forward_agent_sock_path;
1420cbfa66cSDaniel Fojt 
1430cbfa66cSDaniel Fojt /*
14418de8d7fSPeter Avalos  * Flag to indicate that we have received a window change signal which has
14518de8d7fSPeter Avalos  * not yet been processed.  This will cause a message indicating the new
14618de8d7fSPeter Avalos  * window size to be sent to the server a little later.  This is volatile
14718de8d7fSPeter Avalos  * because this is updated in a signal handler.
14818de8d7fSPeter Avalos  */
14918de8d7fSPeter Avalos static volatile sig_atomic_t received_window_change_signal = 0;
15018de8d7fSPeter Avalos static volatile sig_atomic_t received_signal = 0;
15118de8d7fSPeter Avalos 
152856ea928SPeter Avalos /* Time when backgrounded control master using ControlPersist should exit */
153856ea928SPeter Avalos static time_t control_persist_exit_time = 0;
154856ea928SPeter Avalos 
15518de8d7fSPeter Avalos /* Common data for the client loop code. */
156856ea928SPeter Avalos volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
15718de8d7fSPeter Avalos static int last_was_cr;		/* Last character was a newline. */
15818de8d7fSPeter Avalos static int exit_status;		/* Used to store the command exit status. */
15918de8d7fSPeter Avalos static int connection_in;	/* Connection to server (input). */
16018de8d7fSPeter Avalos static int connection_out;	/* Connection to server (output). */
16118de8d7fSPeter Avalos static int need_rekeying;	/* Set to non-zero if rekeying is requested. */
162856ea928SPeter Avalos static int session_closed;	/* In SSH2: login session closed. */
163*ba1276acSMatthew Dillon static time_t x11_refuse_time;	/* If >0, refuse x11 opens after this time. */
16450a69bb5SSascha Wildner static time_t server_alive_time;	/* Time to do server_alive_check */
165*ba1276acSMatthew Dillon static int hostkeys_update_complete;
166*ba1276acSMatthew Dillon static int session_setup_complete;
16718de8d7fSPeter Avalos 
168664f4763Szrj static void client_init_dispatch(struct ssh *ssh);
16918de8d7fSPeter Avalos int	session_ident = -1;
17018de8d7fSPeter Avalos 
17118de8d7fSPeter Avalos /* Track escape per proto2 channel */
17218de8d7fSPeter Avalos struct escape_filter_ctx {
17318de8d7fSPeter Avalos 	int escape_pending;
17418de8d7fSPeter Avalos 	int escape_char;
17518de8d7fSPeter Avalos };
17618de8d7fSPeter Avalos 
17718de8d7fSPeter Avalos /* Context for channel confirmation replies */
17818de8d7fSPeter Avalos struct channel_reply_ctx {
17918de8d7fSPeter Avalos 	const char *request_type;
1801c188a7fSPeter Avalos 	int id;
1811c188a7fSPeter Avalos 	enum confirm_action action;
18218de8d7fSPeter Avalos };
18318de8d7fSPeter Avalos 
18418de8d7fSPeter Avalos /* Global request success/failure callbacks */
185ce74bacaSMatthew Dillon /* XXX move to struct ssh? */
18618de8d7fSPeter Avalos struct global_confirm {
18718de8d7fSPeter Avalos 	TAILQ_ENTRY(global_confirm) entry;
18818de8d7fSPeter Avalos 	global_confirm_cb *cb;
18918de8d7fSPeter Avalos 	void *ctx;
19018de8d7fSPeter Avalos 	int ref_count;
19118de8d7fSPeter Avalos };
19218de8d7fSPeter Avalos TAILQ_HEAD(global_confirms, global_confirm);
19318de8d7fSPeter Avalos static struct global_confirms global_confirms =
19418de8d7fSPeter Avalos     TAILQ_HEAD_INITIALIZER(global_confirms);
19518de8d7fSPeter Avalos 
196ee116499SAntonio Huete Jimenez static void quit_message(const char *fmt, ...)
197ee116499SAntonio Huete Jimenez     __attribute__((__format__ (printf, 1, 2)));
198ee116499SAntonio Huete Jimenez 
199ee116499SAntonio Huete Jimenez static void
quit_message(const char * fmt,...)200ee116499SAntonio Huete Jimenez quit_message(const char *fmt, ...)
201ee116499SAntonio Huete Jimenez {
202*ba1276acSMatthew Dillon 	char *msg, *fmt2;
203ee116499SAntonio Huete Jimenez 	va_list args;
204*ba1276acSMatthew Dillon 	xasprintf(&fmt2, "%s\r\n", fmt);
205ee116499SAntonio Huete Jimenez 
206ee116499SAntonio Huete Jimenez 	va_start(args, fmt);
207*ba1276acSMatthew Dillon 	xvasprintf(&msg, fmt2, args);
208ee116499SAntonio Huete Jimenez 	va_end(args);
209ee116499SAntonio Huete Jimenez 
210*ba1276acSMatthew Dillon 	(void)atomicio(vwrite, STDERR_FILENO, msg, strlen(msg));
211*ba1276acSMatthew Dillon 	free(msg);
212*ba1276acSMatthew Dillon 	free(fmt2);
213*ba1276acSMatthew Dillon 
214ee116499SAntonio Huete Jimenez 	quit_pending = 1;
215ee116499SAntonio Huete Jimenez }
21618de8d7fSPeter Avalos 
21718de8d7fSPeter Avalos /*
21818de8d7fSPeter Avalos  * Signal handler for the window change signal (SIGWINCH).  This just sets a
21918de8d7fSPeter Avalos  * flag indicating that the window has changed.
22018de8d7fSPeter Avalos  */
22118de8d7fSPeter Avalos static void
window_change_handler(int sig)22218de8d7fSPeter Avalos window_change_handler(int sig)
22318de8d7fSPeter Avalos {
22418de8d7fSPeter Avalos 	received_window_change_signal = 1;
22518de8d7fSPeter Avalos }
22618de8d7fSPeter Avalos 
22718de8d7fSPeter Avalos /*
22818de8d7fSPeter Avalos  * Signal handler for signals that cause the program to terminate.  These
22918de8d7fSPeter Avalos  * signals must be trapped to restore terminal modes.
23018de8d7fSPeter Avalos  */
23118de8d7fSPeter Avalos static void
signal_handler(int sig)23218de8d7fSPeter Avalos signal_handler(int sig)
23318de8d7fSPeter Avalos {
23418de8d7fSPeter Avalos 	received_signal = sig;
23518de8d7fSPeter Avalos 	quit_pending = 1;
23618de8d7fSPeter Avalos }
23718de8d7fSPeter Avalos 
23818de8d7fSPeter Avalos /*
239856ea928SPeter Avalos  * Sets control_persist_exit_time to the absolute time when the
240856ea928SPeter Avalos  * backgrounded control master should exit due to expiry of the
241856ea928SPeter Avalos  * ControlPersist timeout.  Sets it to 0 if we are not a backgrounded
242856ea928SPeter Avalos  * control master process, or if there is no ControlPersist timeout.
243856ea928SPeter Avalos  */
244856ea928SPeter Avalos static void
set_control_persist_exit_time(struct ssh * ssh)245ce74bacaSMatthew Dillon set_control_persist_exit_time(struct ssh *ssh)
246856ea928SPeter Avalos {
247856ea928SPeter Avalos 	if (muxserver_sock == -1 || !options.control_persist
2481c188a7fSPeter Avalos 	    || options.control_persist_timeout == 0) {
249856ea928SPeter Avalos 		/* not using a ControlPersist timeout */
250856ea928SPeter Avalos 		control_persist_exit_time = 0;
251ce74bacaSMatthew Dillon 	} else if (channel_still_open(ssh)) {
252856ea928SPeter Avalos 		/* some client connections are still open */
253856ea928SPeter Avalos 		if (control_persist_exit_time > 0)
25450a69bb5SSascha Wildner 			debug2_f("cancel scheduled exit");
255856ea928SPeter Avalos 		control_persist_exit_time = 0;
256856ea928SPeter Avalos 	} else if (control_persist_exit_time <= 0) {
257856ea928SPeter Avalos 		/* a client connection has recently closed */
25836e94dc5SPeter Avalos 		control_persist_exit_time = monotime() +
259856ea928SPeter Avalos 			(time_t)options.control_persist_timeout;
26050a69bb5SSascha Wildner 		debug2_f("schedule exit in %d seconds",
261856ea928SPeter Avalos 		    options.control_persist_timeout);
262856ea928SPeter Avalos 	}
263856ea928SPeter Avalos 	/* else we are already counting down to the timeout */
264856ea928SPeter Avalos }
265856ea928SPeter Avalos 
26699e85e0dSPeter Avalos #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
26799e85e0dSPeter Avalos static int
client_x11_display_valid(const char * display)26899e85e0dSPeter Avalos client_x11_display_valid(const char *display)
26999e85e0dSPeter Avalos {
27099e85e0dSPeter Avalos 	size_t i, dlen;
27199e85e0dSPeter Avalos 
272e9778795SPeter Avalos 	if (display == NULL)
273e9778795SPeter Avalos 		return 0;
274e9778795SPeter Avalos 
27599e85e0dSPeter Avalos 	dlen = strlen(display);
27699e85e0dSPeter Avalos 	for (i = 0; i < dlen; i++) {
27736e94dc5SPeter Avalos 		if (!isalnum((u_char)display[i]) &&
27899e85e0dSPeter Avalos 		    strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
27999e85e0dSPeter Avalos 			debug("Invalid character '%c' in DISPLAY", display[i]);
28099e85e0dSPeter Avalos 			return 0;
28199e85e0dSPeter Avalos 		}
28299e85e0dSPeter Avalos 	}
28399e85e0dSPeter Avalos 	return 1;
28499e85e0dSPeter Avalos }
28599e85e0dSPeter Avalos 
28618de8d7fSPeter Avalos #define SSH_X11_PROTO		"MIT-MAGIC-COOKIE-1"
287e9778795SPeter Avalos #define X11_TIMEOUT_SLACK	60
288e9778795SPeter Avalos int
client_x11_get_proto(struct ssh * ssh,const char * display,const char * xauth_path,u_int trusted,u_int timeout,char ** _proto,char ** _data)289ce74bacaSMatthew Dillon client_x11_get_proto(struct ssh *ssh, const char *display,
290ce74bacaSMatthew Dillon     const char *xauth_path, u_int trusted, u_int timeout,
291ce74bacaSMatthew Dillon     char **_proto, char **_data)
29218de8d7fSPeter Avalos {
293664f4763Szrj 	char *cmd, line[512], xdisplay[512];
294e9778795SPeter Avalos 	char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
29518de8d7fSPeter Avalos 	static char proto[512], data[512];
29618de8d7fSPeter Avalos 	FILE *f;
297ce74bacaSMatthew Dillon 	int got_data = 0, generated = 0, do_unlink = 0, r;
29818de8d7fSPeter Avalos 	struct stat st;
299e9778795SPeter Avalos 	u_int now, x11_timeout_real;
30018de8d7fSPeter Avalos 
30118de8d7fSPeter Avalos 	*_proto = proto;
30218de8d7fSPeter Avalos 	*_data = data;
303e9778795SPeter Avalos 	proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
30418de8d7fSPeter Avalos 
305e9778795SPeter Avalos 	if (!client_x11_display_valid(display)) {
306e9778795SPeter Avalos 		if (display != NULL)
307e9778795SPeter Avalos 			logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
30899e85e0dSPeter Avalos 			    display);
309e9778795SPeter Avalos 		return -1;
31018de8d7fSPeter Avalos 	}
311e9778795SPeter Avalos 	if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
312e9778795SPeter Avalos 		debug("No xauth program.");
313e9778795SPeter Avalos 		xauth_path = NULL;
314e9778795SPeter Avalos 	}
315e9778795SPeter Avalos 
316e9778795SPeter Avalos 	if (xauth_path != NULL) {
31718de8d7fSPeter Avalos 		/*
31818de8d7fSPeter Avalos 		 * Handle FamilyLocal case where $DISPLAY does
31918de8d7fSPeter Avalos 		 * not match an authorization entry.  For this we
32018de8d7fSPeter Avalos 		 * just try "xauth list unix:displaynum.screennum".
32118de8d7fSPeter Avalos 		 * XXX: "localhost" match to determine FamilyLocal
32218de8d7fSPeter Avalos 		 *      is not perfect.
32318de8d7fSPeter Avalos 		 */
32418de8d7fSPeter Avalos 		if (strncmp(display, "localhost:", 10) == 0) {
325e9778795SPeter Avalos 			if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
326e9778795SPeter Avalos 			    display + 10)) < 0 ||
327e9778795SPeter Avalos 			    (size_t)r >= sizeof(xdisplay)) {
32850a69bb5SSascha Wildner 				error_f("display name too long");
329e9778795SPeter Avalos 				return -1;
330e9778795SPeter Avalos 			}
33118de8d7fSPeter Avalos 			display = xdisplay;
33218de8d7fSPeter Avalos 		}
33318de8d7fSPeter Avalos 		if (trusted == 0) {
334e9778795SPeter Avalos 			/*
335e9778795SPeter Avalos 			 * Generate an untrusted X11 auth cookie.
336e9778795SPeter Avalos 			 *
337e9778795SPeter Avalos 			 * The authentication cookie should briefly outlive
338e9778795SPeter Avalos 			 * ssh's willingness to forward X11 connections to
339e9778795SPeter Avalos 			 * avoid nasty fail-open behaviour in the X server.
340e9778795SPeter Avalos 			 */
341e9778795SPeter Avalos 			mktemp_proto(xauthdir, sizeof(xauthdir));
342e9778795SPeter Avalos 			if (mkdtemp(xauthdir) == NULL) {
34350a69bb5SSascha Wildner 				error_f("mkdtemp: %s", strerror(errno));
344e9778795SPeter Avalos 				return -1;
345e9778795SPeter Avalos 			}
34618de8d7fSPeter Avalos 			do_unlink = 1;
347e9778795SPeter Avalos 			if ((r = snprintf(xauthfile, sizeof(xauthfile),
348e9778795SPeter Avalos 			    "%s/xauthfile", xauthdir)) < 0 ||
349e9778795SPeter Avalos 			    (size_t)r >= sizeof(xauthfile)) {
35050a69bb5SSascha Wildner 				error_f("xauthfile path too long");
351e9778795SPeter Avalos 				rmdir(xauthdir);
352e9778795SPeter Avalos 				return -1;
353e9778795SPeter Avalos 			}
354e9778795SPeter Avalos 
355664f4763Szrj 			if (timeout == 0) {
356664f4763Szrj 				/* auth doesn't time out */
357664f4763Szrj 				xasprintf(&cmd, "%s -f %s generate %s %s "
358664f4763Szrj 				    "untrusted 2>%s",
359e9778795SPeter Avalos 				    xauth_path, xauthfile, display,
360664f4763Szrj 				    SSH_X11_PROTO, _PATH_DEVNULL);
361664f4763Szrj 			} else {
362664f4763Szrj 				/* Add some slack to requested expiry */
363664f4763Szrj 				if (timeout < UINT_MAX - X11_TIMEOUT_SLACK)
364664f4763Szrj 					x11_timeout_real = timeout +
365664f4763Szrj 					    X11_TIMEOUT_SLACK;
366664f4763Szrj 				else {
367664f4763Szrj 					/* Don't overflow on long timeouts */
368664f4763Szrj 					x11_timeout_real = UINT_MAX;
369664f4763Szrj 				}
370664f4763Szrj 				xasprintf(&cmd, "%s -f %s generate %s %s "
371664f4763Szrj 				    "untrusted timeout %u 2>%s",
372664f4763Szrj 				    xauth_path, xauthfile, display,
373664f4763Szrj 				    SSH_X11_PROTO, x11_timeout_real,
374664f4763Szrj 				    _PATH_DEVNULL);
375664f4763Szrj 			}
37650a69bb5SSascha Wildner 			debug2_f("xauth command: %s", cmd);
377664f4763Szrj 
378664f4763Szrj 			if (timeout != 0 && x11_refuse_time == 0) {
37936e94dc5SPeter Avalos 				now = monotime() + 1;
380*ba1276acSMatthew Dillon 				if (SSH_TIME_T_MAX - timeout < now)
381*ba1276acSMatthew Dillon 					x11_refuse_time = SSH_TIME_T_MAX;
382856ea928SPeter Avalos 				else
383856ea928SPeter Avalos 					x11_refuse_time = now + timeout;
384ce74bacaSMatthew Dillon 				channel_set_x11_refuse_time(ssh,
385ce74bacaSMatthew Dillon 				    x11_refuse_time);
386856ea928SPeter Avalos 			}
387e9778795SPeter Avalos 			if (system(cmd) == 0)
388e9778795SPeter Avalos 				generated = 1;
389664f4763Szrj 			free(cmd);
39018de8d7fSPeter Avalos 		}
39118de8d7fSPeter Avalos 
39218de8d7fSPeter Avalos 		/*
39318de8d7fSPeter Avalos 		 * When in untrusted mode, we read the cookie only if it was
39418de8d7fSPeter Avalos 		 * successfully generated as an untrusted one in the step
39518de8d7fSPeter Avalos 		 * above.
39618de8d7fSPeter Avalos 		 */
39718de8d7fSPeter Avalos 		if (trusted || generated) {
398664f4763Szrj 			xasprintf(&cmd,
39918de8d7fSPeter Avalos 			    "%s %s%s list %s 2>" _PATH_DEVNULL,
40018de8d7fSPeter Avalos 			    xauth_path,
40118de8d7fSPeter Avalos 			    generated ? "-f " : "" ,
40218de8d7fSPeter Avalos 			    generated ? xauthfile : "",
40318de8d7fSPeter Avalos 			    display);
40418de8d7fSPeter Avalos 			debug2("x11_get_proto: %s", cmd);
40518de8d7fSPeter Avalos 			f = popen(cmd, "r");
40618de8d7fSPeter Avalos 			if (f && fgets(line, sizeof(line), f) &&
40718de8d7fSPeter Avalos 			    sscanf(line, "%*s %511s %511s", proto, data) == 2)
40818de8d7fSPeter Avalos 				got_data = 1;
40918de8d7fSPeter Avalos 			if (f)
41018de8d7fSPeter Avalos 				pclose(f);
411664f4763Szrj 			free(cmd);
412e9778795SPeter Avalos 		}
41318de8d7fSPeter Avalos 	}
41418de8d7fSPeter Avalos 
41518de8d7fSPeter Avalos 	if (do_unlink) {
41618de8d7fSPeter Avalos 		unlink(xauthfile);
41718de8d7fSPeter Avalos 		rmdir(xauthdir);
41818de8d7fSPeter Avalos 	}
419e9778795SPeter Avalos 
420e9778795SPeter Avalos 	/* Don't fall back to fake X11 data for untrusted forwarding */
421e9778795SPeter Avalos 	if (!trusted && !got_data) {
422e9778795SPeter Avalos 		error("Warning: untrusted X11 forwarding setup failed: "
423e9778795SPeter Avalos 		    "xauth key data not generated");
424e9778795SPeter Avalos 		return -1;
425e9778795SPeter Avalos 	}
42618de8d7fSPeter Avalos 
42718de8d7fSPeter Avalos 	/*
42818de8d7fSPeter Avalos 	 * If we didn't get authentication data, just make up some
42918de8d7fSPeter Avalos 	 * data.  The forwarding code will check the validity of the
43018de8d7fSPeter Avalos 	 * response anyway, and substitute this data.  The X11
43118de8d7fSPeter Avalos 	 * server, however, will ignore this fake data and use
43218de8d7fSPeter Avalos 	 * whatever authentication mechanisms it was using otherwise
43318de8d7fSPeter Avalos 	 * for the local connection.
43418de8d7fSPeter Avalos 	 */
43518de8d7fSPeter Avalos 	if (!got_data) {
436ce74bacaSMatthew Dillon 		u_int8_t rnd[16];
437ce74bacaSMatthew Dillon 		u_int i;
43818de8d7fSPeter Avalos 
43918de8d7fSPeter Avalos 		logit("Warning: No xauth data; "
44018de8d7fSPeter Avalos 		    "using fake authentication data for X11 forwarding.");
44118de8d7fSPeter Avalos 		strlcpy(proto, SSH_X11_PROTO, sizeof proto);
442ce74bacaSMatthew Dillon 		arc4random_buf(rnd, sizeof(rnd));
443ce74bacaSMatthew Dillon 		for (i = 0; i < sizeof(rnd); i++) {
44418de8d7fSPeter Avalos 			snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
445ce74bacaSMatthew Dillon 			    rnd[i]);
44618de8d7fSPeter Avalos 		}
44718de8d7fSPeter Avalos 	}
448e9778795SPeter Avalos 
449e9778795SPeter Avalos 	return 0;
45018de8d7fSPeter Avalos }
45118de8d7fSPeter Avalos 
45218de8d7fSPeter Avalos /*
45318de8d7fSPeter Avalos  * Checks if the client window has changed, and sends a packet about it to
45418de8d7fSPeter Avalos  * the server if so.  The actual change is detected elsewhere (by a software
45518de8d7fSPeter Avalos  * interrupt on Unix); this just checks the flag and sends a message if
45618de8d7fSPeter Avalos  * appropriate.
45718de8d7fSPeter Avalos  */
45818de8d7fSPeter Avalos 
45918de8d7fSPeter Avalos static void
client_check_window_change(struct ssh * ssh)460ce74bacaSMatthew Dillon client_check_window_change(struct ssh *ssh)
46118de8d7fSPeter Avalos {
46218de8d7fSPeter Avalos 	if (!received_window_change_signal)
46318de8d7fSPeter Avalos 		return;
46418de8d7fSPeter Avalos 	received_window_change_signal = 0;
46550a69bb5SSascha Wildner 	debug2_f("changed");
466ce74bacaSMatthew Dillon 	channel_send_window_changes(ssh);
46718de8d7fSPeter Avalos }
46818de8d7fSPeter Avalos 
469e9778795SPeter Avalos static int
client_global_request_reply(int type,u_int32_t seq,struct ssh * ssh)470ce74bacaSMatthew Dillon client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
47118de8d7fSPeter Avalos {
47218de8d7fSPeter Avalos 	struct global_confirm *gc;
47318de8d7fSPeter Avalos 
47418de8d7fSPeter Avalos 	if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
475e9778795SPeter Avalos 		return 0;
47618de8d7fSPeter Avalos 	if (gc->cb != NULL)
477ce74bacaSMatthew Dillon 		gc->cb(ssh, type, seq, gc->ctx);
47818de8d7fSPeter Avalos 	if (--gc->ref_count <= 0) {
47918de8d7fSPeter Avalos 		TAILQ_REMOVE(&global_confirms, gc, entry);
4800cbfa66cSDaniel Fojt 		freezero(gc, sizeof(*gc));
48118de8d7fSPeter Avalos 	}
48218de8d7fSPeter Avalos 
483664f4763Szrj 	ssh_packet_set_alive_timeouts(ssh, 0);
484e9778795SPeter Avalos 	return 0;
48518de8d7fSPeter Avalos }
48618de8d7fSPeter Avalos 
48718de8d7fSPeter Avalos static void
schedule_server_alive_check(void)48850a69bb5SSascha Wildner schedule_server_alive_check(void)
48950a69bb5SSascha Wildner {
49050a69bb5SSascha Wildner 	if (options.server_alive_interval > 0)
49150a69bb5SSascha Wildner 		server_alive_time = monotime() + options.server_alive_interval;
49250a69bb5SSascha Wildner }
49350a69bb5SSascha Wildner 
49450a69bb5SSascha Wildner static void
server_alive_check(struct ssh * ssh)495664f4763Szrj server_alive_check(struct ssh *ssh)
49618de8d7fSPeter Avalos {
497664f4763Szrj 	int r;
498664f4763Szrj 
499664f4763Szrj 	if (ssh_packet_inc_alive_timeouts(ssh) > options.server_alive_count_max) {
5009f304aafSPeter Avalos 		logit("Timeout, server %s not responding.", host);
50118de8d7fSPeter Avalos 		cleanup_exit(255);
50218de8d7fSPeter Avalos 	}
503664f4763Szrj 	if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
504664f4763Szrj 	    (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) != 0 ||
505664f4763Szrj 	    (r = sshpkt_put_u8(ssh, 1)) != 0 ||		/* boolean: want reply */
506664f4763Szrj 	    (r = sshpkt_send(ssh)) != 0)
50750a69bb5SSascha Wildner 		fatal_fr(r, "send packet");
50818de8d7fSPeter Avalos 	/* Insert an empty placeholder to maintain ordering */
50918de8d7fSPeter Avalos 	client_register_global_confirm(NULL, NULL);
51050a69bb5SSascha Wildner 	schedule_server_alive_check();
51118de8d7fSPeter Avalos }
51218de8d7fSPeter Avalos 
513*ba1276acSMatthew Dillon /* Try to send a dummy keystroke */
514*ba1276acSMatthew Dillon static int
send_chaff(struct ssh * ssh)515*ba1276acSMatthew Dillon send_chaff(struct ssh *ssh)
516*ba1276acSMatthew Dillon {
517*ba1276acSMatthew Dillon 	int r;
518*ba1276acSMatthew Dillon 
519*ba1276acSMatthew Dillon 	if (ssh->kex == NULL || (ssh->kex->flags & KEX_HAS_PING) == 0)
520*ba1276acSMatthew Dillon 		return 0;
521*ba1276acSMatthew Dillon 	/* XXX probabilistically send chaff? */
522*ba1276acSMatthew Dillon 	/*
523*ba1276acSMatthew Dillon 	 * a SSH2_MSG_CHANNEL_DATA payload is 9 bytes:
524*ba1276acSMatthew Dillon 	 *    4 bytes channel ID + 4 bytes string length + 1 byte string data
525*ba1276acSMatthew Dillon 	 * simulate that here.
526*ba1276acSMatthew Dillon 	 */
527*ba1276acSMatthew Dillon 	if ((r = sshpkt_start(ssh, SSH2_MSG_PING)) != 0 ||
528*ba1276acSMatthew Dillon 	    (r = sshpkt_put_cstring(ssh, "PING!")) != 0 ||
529*ba1276acSMatthew Dillon 	    (r = sshpkt_send(ssh)) != 0)
530*ba1276acSMatthew Dillon 		fatal_fr(r, "send packet");
531*ba1276acSMatthew Dillon 	return 1;
532*ba1276acSMatthew Dillon }
533*ba1276acSMatthew Dillon 
534*ba1276acSMatthew Dillon /* Sets the next interval to send a keystroke or chaff packet */
535*ba1276acSMatthew Dillon static void
set_next_interval(const struct timespec * now,struct timespec * next_interval,u_int interval_ms,int starting)536*ba1276acSMatthew Dillon set_next_interval(const struct timespec *now, struct timespec *next_interval,
537*ba1276acSMatthew Dillon     u_int interval_ms, int starting)
538*ba1276acSMatthew Dillon {
539*ba1276acSMatthew Dillon 	struct timespec tmp;
540*ba1276acSMatthew Dillon 	long long interval_ns, fuzz_ns;
541*ba1276acSMatthew Dillon 	static long long rate_fuzz;
542*ba1276acSMatthew Dillon 
543*ba1276acSMatthew Dillon 	interval_ns = interval_ms * (1000LL * 1000);
544*ba1276acSMatthew Dillon 	fuzz_ns = (interval_ns * SSH_KEYSTROKE_TIMING_FUZZ) / 100;
545*ba1276acSMatthew Dillon 	/* Center fuzz around requested interval */
546*ba1276acSMatthew Dillon 	if (fuzz_ns > INT_MAX)
547*ba1276acSMatthew Dillon 		fuzz_ns = INT_MAX;
548*ba1276acSMatthew Dillon 	if (fuzz_ns > interval_ns) {
549*ba1276acSMatthew Dillon 		/* Shouldn't happen */
550*ba1276acSMatthew Dillon 		fatal_f("internal error: fuzz %u%% %lldns > interval %lldns",
551*ba1276acSMatthew Dillon 		    SSH_KEYSTROKE_TIMING_FUZZ, fuzz_ns, interval_ns);
552*ba1276acSMatthew Dillon 	}
553*ba1276acSMatthew Dillon 	/*
554*ba1276acSMatthew Dillon 	 * Randomise the keystroke/chaff intervals in two ways:
555*ba1276acSMatthew Dillon 	 * 1. Each interval has some random jitter applied to make the
556*ba1276acSMatthew Dillon 	 *    interval-to-interval time unpredictable.
557*ba1276acSMatthew Dillon 	 * 2. The overall interval rate is also randomly perturbed for each
558*ba1276acSMatthew Dillon 	 *    chaffing session to make the average rate unpredictable.
559*ba1276acSMatthew Dillon 	 */
560*ba1276acSMatthew Dillon 	if (starting)
561*ba1276acSMatthew Dillon 		rate_fuzz = arc4random_uniform(fuzz_ns);
562*ba1276acSMatthew Dillon 	interval_ns -= fuzz_ns;
563*ba1276acSMatthew Dillon 	interval_ns += arc4random_uniform(fuzz_ns) + rate_fuzz;
564*ba1276acSMatthew Dillon 
565*ba1276acSMatthew Dillon 	tmp.tv_sec = interval_ns / (1000 * 1000 * 1000);
566*ba1276acSMatthew Dillon 	tmp.tv_nsec = interval_ns % (1000 * 1000 * 1000);
567*ba1276acSMatthew Dillon 
568*ba1276acSMatthew Dillon 	timespecadd(now, &tmp, next_interval);
569*ba1276acSMatthew Dillon }
570*ba1276acSMatthew Dillon 
571*ba1276acSMatthew Dillon /*
572*ba1276acSMatthew Dillon  * Performs keystroke timing obfuscation. Returns non-zero if the
573*ba1276acSMatthew Dillon  * output fd should be polled.
574*ba1276acSMatthew Dillon  */
575*ba1276acSMatthew Dillon static int
obfuscate_keystroke_timing(struct ssh * ssh,struct timespec * timeout,int channel_did_enqueue)576*ba1276acSMatthew Dillon obfuscate_keystroke_timing(struct ssh *ssh, struct timespec *timeout,
577*ba1276acSMatthew Dillon     int channel_did_enqueue)
578*ba1276acSMatthew Dillon {
579*ba1276acSMatthew Dillon 	static int active;
580*ba1276acSMatthew Dillon 	static struct timespec next_interval, chaff_until;
581*ba1276acSMatthew Dillon 	struct timespec now, tmp;
582*ba1276acSMatthew Dillon 	int just_started = 0, had_keystroke = 0;
583*ba1276acSMatthew Dillon 	static unsigned long long nchaff;
584*ba1276acSMatthew Dillon 	char *stop_reason = NULL;
585*ba1276acSMatthew Dillon 	long long n;
586*ba1276acSMatthew Dillon 
587*ba1276acSMatthew Dillon 	monotime_ts(&now);
588*ba1276acSMatthew Dillon 
589*ba1276acSMatthew Dillon 	if (options.obscure_keystroke_timing_interval <= 0)
590*ba1276acSMatthew Dillon 		return 1;	/* disabled in config */
591*ba1276acSMatthew Dillon 
592*ba1276acSMatthew Dillon 	if (!channel_tty_open(ssh) || quit_pending) {
593*ba1276acSMatthew Dillon 		/* Stop if no channels left of we're waiting for one to close */
594*ba1276acSMatthew Dillon 		stop_reason = "no active channels";
595*ba1276acSMatthew Dillon 	} else if (ssh_packet_is_rekeying(ssh)) {
596*ba1276acSMatthew Dillon 		/* Stop if we're rekeying */
597*ba1276acSMatthew Dillon 		stop_reason = "rekeying started";
598*ba1276acSMatthew Dillon 	} else if (!ssh_packet_interactive_data_to_write(ssh) &&
599*ba1276acSMatthew Dillon 	    ssh_packet_have_data_to_write(ssh)) {
600*ba1276acSMatthew Dillon 		/* Stop if the output buffer has more than a few keystrokes */
601*ba1276acSMatthew Dillon 		stop_reason = "output buffer filling";
602*ba1276acSMatthew Dillon 	} else if (active && channel_did_enqueue &&
603*ba1276acSMatthew Dillon 	    ssh_packet_have_data_to_write(ssh)) {
604*ba1276acSMatthew Dillon 		/* Still in active mode and have a keystroke queued. */
605*ba1276acSMatthew Dillon 		had_keystroke = 1;
606*ba1276acSMatthew Dillon 	} else if (active) {
607*ba1276acSMatthew Dillon 		if (timespeccmp(&now, &chaff_until, >=)) {
608*ba1276acSMatthew Dillon 			/* Stop if there have been no keystrokes for a while */
609*ba1276acSMatthew Dillon 			stop_reason = "chaff time expired";
610*ba1276acSMatthew Dillon 		} else if (timespeccmp(&now, &next_interval, >=) &&
611*ba1276acSMatthew Dillon 		    !ssh_packet_have_data_to_write(ssh)) {
612*ba1276acSMatthew Dillon 			/* If due to send but have no data, then send chaff */
613*ba1276acSMatthew Dillon 			if (send_chaff(ssh))
614*ba1276acSMatthew Dillon 				nchaff++;
615*ba1276acSMatthew Dillon 		}
616*ba1276acSMatthew Dillon 	}
617*ba1276acSMatthew Dillon 
618*ba1276acSMatthew Dillon 	if (stop_reason != NULL) {
619*ba1276acSMatthew Dillon 		if (active) {
620*ba1276acSMatthew Dillon 			debug3_f("stopping: %s (%llu chaff packets sent)",
621*ba1276acSMatthew Dillon 			    stop_reason, nchaff);
622*ba1276acSMatthew Dillon 			active = 0;
623*ba1276acSMatthew Dillon 		}
624*ba1276acSMatthew Dillon 		return 1;
625*ba1276acSMatthew Dillon 	}
626*ba1276acSMatthew Dillon 
627*ba1276acSMatthew Dillon 	/*
628*ba1276acSMatthew Dillon 	 * If we're in interactive mode, and only have a small amount
629*ba1276acSMatthew Dillon 	 * of outbound data, then we assume that the user is typing
630*ba1276acSMatthew Dillon 	 * interactively. In this case, start quantising outbound packets to
631*ba1276acSMatthew Dillon 	 * fixed time intervals to hide inter-keystroke timing.
632*ba1276acSMatthew Dillon 	 */
633*ba1276acSMatthew Dillon 	if (!active && ssh_packet_interactive_data_to_write(ssh) &&
634*ba1276acSMatthew Dillon 	    channel_did_enqueue && ssh_packet_have_data_to_write(ssh)) {
635*ba1276acSMatthew Dillon 		debug3_f("starting: interval ~%dms",
636*ba1276acSMatthew Dillon 		    options.obscure_keystroke_timing_interval);
637*ba1276acSMatthew Dillon 		just_started = had_keystroke = active = 1;
638*ba1276acSMatthew Dillon 		nchaff = 0;
639*ba1276acSMatthew Dillon 		set_next_interval(&now, &next_interval,
640*ba1276acSMatthew Dillon 		    options.obscure_keystroke_timing_interval, 1);
641*ba1276acSMatthew Dillon 	}
642*ba1276acSMatthew Dillon 
643*ba1276acSMatthew Dillon 	/* Don't hold off if obfuscation inactive */
644*ba1276acSMatthew Dillon 	if (!active)
645*ba1276acSMatthew Dillon 		return 1;
646*ba1276acSMatthew Dillon 
647*ba1276acSMatthew Dillon 	if (had_keystroke) {
648*ba1276acSMatthew Dillon 		/*
649*ba1276acSMatthew Dillon 		 * Arrange to send chaff packets for a random interval after
650*ba1276acSMatthew Dillon 		 * the last keystroke was sent.
651*ba1276acSMatthew Dillon 		 */
652*ba1276acSMatthew Dillon 		ms_to_timespec(&tmp, SSH_KEYSTROKE_CHAFF_MIN_MS +
653*ba1276acSMatthew Dillon 		    arc4random_uniform(SSH_KEYSTROKE_CHAFF_RNG_MS));
654*ba1276acSMatthew Dillon 		timespecadd(&now, &tmp, &chaff_until);
655*ba1276acSMatthew Dillon 	}
656*ba1276acSMatthew Dillon 
657*ba1276acSMatthew Dillon 	ptimeout_deadline_monotime_tsp(timeout, &next_interval);
658*ba1276acSMatthew Dillon 
659*ba1276acSMatthew Dillon 	if (just_started)
660*ba1276acSMatthew Dillon 		return 1;
661*ba1276acSMatthew Dillon 
662*ba1276acSMatthew Dillon 	/* Don't arm output fd for poll until the timing interval has elapsed */
663*ba1276acSMatthew Dillon 	if (timespeccmp(&now, &next_interval, <))
664*ba1276acSMatthew Dillon 		return 0;
665*ba1276acSMatthew Dillon 
666*ba1276acSMatthew Dillon 	/* Calculate number of intervals missed since the last check */
667*ba1276acSMatthew Dillon 	n = (now.tv_sec - next_interval.tv_sec) * 1000LL * 1000 * 1000;
668*ba1276acSMatthew Dillon 	n += now.tv_nsec - next_interval.tv_nsec;
669*ba1276acSMatthew Dillon 	n /= options.obscure_keystroke_timing_interval * 1000LL * 1000;
670*ba1276acSMatthew Dillon 	n = (n < 0) ? 1 : n + 1;
671*ba1276acSMatthew Dillon 
672*ba1276acSMatthew Dillon 	/* Advance to the next interval */
673*ba1276acSMatthew Dillon 	set_next_interval(&now, &next_interval,
674*ba1276acSMatthew Dillon 	    options.obscure_keystroke_timing_interval * n, 0);
675*ba1276acSMatthew Dillon 	return 1;
676*ba1276acSMatthew Dillon }
677*ba1276acSMatthew Dillon 
67818de8d7fSPeter Avalos /*
67918de8d7fSPeter Avalos  * Waits until the client can do something (some data becomes available on
68018de8d7fSPeter Avalos  * one of the file descriptors).
68118de8d7fSPeter Avalos  */
68218de8d7fSPeter Avalos static void
client_wait_until_can_do_something(struct ssh * ssh,struct pollfd ** pfdp,u_int * npfd_allocp,u_int * npfd_activep,int channel_did_enqueue,sigset_t * sigsetp,int * conn_in_readyp,int * conn_out_readyp)683ee116499SAntonio Huete Jimenez client_wait_until_can_do_something(struct ssh *ssh, struct pollfd **pfdp,
684*ba1276acSMatthew Dillon     u_int *npfd_allocp, u_int *npfd_activep, int channel_did_enqueue,
685*ba1276acSMatthew Dillon     sigset_t *sigsetp, int *conn_in_readyp, int *conn_out_readyp)
68618de8d7fSPeter Avalos {
687*ba1276acSMatthew Dillon 	struct timespec timeout;
688*ba1276acSMatthew Dillon 	int ret, oready;
689ee116499SAntonio Huete Jimenez 	u_int p;
69018de8d7fSPeter Avalos 
691ee116499SAntonio Huete Jimenez 	*conn_in_readyp = *conn_out_readyp = 0;
69218de8d7fSPeter Avalos 
693ee116499SAntonio Huete Jimenez 	/* Prepare channel poll. First two pollfd entries are reserved */
694*ba1276acSMatthew Dillon 	ptimeout_init(&timeout);
695*ba1276acSMatthew Dillon 	channel_prepare_poll(ssh, pfdp, npfd_allocp, npfd_activep, 2, &timeout);
696ee116499SAntonio Huete Jimenez 	if (*npfd_activep < 2)
697ee116499SAntonio Huete Jimenez 		fatal_f("bad npfd %u", *npfd_activep); /* shouldn't happen */
698ee116499SAntonio Huete Jimenez 
699ee116499SAntonio Huete Jimenez 	/* channel_prepare_poll could have closed the last channel */
700ce74bacaSMatthew Dillon 	if (session_closed && !channel_still_open(ssh) &&
701664f4763Szrj 	    !ssh_packet_have_data_to_write(ssh)) {
702ee116499SAntonio Huete Jimenez 		/* clear events since we did not call poll() */
703ee116499SAntonio Huete Jimenez 		for (p = 0; p < *npfd_activep; p++)
704ee116499SAntonio Huete Jimenez 			(*pfdp)[p].revents = 0;
70518de8d7fSPeter Avalos 		return;
706ce74bacaSMatthew Dillon 	}
707ce74bacaSMatthew Dillon 
708*ba1276acSMatthew Dillon 	oready = obfuscate_keystroke_timing(ssh, &timeout, channel_did_enqueue);
709*ba1276acSMatthew Dillon 
710ee116499SAntonio Huete Jimenez 	/* Monitor server connection on reserved pollfd entries */
711ee116499SAntonio Huete Jimenez 	(*pfdp)[0].fd = connection_in;
712ee116499SAntonio Huete Jimenez 	(*pfdp)[0].events = POLLIN;
713ee116499SAntonio Huete Jimenez 	(*pfdp)[1].fd = connection_out;
714*ba1276acSMatthew Dillon 	(*pfdp)[1].events = (oready && ssh_packet_have_data_to_write(ssh)) ?
715*ba1276acSMatthew Dillon 	    POLLOUT : 0;
71618de8d7fSPeter Avalos 
71718de8d7fSPeter Avalos 	/*
71818de8d7fSPeter Avalos 	 * Wait for something to happen.  This will suspend the process until
719ee116499SAntonio Huete Jimenez 	 * some polled descriptor can be read, written, or has some other
720856ea928SPeter Avalos 	 * event pending, or a timeout expires.
72118de8d7fSPeter Avalos 	 */
722ce74bacaSMatthew Dillon 	set_control_persist_exit_time(ssh);
723*ba1276acSMatthew Dillon 	if (control_persist_exit_time > 0)
724*ba1276acSMatthew Dillon 		ptimeout_deadline_monotime(&timeout, control_persist_exit_time);
725*ba1276acSMatthew Dillon 	if (options.server_alive_interval > 0)
726*ba1276acSMatthew Dillon 		ptimeout_deadline_monotime(&timeout, server_alive_time);
727*ba1276acSMatthew Dillon 	if (options.rekey_interval > 0 && !ssh_packet_is_rekeying(ssh)) {
728*ba1276acSMatthew Dillon 		ptimeout_deadline_sec(&timeout,
729*ba1276acSMatthew Dillon 		    ssh_packet_get_rekey_timeout(ssh));
730856ea928SPeter Avalos 	}
731856ea928SPeter Avalos 
732*ba1276acSMatthew Dillon 	ret = ppoll(*pfdp, *npfd_activep, ptimeout_get_tsp(&timeout), sigsetp);
733ee116499SAntonio Huete Jimenez 
7340cbfa66cSDaniel Fojt 	if (ret == -1) {
73518de8d7fSPeter Avalos 		/*
736ee116499SAntonio Huete Jimenez 		 * We have to clear the events because we return.
73718de8d7fSPeter Avalos 		 * We have to return, because the mainloop checks for the flags
73818de8d7fSPeter Avalos 		 * set by the signal handlers.
73918de8d7fSPeter Avalos 		 */
740ee116499SAntonio Huete Jimenez 		for (p = 0; p < *npfd_activep; p++)
741ee116499SAntonio Huete Jimenez 			(*pfdp)[p].revents = 0;
74218de8d7fSPeter Avalos 		if (errno == EINTR)
74318de8d7fSPeter Avalos 			return;
74418de8d7fSPeter Avalos 		/* Note: we might still have data in the buffers. */
745ee116499SAntonio Huete Jimenez 		quit_message("poll: %s", strerror(errno));
746ee116499SAntonio Huete Jimenez 		return;
747ee116499SAntonio Huete Jimenez 	}
748ee116499SAntonio Huete Jimenez 
749ee116499SAntonio Huete Jimenez 	*conn_in_readyp = (*pfdp)[0].revents != 0;
750ee116499SAntonio Huete Jimenez 	*conn_out_readyp = (*pfdp)[1].revents != 0;
751ee116499SAntonio Huete Jimenez 
752ee116499SAntonio Huete Jimenez 	if (options.server_alive_interval > 0 && !*conn_in_readyp &&
753ee116499SAntonio Huete Jimenez 	    monotime() >= server_alive_time) {
75436e94dc5SPeter Avalos 		/*
755ee116499SAntonio Huete Jimenez 		 * ServerAlive check is needed. We can't rely on the poll
75650a69bb5SSascha Wildner 		 * timing out since traffic on the client side such as port
75750a69bb5SSascha Wildner 		 * forwards can keep waking it up.
75836e94dc5SPeter Avalos 		 */
759664f4763Szrj 		server_alive_check(ssh);
76018de8d7fSPeter Avalos 	}
761ee116499SAntonio Huete Jimenez }
76218de8d7fSPeter Avalos 
76318de8d7fSPeter Avalos static void
client_suspend_self(struct sshbuf * bin,struct sshbuf * bout,struct sshbuf * berr)764664f4763Szrj client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr)
76518de8d7fSPeter Avalos {
76618de8d7fSPeter Avalos 	/* Flush stdout and stderr buffers. */
767664f4763Szrj 	if (sshbuf_len(bout) > 0)
768664f4763Szrj 		atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout),
769664f4763Szrj 		    sshbuf_len(bout));
770664f4763Szrj 	if (sshbuf_len(berr) > 0)
771664f4763Szrj 		atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr),
772664f4763Szrj 		    sshbuf_len(berr));
77318de8d7fSPeter Avalos 
7741c188a7fSPeter Avalos 	leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
77518de8d7fSPeter Avalos 
776ce74bacaSMatthew Dillon 	sshbuf_reset(bin);
777ce74bacaSMatthew Dillon 	sshbuf_reset(bout);
778ce74bacaSMatthew Dillon 	sshbuf_reset(berr);
77918de8d7fSPeter Avalos 
78018de8d7fSPeter Avalos 	/* Send the suspend signal to the program itself. */
78118de8d7fSPeter Avalos 	kill(getpid(), SIGTSTP);
78218de8d7fSPeter Avalos 
78318de8d7fSPeter Avalos 	/* Reset window sizes in case they have changed */
78418de8d7fSPeter Avalos 	received_window_change_signal = 1;
78518de8d7fSPeter Avalos 
7861c188a7fSPeter Avalos 	enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
78718de8d7fSPeter Avalos }
78818de8d7fSPeter Avalos 
78918de8d7fSPeter Avalos static void
client_process_net_input(struct ssh * ssh)790ee116499SAntonio Huete Jimenez client_process_net_input(struct ssh *ssh)
79118de8d7fSPeter Avalos {
792ee116499SAntonio Huete Jimenez 	int r;
79318de8d7fSPeter Avalos 
79418de8d7fSPeter Avalos 	/*
79518de8d7fSPeter Avalos 	 * Read input from the server, and add any such data to the buffer of
79618de8d7fSPeter Avalos 	 * the packet subsystem.
79718de8d7fSPeter Avalos 	 */
79850a69bb5SSascha Wildner 	schedule_server_alive_check();
799ee116499SAntonio Huete Jimenez 	if ((r = ssh_packet_process_read(ssh, connection_in)) == 0)
800ee116499SAntonio Huete Jimenez 		return; /* success */
801ee116499SAntonio Huete Jimenez 	if (r == SSH_ERR_SYSTEM_ERROR) {
802ee116499SAntonio Huete Jimenez 		if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK)
803ee116499SAntonio Huete Jimenez 			return;
804ee116499SAntonio Huete Jimenez 		if (errno == EPIPE) {
805ee116499SAntonio Huete Jimenez 			quit_message("Connection to %s closed by remote host.",
806ee116499SAntonio Huete Jimenez 			    host);
80718de8d7fSPeter Avalos 			return;
80818de8d7fSPeter Avalos 		}
80918de8d7fSPeter Avalos 	}
810ee116499SAntonio Huete Jimenez 	quit_message("Read from remote host %s: %s", host, ssh_err(r));
81118de8d7fSPeter Avalos }
81218de8d7fSPeter Avalos 
81318de8d7fSPeter Avalos static void
client_status_confirm(struct ssh * ssh,int type,Channel * c,void * ctx)814ce74bacaSMatthew Dillon client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
81518de8d7fSPeter Avalos {
81618de8d7fSPeter Avalos 	struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
81718de8d7fSPeter Avalos 	char errmsg[256];
818664f4763Szrj 	int r, tochan;
81918de8d7fSPeter Avalos 
8201c188a7fSPeter Avalos 	/*
8211c188a7fSPeter Avalos 	 * If a TTY was explicitly requested, then a failure to allocate
8221c188a7fSPeter Avalos 	 * one is fatal.
8231c188a7fSPeter Avalos 	 */
8241c188a7fSPeter Avalos 	if (cr->action == CONFIRM_TTY &&
8251c188a7fSPeter Avalos 	    (options.request_tty == REQUEST_TTY_FORCE ||
8261c188a7fSPeter Avalos 	    options.request_tty == REQUEST_TTY_YES))
8271c188a7fSPeter Avalos 		cr->action = CONFIRM_CLOSE;
8281c188a7fSPeter Avalos 
829664f4763Szrj 	/* XXX suppress on mux _client_ quietmode */
83018de8d7fSPeter Avalos 	tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
831856ea928SPeter Avalos 	    c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
83218de8d7fSPeter Avalos 
83318de8d7fSPeter Avalos 	if (type == SSH2_MSG_CHANNEL_SUCCESS) {
83418de8d7fSPeter Avalos 		debug2("%s request accepted on channel %d",
83518de8d7fSPeter Avalos 		    cr->request_type, c->self);
83618de8d7fSPeter Avalos 	} else if (type == SSH2_MSG_CHANNEL_FAILURE) {
83718de8d7fSPeter Avalos 		if (tochan) {
83818de8d7fSPeter Avalos 			snprintf(errmsg, sizeof(errmsg),
83918de8d7fSPeter Avalos 			    "%s request failed\r\n", cr->request_type);
84018de8d7fSPeter Avalos 		} else {
84118de8d7fSPeter Avalos 			snprintf(errmsg, sizeof(errmsg),
84218de8d7fSPeter Avalos 			    "%s request failed on channel %d",
84318de8d7fSPeter Avalos 			    cr->request_type, c->self);
84418de8d7fSPeter Avalos 		}
84518de8d7fSPeter Avalos 		/* If error occurred on primary session channel, then exit */
8461c188a7fSPeter Avalos 		if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
84718de8d7fSPeter Avalos 			fatal("%s", errmsg);
8481c188a7fSPeter Avalos 		/*
8491c188a7fSPeter Avalos 		 * If error occurred on mux client, append to
8501c188a7fSPeter Avalos 		 * their stderr.
8511c188a7fSPeter Avalos 		 */
8521c188a7fSPeter Avalos 		if (tochan) {
85350a69bb5SSascha Wildner 			debug3_f("channel %d: mux request: %s", c->self,
85450a69bb5SSascha Wildner 			    cr->request_type);
855664f4763Szrj 			if ((r = sshbuf_put(c->extended, errmsg,
856664f4763Szrj 			    strlen(errmsg))) != 0)
85750a69bb5SSascha Wildner 				fatal_fr(r, "sshbuf_put");
8581c188a7fSPeter Avalos 		} else
85918de8d7fSPeter Avalos 			error("%s", errmsg);
8601c188a7fSPeter Avalos 		if (cr->action == CONFIRM_TTY) {
8611c188a7fSPeter Avalos 			/*
8621c188a7fSPeter Avalos 			 * If a TTY allocation error occurred, then arrange
8631c188a7fSPeter Avalos 			 * for the correct TTY to leave raw mode.
8641c188a7fSPeter Avalos 			 */
8651c188a7fSPeter Avalos 			if (c->self == session_ident)
8661c188a7fSPeter Avalos 				leave_raw_mode(0);
8671c188a7fSPeter Avalos 			else
868ce74bacaSMatthew Dillon 				mux_tty_alloc_failed(ssh, c);
8691c188a7fSPeter Avalos 		} else if (cr->action == CONFIRM_CLOSE) {
870ce74bacaSMatthew Dillon 			chan_read_failed(ssh, c);
871ce74bacaSMatthew Dillon 			chan_write_failed(ssh, c);
87218de8d7fSPeter Avalos 		}
87318de8d7fSPeter Avalos 	}
87436e94dc5SPeter Avalos 	free(cr);
87518de8d7fSPeter Avalos }
87618de8d7fSPeter Avalos 
87718de8d7fSPeter Avalos static void
client_abandon_status_confirm(struct ssh * ssh,Channel * c,void * ctx)878ce74bacaSMatthew Dillon client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
87918de8d7fSPeter Avalos {
88036e94dc5SPeter Avalos 	free(ctx);
88118de8d7fSPeter Avalos }
88218de8d7fSPeter Avalos 
8831c188a7fSPeter Avalos void
client_expect_confirm(struct ssh * ssh,int id,const char * request,enum confirm_action action)884ce74bacaSMatthew Dillon client_expect_confirm(struct ssh *ssh, int id, const char *request,
8851c188a7fSPeter Avalos     enum confirm_action action)
88618de8d7fSPeter Avalos {
88736e94dc5SPeter Avalos 	struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
88818de8d7fSPeter Avalos 
88918de8d7fSPeter Avalos 	cr->request_type = request;
8901c188a7fSPeter Avalos 	cr->action = action;
89118de8d7fSPeter Avalos 
892ce74bacaSMatthew Dillon 	channel_register_status_confirm(ssh, id, client_status_confirm,
89318de8d7fSPeter Avalos 	    client_abandon_status_confirm, cr);
89418de8d7fSPeter Avalos }
89518de8d7fSPeter Avalos 
89618de8d7fSPeter Avalos void
client_register_global_confirm(global_confirm_cb * cb,void * ctx)89718de8d7fSPeter Avalos client_register_global_confirm(global_confirm_cb *cb, void *ctx)
89818de8d7fSPeter Avalos {
89918de8d7fSPeter Avalos 	struct global_confirm *gc, *last_gc;
90018de8d7fSPeter Avalos 
90118de8d7fSPeter Avalos 	/* Coalesce identical callbacks */
90218de8d7fSPeter Avalos 	last_gc = TAILQ_LAST(&global_confirms, global_confirms);
90318de8d7fSPeter Avalos 	if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
90418de8d7fSPeter Avalos 		if (++last_gc->ref_count >= INT_MAX)
90550a69bb5SSascha Wildner 			fatal_f("last_gc->ref_count = %d",
90650a69bb5SSascha Wildner 			    last_gc->ref_count);
90718de8d7fSPeter Avalos 		return;
90818de8d7fSPeter Avalos 	}
90918de8d7fSPeter Avalos 
91036e94dc5SPeter Avalos 	gc = xcalloc(1, sizeof(*gc));
91118de8d7fSPeter Avalos 	gc->cb = cb;
91218de8d7fSPeter Avalos 	gc->ctx = ctx;
91318de8d7fSPeter Avalos 	gc->ref_count = 1;
91418de8d7fSPeter Avalos 	TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
91518de8d7fSPeter Avalos }
91618de8d7fSPeter Avalos 
917*ba1276acSMatthew Dillon /*
918*ba1276acSMatthew Dillon  * Returns non-zero if the client is able to handle a hostkeys-00@openssh.com
919*ba1276acSMatthew Dillon  * hostkey update request.
920*ba1276acSMatthew Dillon  */
921*ba1276acSMatthew Dillon static int
can_update_hostkeys(void)922*ba1276acSMatthew Dillon can_update_hostkeys(void)
923*ba1276acSMatthew Dillon {
924*ba1276acSMatthew Dillon 	if (hostkeys_update_complete)
925*ba1276acSMatthew Dillon 		return 0;
926*ba1276acSMatthew Dillon 	if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
927*ba1276acSMatthew Dillon 	    options.batch_mode)
928*ba1276acSMatthew Dillon 		return 0; /* won't ask in batchmode, so don't even try */
929*ba1276acSMatthew Dillon 	if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
930*ba1276acSMatthew Dillon 		return 0;
931*ba1276acSMatthew Dillon 	return 1;
932*ba1276acSMatthew Dillon }
933*ba1276acSMatthew Dillon 
934*ba1276acSMatthew Dillon static void
client_repledge(void)935*ba1276acSMatthew Dillon client_repledge(void)
936*ba1276acSMatthew Dillon {
937*ba1276acSMatthew Dillon 	debug3_f("enter");
938*ba1276acSMatthew Dillon 
939*ba1276acSMatthew Dillon 	/* Might be able to tighten pledge now that session is established */
940*ba1276acSMatthew Dillon 	if (options.control_master || options.control_path != NULL ||
941*ba1276acSMatthew Dillon 	    options.forward_x11 || options.fork_after_authentication ||
942*ba1276acSMatthew Dillon 	    can_update_hostkeys() ||
943*ba1276acSMatthew Dillon 	    (session_ident != -1 && !session_setup_complete)) {
944*ba1276acSMatthew Dillon 		/* Can't tighten */
945*ba1276acSMatthew Dillon 		return;
946*ba1276acSMatthew Dillon 	}
947*ba1276acSMatthew Dillon 	/*
948*ba1276acSMatthew Dillon 	 * LocalCommand and UpdateHostkeys have finished, so can get rid of
949*ba1276acSMatthew Dillon 	 * filesystem.
950*ba1276acSMatthew Dillon 	 *
951*ba1276acSMatthew Dillon 	 * XXX protocol allows a server can to change hostkeys during the
952*ba1276acSMatthew Dillon 	 *     connection at rekey time that could trigger a hostkeys update
953*ba1276acSMatthew Dillon 	 *     but AFAIK no implementations support this. Could improve by
954*ba1276acSMatthew Dillon 	 *     forcing known_hosts to be read-only or via unveil(2).
955*ba1276acSMatthew Dillon 	 */
956*ba1276acSMatthew Dillon 	if (options.num_local_forwards != 0 ||
957*ba1276acSMatthew Dillon 	    options.num_remote_forwards != 0 ||
958*ba1276acSMatthew Dillon 	    options.num_permitted_remote_opens != 0 ||
959*ba1276acSMatthew Dillon 	    options.enable_escape_commandline != 0) {
960*ba1276acSMatthew Dillon 		/* rfwd needs inet */
961*ba1276acSMatthew Dillon 		debug("pledge: network");
962*ba1276acSMatthew Dillon 		if (pledge("stdio unix inet dns proc tty", NULL) == -1)
963*ba1276acSMatthew Dillon 			fatal_f("pledge(): %s", strerror(errno));
964*ba1276acSMatthew Dillon 	} else if (options.forward_agent != 0) {
965*ba1276acSMatthew Dillon 		/* agent forwarding needs to open $SSH_AUTH_SOCK at will */
966*ba1276acSMatthew Dillon 		debug("pledge: agent");
967*ba1276acSMatthew Dillon 		if (pledge("stdio unix proc tty", NULL) == -1)
968*ba1276acSMatthew Dillon 			fatal_f("pledge(): %s", strerror(errno));
969*ba1276acSMatthew Dillon 	} else {
970*ba1276acSMatthew Dillon 		debug("pledge: fork");
971*ba1276acSMatthew Dillon 		if (pledge("stdio proc tty", NULL) == -1)
972*ba1276acSMatthew Dillon 			fatal_f("pledge(): %s", strerror(errno));
973*ba1276acSMatthew Dillon 	}
974*ba1276acSMatthew Dillon 	/* XXX further things to do:
975*ba1276acSMatthew Dillon 	 *
976*ba1276acSMatthew Dillon 	 * - might be able to get rid of proc if we kill ~^Z
977*ba1276acSMatthew Dillon 	 * - ssh -N (no session)
978*ba1276acSMatthew Dillon 	 * - stdio forwarding
979*ba1276acSMatthew Dillon 	 * - sessions without tty
980*ba1276acSMatthew Dillon 	 */
981*ba1276acSMatthew Dillon }
982*ba1276acSMatthew Dillon 
98318de8d7fSPeter Avalos static void
process_cmdline(struct ssh * ssh)984ce74bacaSMatthew Dillon process_cmdline(struct ssh *ssh)
98518de8d7fSPeter Avalos {
98618de8d7fSPeter Avalos 	void (*handler)(int);
98736e94dc5SPeter Avalos 	char *s, *cmd;
98836e94dc5SPeter Avalos 	int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
98936e94dc5SPeter Avalos 	struct Forward fwd;
99018de8d7fSPeter Avalos 
99136e94dc5SPeter Avalos 	memset(&fwd, 0, sizeof(fwd));
99218de8d7fSPeter Avalos 
9931c188a7fSPeter Avalos 	leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
9940cbfa66cSDaniel Fojt 	handler = ssh_signal(SIGINT, SIG_IGN);
99518de8d7fSPeter Avalos 	cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
99618de8d7fSPeter Avalos 	if (s == NULL)
99718de8d7fSPeter Avalos 		goto out;
99836e94dc5SPeter Avalos 	while (isspace((u_char)*s))
99918de8d7fSPeter Avalos 		s++;
100018de8d7fSPeter Avalos 	if (*s == '-')
100118de8d7fSPeter Avalos 		s++;	/* Skip cmdline '-', if any */
100218de8d7fSPeter Avalos 	if (*s == '\0')
100318de8d7fSPeter Avalos 		goto out;
100418de8d7fSPeter Avalos 
100518de8d7fSPeter Avalos 	if (*s == 'h' || *s == 'H' || *s == '?') {
100618de8d7fSPeter Avalos 		logit("Commands:");
100718de8d7fSPeter Avalos 		logit("      -L[bind_address:]port:host:hostport    "
100818de8d7fSPeter Avalos 		    "Request local forward");
100918de8d7fSPeter Avalos 		logit("      -R[bind_address:]port:host:hostport    "
101018de8d7fSPeter Avalos 		    "Request remote forward");
1011cb5eb4f1SPeter Avalos 		logit("      -D[bind_address:]port                  "
1012cb5eb4f1SPeter Avalos 		    "Request dynamic forward");
101399e85e0dSPeter Avalos 		logit("      -KL[bind_address:]port                 "
101499e85e0dSPeter Avalos 		    "Cancel local forward");
101518de8d7fSPeter Avalos 		logit("      -KR[bind_address:]port                 "
101618de8d7fSPeter Avalos 		    "Cancel remote forward");
101799e85e0dSPeter Avalos 		logit("      -KD[bind_address:]port                 "
101899e85e0dSPeter Avalos 		    "Cancel dynamic forward");
101918de8d7fSPeter Avalos 		if (!options.permit_local_command)
102018de8d7fSPeter Avalos 			goto out;
102118de8d7fSPeter Avalos 		logit("      !args                                  "
102218de8d7fSPeter Avalos 		    "Execute local command");
102318de8d7fSPeter Avalos 		goto out;
102418de8d7fSPeter Avalos 	}
102518de8d7fSPeter Avalos 
102618de8d7fSPeter Avalos 	if (*s == '!' && options.permit_local_command) {
102718de8d7fSPeter Avalos 		s++;
102818de8d7fSPeter Avalos 		ssh_local_cmd(s);
102918de8d7fSPeter Avalos 		goto out;
103018de8d7fSPeter Avalos 	}
103118de8d7fSPeter Avalos 
103218de8d7fSPeter Avalos 	if (*s == 'K') {
103318de8d7fSPeter Avalos 		delete = 1;
103418de8d7fSPeter Avalos 		s++;
103518de8d7fSPeter Avalos 	}
1036cb5eb4f1SPeter Avalos 	if (*s == 'L')
1037cb5eb4f1SPeter Avalos 		local = 1;
1038cb5eb4f1SPeter Avalos 	else if (*s == 'R')
1039cb5eb4f1SPeter Avalos 		remote = 1;
1040cb5eb4f1SPeter Avalos 	else if (*s == 'D')
1041cb5eb4f1SPeter Avalos 		dynamic = 1;
1042cb5eb4f1SPeter Avalos 	else {
104318de8d7fSPeter Avalos 		logit("Invalid command.");
104418de8d7fSPeter Avalos 		goto out;
104518de8d7fSPeter Avalos 	}
1046cb5eb4f1SPeter Avalos 
104736e94dc5SPeter Avalos 	while (isspace((u_char)*++s))
104818de8d7fSPeter Avalos 		;
104918de8d7fSPeter Avalos 
1050856ea928SPeter Avalos 	/* XXX update list of forwards in options */
105118de8d7fSPeter Avalos 	if (delete) {
105236e94dc5SPeter Avalos 		/* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
105336e94dc5SPeter Avalos 		if (!parse_forward(&fwd, s, 1, 0)) {
105436e94dc5SPeter Avalos 			logit("Bad forwarding close specification.");
105518de8d7fSPeter Avalos 			goto out;
105618de8d7fSPeter Avalos 		}
105799e85e0dSPeter Avalos 		if (remote)
1058ce74bacaSMatthew Dillon 			ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
105999e85e0dSPeter Avalos 		else if (dynamic)
1060ce74bacaSMatthew Dillon 			ok = channel_cancel_lport_listener(ssh, &fwd,
106136e94dc5SPeter Avalos 			    0, &options.fwd_opts) > 0;
106299e85e0dSPeter Avalos 		else
1063ce74bacaSMatthew Dillon 			ok = channel_cancel_lport_listener(ssh, &fwd,
106436e94dc5SPeter Avalos 			    CHANNEL_CANCEL_PORT_STATIC,
106536e94dc5SPeter Avalos 			    &options.fwd_opts) > 0;
106699e85e0dSPeter Avalos 		if (!ok) {
1067ce74bacaSMatthew Dillon 			logit("Unknown port forwarding.");
106899e85e0dSPeter Avalos 			goto out;
106999e85e0dSPeter Avalos 		}
107099e85e0dSPeter Avalos 		logit("Canceled forwarding.");
107118de8d7fSPeter Avalos 	} else {
1072*ba1276acSMatthew Dillon 		/* -R specs can be both dynamic or not, so check both. */
1073*ba1276acSMatthew Dillon 		if (remote) {
1074*ba1276acSMatthew Dillon 			if (!parse_forward(&fwd, s, 0, remote) &&
1075*ba1276acSMatthew Dillon 			    !parse_forward(&fwd, s, 1, remote)) {
1076*ba1276acSMatthew Dillon 				logit("Bad remote forwarding specification.");
1077*ba1276acSMatthew Dillon 				goto out;
1078*ba1276acSMatthew Dillon 			}
1079*ba1276acSMatthew Dillon 		} else if (!parse_forward(&fwd, s, dynamic, remote)) {
1080*ba1276acSMatthew Dillon 			logit("Bad local forwarding specification.");
108118de8d7fSPeter Avalos 			goto out;
108218de8d7fSPeter Avalos 		}
1083cb5eb4f1SPeter Avalos 		if (local || dynamic) {
1084ce74bacaSMatthew Dillon 			if (!channel_setup_local_fwd_listener(ssh, &fwd,
108536e94dc5SPeter Avalos 			    &options.fwd_opts)) {
108618de8d7fSPeter Avalos 				logit("Port forwarding failed.");
108718de8d7fSPeter Avalos 				goto out;
108818de8d7fSPeter Avalos 			}
108918de8d7fSPeter Avalos 		} else {
1090ce74bacaSMatthew Dillon 			if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
109118de8d7fSPeter Avalos 				logit("Port forwarding failed.");
109218de8d7fSPeter Avalos 				goto out;
109318de8d7fSPeter Avalos 			}
109418de8d7fSPeter Avalos 		}
109518de8d7fSPeter Avalos 		logit("Forwarding port.");
109618de8d7fSPeter Avalos 	}
109718de8d7fSPeter Avalos 
109818de8d7fSPeter Avalos out:
10990cbfa66cSDaniel Fojt 	ssh_signal(SIGINT, handler);
11001c188a7fSPeter Avalos 	enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
110136e94dc5SPeter Avalos 	free(cmd);
110236e94dc5SPeter Avalos 	free(fwd.listen_host);
110336e94dc5SPeter Avalos 	free(fwd.listen_path);
110436e94dc5SPeter Avalos 	free(fwd.connect_host);
110536e94dc5SPeter Avalos 	free(fwd.connect_path);
110636e94dc5SPeter Avalos }
110736e94dc5SPeter Avalos 
110836e94dc5SPeter Avalos /* reasons to suppress output of an escape command in help output */
110936e94dc5SPeter Avalos #define SUPPRESS_NEVER		0	/* never suppress, always show */
1110ce74bacaSMatthew Dillon #define SUPPRESS_MUXCLIENT	1	/* don't show in mux client sessions */
1111ce74bacaSMatthew Dillon #define SUPPRESS_MUXMASTER	2	/* don't show in mux master sessions */
1112ce74bacaSMatthew Dillon #define SUPPRESS_SYSLOG		4	/* don't show when logging to syslog */
1113*ba1276acSMatthew Dillon #define SUPPRESS_NOCMDLINE	8	/* don't show when cmdline disabled*/
111436e94dc5SPeter Avalos struct escape_help_text {
111536e94dc5SPeter Avalos 	const char *cmd;
111636e94dc5SPeter Avalos 	const char *text;
111736e94dc5SPeter Avalos 	unsigned int flags;
111836e94dc5SPeter Avalos };
111936e94dc5SPeter Avalos static struct escape_help_text esc_txt[] = {
112036e94dc5SPeter Avalos     {".",  "terminate session", SUPPRESS_MUXMASTER},
112136e94dc5SPeter Avalos     {".",  "terminate connection (and any multiplexed sessions)",
112236e94dc5SPeter Avalos 	SUPPRESS_MUXCLIENT},
1123ce74bacaSMatthew Dillon     {"B",  "send a BREAK to the remote system", SUPPRESS_NEVER},
1124*ba1276acSMatthew Dillon     {"C",  "open a command line", SUPPRESS_MUXCLIENT|SUPPRESS_NOCMDLINE},
1125ce74bacaSMatthew Dillon     {"R",  "request rekey", SUPPRESS_NEVER},
112636e94dc5SPeter Avalos     {"V/v",  "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
112736e94dc5SPeter Avalos     {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
112836e94dc5SPeter Avalos     {"#",  "list forwarded connections", SUPPRESS_NEVER},
112936e94dc5SPeter Avalos     {"&",  "background ssh (when waiting for connections to terminate)",
113036e94dc5SPeter Avalos 	SUPPRESS_MUXCLIENT},
113136e94dc5SPeter Avalos     {"?", "this message", SUPPRESS_NEVER},
113236e94dc5SPeter Avalos };
113336e94dc5SPeter Avalos 
113436e94dc5SPeter Avalos static void
print_escape_help(struct sshbuf * b,int escape_char,int mux_client,int using_stderr)1135664f4763Szrj print_escape_help(struct sshbuf *b, int escape_char, int mux_client,
1136664f4763Szrj     int using_stderr)
113736e94dc5SPeter Avalos {
113836e94dc5SPeter Avalos 	unsigned int i, suppress_flags;
1139664f4763Szrj 	int r;
114036e94dc5SPeter Avalos 
1141664f4763Szrj 	if ((r = sshbuf_putf(b,
1142664f4763Szrj 	    "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0)
114350a69bb5SSascha Wildner 		fatal_fr(r, "sshbuf_putf");
114436e94dc5SPeter Avalos 
1145ce74bacaSMatthew Dillon 	suppress_flags =
114636e94dc5SPeter Avalos 	    (mux_client ? SUPPRESS_MUXCLIENT : 0) |
114736e94dc5SPeter Avalos 	    (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1148*ba1276acSMatthew Dillon 	    (using_stderr ? 0 : SUPPRESS_SYSLOG) |
1149*ba1276acSMatthew Dillon 	    (options.enable_escape_commandline == 0 ? SUPPRESS_NOCMDLINE : 0);
115036e94dc5SPeter Avalos 
115136e94dc5SPeter Avalos 	for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
115236e94dc5SPeter Avalos 		if (esc_txt[i].flags & suppress_flags)
115336e94dc5SPeter Avalos 			continue;
1154664f4763Szrj 		if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n",
1155664f4763Szrj 		    escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0)
115650a69bb5SSascha Wildner 			fatal_fr(r, "sshbuf_putf");
115736e94dc5SPeter Avalos 	}
115836e94dc5SPeter Avalos 
1159664f4763Szrj 	if ((r = sshbuf_putf(b,
116036e94dc5SPeter Avalos 	    " %c%c   - send the escape character by typing it twice\r\n"
116136e94dc5SPeter Avalos 	    "(Note that escapes are only recognized immediately after "
1162664f4763Szrj 	    "newline.)\r\n", escape_char, escape_char)) != 0)
116350a69bb5SSascha Wildner 		fatal_fr(r, "sshbuf_putf");
116418de8d7fSPeter Avalos }
116518de8d7fSPeter Avalos 
116618de8d7fSPeter Avalos /*
1167ce74bacaSMatthew Dillon  * Process the characters one by one.
116818de8d7fSPeter Avalos  */
116918de8d7fSPeter Avalos static int
process_escapes(struct ssh * ssh,Channel * c,struct sshbuf * bin,struct sshbuf * bout,struct sshbuf * berr,char * buf,int len)1170ce74bacaSMatthew Dillon process_escapes(struct ssh *ssh, Channel *c,
1171664f4763Szrj     struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr,
117218de8d7fSPeter Avalos     char *buf, int len)
117318de8d7fSPeter Avalos {
117418de8d7fSPeter Avalos 	pid_t pid;
1175664f4763Szrj 	int r, bytes = 0;
117618de8d7fSPeter Avalos 	u_int i;
117718de8d7fSPeter Avalos 	u_char ch;
117818de8d7fSPeter Avalos 	char *s;
1179*ba1276acSMatthew Dillon 	struct escape_filter_ctx *efc;
118018de8d7fSPeter Avalos 
1181*ba1276acSMatthew Dillon 	if (c == NULL || c->filter_ctx == NULL || len <= 0)
118218de8d7fSPeter Avalos 		return 0;
118318de8d7fSPeter Avalos 
1184*ba1276acSMatthew Dillon 	efc = (struct escape_filter_ctx *)c->filter_ctx;
118518de8d7fSPeter Avalos 
118618de8d7fSPeter Avalos 	for (i = 0; i < (u_int)len; i++) {
118718de8d7fSPeter Avalos 		/* Get one character at a time. */
118818de8d7fSPeter Avalos 		ch = buf[i];
118918de8d7fSPeter Avalos 
1190ce74bacaSMatthew Dillon 		if (efc->escape_pending) {
119118de8d7fSPeter Avalos 			/* We have previously seen an escape character. */
119218de8d7fSPeter Avalos 			/* Clear the flag now. */
1193ce74bacaSMatthew Dillon 			efc->escape_pending = 0;
119418de8d7fSPeter Avalos 
119518de8d7fSPeter Avalos 			/* Process the escaped character. */
119618de8d7fSPeter Avalos 			switch (ch) {
119718de8d7fSPeter Avalos 			case '.':
119818de8d7fSPeter Avalos 				/* Terminate the connection. */
1199664f4763Szrj 				if ((r = sshbuf_putf(berr, "%c.\r\n",
1200664f4763Szrj 				    efc->escape_char)) != 0)
120150a69bb5SSascha Wildner 					fatal_fr(r, "sshbuf_putf");
1202856ea928SPeter Avalos 				if (c && c->ctl_chan != -1) {
1203*ba1276acSMatthew Dillon 					channel_force_close(ssh, c, 1);
120418de8d7fSPeter Avalos 					return 0;
120518de8d7fSPeter Avalos 				} else
120618de8d7fSPeter Avalos 					quit_pending = 1;
120718de8d7fSPeter Avalos 				return -1;
120818de8d7fSPeter Avalos 
120918de8d7fSPeter Avalos 			case 'Z' - 64:
121018de8d7fSPeter Avalos 				/* XXX support this for mux clients */
1211856ea928SPeter Avalos 				if (c && c->ctl_chan != -1) {
121236e94dc5SPeter Avalos 					char b[16];
121318de8d7fSPeter Avalos  noescape:
121436e94dc5SPeter Avalos 					if (ch == 'Z' - 64)
121536e94dc5SPeter Avalos 						snprintf(b, sizeof b, "^Z");
121636e94dc5SPeter Avalos 					else
121736e94dc5SPeter Avalos 						snprintf(b, sizeof b, "%c", ch);
1218664f4763Szrj 					if ((r = sshbuf_putf(berr,
121936e94dc5SPeter Avalos 					    "%c%s escape not available to "
122018de8d7fSPeter Avalos 					    "multiplexed sessions\r\n",
1221664f4763Szrj 					    efc->escape_char, b)) != 0)
122250a69bb5SSascha Wildner 						fatal_fr(r, "sshbuf_putf");
122318de8d7fSPeter Avalos 					continue;
122418de8d7fSPeter Avalos 				}
122518de8d7fSPeter Avalos 				/* Suspend the program. Inform the user */
1226664f4763Szrj 				if ((r = sshbuf_putf(berr,
1227664f4763Szrj 				    "%c^Z [suspend ssh]\r\n",
1228664f4763Szrj 				    efc->escape_char)) != 0)
122950a69bb5SSascha Wildner 					fatal_fr(r, "sshbuf_putf");
123018de8d7fSPeter Avalos 
123118de8d7fSPeter Avalos 				/* Restore terminal modes and suspend. */
123218de8d7fSPeter Avalos 				client_suspend_self(bin, bout, berr);
123318de8d7fSPeter Avalos 
123418de8d7fSPeter Avalos 				/* We have been continued. */
123518de8d7fSPeter Avalos 				continue;
123618de8d7fSPeter Avalos 
123718de8d7fSPeter Avalos 			case 'B':
1238664f4763Szrj 				if ((r = sshbuf_putf(berr,
1239664f4763Szrj 				    "%cB\r\n", efc->escape_char)) != 0)
124050a69bb5SSascha Wildner 					fatal_fr(r, "sshbuf_putf");
1241ce74bacaSMatthew Dillon 				channel_request_start(ssh, c->self, "break", 0);
1242664f4763Szrj 				if ((r = sshpkt_put_u32(ssh, 1000)) != 0 ||
1243664f4763Szrj 				    (r = sshpkt_send(ssh)) != 0)
124450a69bb5SSascha Wildner 					fatal_fr(r, "send packet");
124518de8d7fSPeter Avalos 				continue;
124618de8d7fSPeter Avalos 
124718de8d7fSPeter Avalos 			case 'R':
124850a69bb5SSascha Wildner 				if (ssh->compat & SSH_BUG_NOREKEY)
124918de8d7fSPeter Avalos 					logit("Server does not "
125018de8d7fSPeter Avalos 					    "support re-keying");
125118de8d7fSPeter Avalos 				else
125218de8d7fSPeter Avalos 					need_rekeying = 1;
125318de8d7fSPeter Avalos 				continue;
125418de8d7fSPeter Avalos 
125536e94dc5SPeter Avalos 			case 'V':
125636e94dc5SPeter Avalos 				/* FALLTHROUGH */
125736e94dc5SPeter Avalos 			case 'v':
125836e94dc5SPeter Avalos 				if (c && c->ctl_chan != -1)
125936e94dc5SPeter Avalos 					goto noescape;
126036e94dc5SPeter Avalos 				if (!log_is_on_stderr()) {
1261664f4763Szrj 					if ((r = sshbuf_putf(berr,
126236e94dc5SPeter Avalos 					    "%c%c [Logging to syslog]\r\n",
1263664f4763Szrj 					    efc->escape_char, ch)) != 0)
126450a69bb5SSascha Wildner 						fatal_fr(r, "sshbuf_putf");
126536e94dc5SPeter Avalos 					continue;
126636e94dc5SPeter Avalos 				}
126736e94dc5SPeter Avalos 				if (ch == 'V' && options.log_level >
126836e94dc5SPeter Avalos 				    SYSLOG_LEVEL_QUIET)
126936e94dc5SPeter Avalos 					log_change_level(--options.log_level);
127036e94dc5SPeter Avalos 				if (ch == 'v' && options.log_level <
127136e94dc5SPeter Avalos 				    SYSLOG_LEVEL_DEBUG3)
127236e94dc5SPeter Avalos 					log_change_level(++options.log_level);
1273664f4763Szrj 				if ((r = sshbuf_putf(berr,
1274ce74bacaSMatthew Dillon 				    "%c%c [LogLevel %s]\r\n",
1275ce74bacaSMatthew Dillon 				    efc->escape_char, ch,
1276664f4763Szrj 				    log_level_name(options.log_level))) != 0)
127750a69bb5SSascha Wildner 					fatal_fr(r, "sshbuf_putf");
127836e94dc5SPeter Avalos 				continue;
127936e94dc5SPeter Avalos 
128018de8d7fSPeter Avalos 			case '&':
1281*ba1276acSMatthew Dillon 				if (c->ctl_chan != -1)
128218de8d7fSPeter Avalos 					goto noescape;
128318de8d7fSPeter Avalos 				/*
128418de8d7fSPeter Avalos 				 * Detach the program (continue to serve
128518de8d7fSPeter Avalos 				 * connections, but put in background and no
128618de8d7fSPeter Avalos 				 * more new connections).
128718de8d7fSPeter Avalos 				 */
128818de8d7fSPeter Avalos 				/* Restore tty modes. */
12891c188a7fSPeter Avalos 				leave_raw_mode(
12901c188a7fSPeter Avalos 				    options.request_tty == REQUEST_TTY_FORCE);
129118de8d7fSPeter Avalos 
129218de8d7fSPeter Avalos 				/* Stop listening for new connections. */
1293ce74bacaSMatthew Dillon 				channel_stop_listening(ssh);
129418de8d7fSPeter Avalos 
129550a69bb5SSascha Wildner 				if ((r = sshbuf_putf(berr, "%c& "
129650a69bb5SSascha Wildner 				    "[backgrounded]\n", efc->escape_char)) != 0)
129750a69bb5SSascha Wildner 					fatal_fr(r, "sshbuf_putf");
129818de8d7fSPeter Avalos 
129918de8d7fSPeter Avalos 				/* Fork into background. */
130018de8d7fSPeter Avalos 				pid = fork();
13010cbfa66cSDaniel Fojt 				if (pid == -1) {
130218de8d7fSPeter Avalos 					error("fork: %.100s", strerror(errno));
130318de8d7fSPeter Avalos 					continue;
130418de8d7fSPeter Avalos 				}
130518de8d7fSPeter Avalos 				if (pid != 0) {	/* This is the parent. */
130618de8d7fSPeter Avalos 					/* The parent just exits. */
130718de8d7fSPeter Avalos 					exit(0);
130818de8d7fSPeter Avalos 				}
130918de8d7fSPeter Avalos 				/* The child continues serving connections. */
131018de8d7fSPeter Avalos 				/* fake EOF on stdin */
1311664f4763Szrj 				if ((r = sshbuf_put_u8(bin, 4)) != 0)
131250a69bb5SSascha Wildner 					fatal_fr(r, "sshbuf_put_u8");
131318de8d7fSPeter Avalos 				return -1;
131418de8d7fSPeter Avalos 			case '?':
1315ce74bacaSMatthew Dillon 				print_escape_help(berr, efc->escape_char,
131636e94dc5SPeter Avalos 				    (c && c->ctl_chan != -1),
131736e94dc5SPeter Avalos 				    log_is_on_stderr());
131818de8d7fSPeter Avalos 				continue;
131918de8d7fSPeter Avalos 
132018de8d7fSPeter Avalos 			case '#':
1321664f4763Szrj 				if ((r = sshbuf_putf(berr, "%c#\r\n",
1322664f4763Szrj 				    efc->escape_char)) != 0)
132350a69bb5SSascha Wildner 					fatal_fr(r, "sshbuf_putf");
1324ce74bacaSMatthew Dillon 				s = channel_open_message(ssh);
1325664f4763Szrj 				if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
132650a69bb5SSascha Wildner 					fatal_fr(r, "sshbuf_put");
132736e94dc5SPeter Avalos 				free(s);
132818de8d7fSPeter Avalos 				continue;
132918de8d7fSPeter Avalos 
133018de8d7fSPeter Avalos 			case 'C':
1331856ea928SPeter Avalos 				if (c && c->ctl_chan != -1)
1332cb5eb4f1SPeter Avalos 					goto noescape;
1333*ba1276acSMatthew Dillon 				if (options.enable_escape_commandline == 0) {
1334*ba1276acSMatthew Dillon 					if ((r = sshbuf_putf(berr,
1335*ba1276acSMatthew Dillon 					    "commandline disabled\r\n")) != 0)
1336*ba1276acSMatthew Dillon 						fatal_fr(r, "sshbuf_putf");
1337*ba1276acSMatthew Dillon 					continue;
1338*ba1276acSMatthew Dillon 				}
1339ce74bacaSMatthew Dillon 				process_cmdline(ssh);
134018de8d7fSPeter Avalos 				continue;
134118de8d7fSPeter Avalos 
134218de8d7fSPeter Avalos 			default:
1343ce74bacaSMatthew Dillon 				if (ch != efc->escape_char) {
1344664f4763Szrj 					if ((r = sshbuf_put_u8(bin,
1345664f4763Szrj 					    efc->escape_char)) != 0)
134650a69bb5SSascha Wildner 						fatal_fr(r, "sshbuf_put_u8");
134718de8d7fSPeter Avalos 					bytes++;
134818de8d7fSPeter Avalos 				}
134918de8d7fSPeter Avalos 				/* Escaped characters fall through here */
135018de8d7fSPeter Avalos 				break;
135118de8d7fSPeter Avalos 			}
135218de8d7fSPeter Avalos 		} else {
135318de8d7fSPeter Avalos 			/*
135418de8d7fSPeter Avalos 			 * The previous character was not an escape char.
135518de8d7fSPeter Avalos 			 * Check if this is an escape.
135618de8d7fSPeter Avalos 			 */
1357ce74bacaSMatthew Dillon 			if (last_was_cr && ch == efc->escape_char) {
135818de8d7fSPeter Avalos 				/*
135918de8d7fSPeter Avalos 				 * It is. Set the flag and continue to
136018de8d7fSPeter Avalos 				 * next character.
136118de8d7fSPeter Avalos 				 */
1362ce74bacaSMatthew Dillon 				efc->escape_pending = 1;
136318de8d7fSPeter Avalos 				continue;
136418de8d7fSPeter Avalos 			}
136518de8d7fSPeter Avalos 		}
136618de8d7fSPeter Avalos 
136718de8d7fSPeter Avalos 		/*
136818de8d7fSPeter Avalos 		 * Normal character.  Record whether it was a newline,
136918de8d7fSPeter Avalos 		 * and append it to the buffer.
137018de8d7fSPeter Avalos 		 */
137118de8d7fSPeter Avalos 		last_was_cr = (ch == '\r' || ch == '\n');
1372664f4763Szrj 		if ((r = sshbuf_put_u8(bin, ch)) != 0)
137350a69bb5SSascha Wildner 			fatal_fr(r, "sshbuf_put_u8");
137418de8d7fSPeter Avalos 		bytes++;
137518de8d7fSPeter Avalos 	}
137618de8d7fSPeter Avalos 	return bytes;
137718de8d7fSPeter Avalos }
137818de8d7fSPeter Avalos 
137918de8d7fSPeter Avalos /*
138018de8d7fSPeter Avalos  * Get packets from the connection input buffer, and process them as long as
138118de8d7fSPeter Avalos  * there are packets available.
138218de8d7fSPeter Avalos  *
138318de8d7fSPeter Avalos  * Any unknown packets received during the actual
138418de8d7fSPeter Avalos  * session cause the session to terminate.  This is
138518de8d7fSPeter Avalos  * intended to make debugging easier since no
138618de8d7fSPeter Avalos  * confirmations are sent.  Any compatible protocol
138718de8d7fSPeter Avalos  * extensions must be negotiated during the
138818de8d7fSPeter Avalos  * preparatory phase.
138918de8d7fSPeter Avalos  */
139018de8d7fSPeter Avalos 
139118de8d7fSPeter Avalos static void
client_process_buffered_input_packets(struct ssh * ssh)1392664f4763Szrj client_process_buffered_input_packets(struct ssh *ssh)
139318de8d7fSPeter Avalos {
1394664f4763Szrj 	ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, &quit_pending);
139518de8d7fSPeter Avalos }
139618de8d7fSPeter Avalos 
139718de8d7fSPeter Avalos /* scan buf[] for '~' before sending data to the peer */
139818de8d7fSPeter Avalos 
139918de8d7fSPeter Avalos /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
140018de8d7fSPeter Avalos void *
client_new_escape_filter_ctx(int escape_char)140118de8d7fSPeter Avalos client_new_escape_filter_ctx(int escape_char)
140218de8d7fSPeter Avalos {
140318de8d7fSPeter Avalos 	struct escape_filter_ctx *ret;
140418de8d7fSPeter Avalos 
140536e94dc5SPeter Avalos 	ret = xcalloc(1, sizeof(*ret));
140618de8d7fSPeter Avalos 	ret->escape_pending = 0;
140718de8d7fSPeter Avalos 	ret->escape_char = escape_char;
140818de8d7fSPeter Avalos 	return (void *)ret;
140918de8d7fSPeter Avalos }
141018de8d7fSPeter Avalos 
141118de8d7fSPeter Avalos /* Free the escape filter context on channel free */
141218de8d7fSPeter Avalos void
client_filter_cleanup(struct ssh * ssh,int cid,void * ctx)1413ce74bacaSMatthew Dillon client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
141418de8d7fSPeter Avalos {
141536e94dc5SPeter Avalos 	free(ctx);
141618de8d7fSPeter Avalos }
141718de8d7fSPeter Avalos 
141818de8d7fSPeter Avalos int
client_simple_escape_filter(struct ssh * ssh,Channel * c,char * buf,int len)1419ce74bacaSMatthew Dillon client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
142018de8d7fSPeter Avalos {
142118de8d7fSPeter Avalos 	if (c->extended_usage != CHAN_EXTENDED_WRITE)
142218de8d7fSPeter Avalos 		return 0;
142318de8d7fSPeter Avalos 
1424ce74bacaSMatthew Dillon 	return process_escapes(ssh, c, c->input, c->output, c->extended,
142518de8d7fSPeter Avalos 	    buf, len);
142618de8d7fSPeter Avalos }
142718de8d7fSPeter Avalos 
142818de8d7fSPeter Avalos static void
client_channel_closed(struct ssh * ssh,int id,int force,void * arg)1429*ba1276acSMatthew Dillon client_channel_closed(struct ssh *ssh, int id, int force, void *arg)
143018de8d7fSPeter Avalos {
1431ce74bacaSMatthew Dillon 	channel_cancel_cleanup(ssh, id);
143218de8d7fSPeter Avalos 	session_closed = 1;
14331c188a7fSPeter Avalos 	leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
143418de8d7fSPeter Avalos }
143518de8d7fSPeter Avalos 
143618de8d7fSPeter Avalos /*
143718de8d7fSPeter Avalos  * Implements the interactive session with the server.  This is called after
143818de8d7fSPeter Avalos  * the user has been authenticated, and a command has been started on the
143918de8d7fSPeter Avalos  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
144018de8d7fSPeter Avalos  * used as an escape character for terminating or suspending the session.
144118de8d7fSPeter Avalos  */
144218de8d7fSPeter Avalos int
client_loop(struct ssh * ssh,int have_pty,int escape_char_arg,int ssh2_chan_id)1443ce74bacaSMatthew Dillon client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
1444ce74bacaSMatthew Dillon     int ssh2_chan_id)
144518de8d7fSPeter Avalos {
1446ee116499SAntonio Huete Jimenez 	struct pollfd *pfd = NULL;
1447ee116499SAntonio Huete Jimenez 	u_int npfd_alloc = 0, npfd_active = 0;
144818de8d7fSPeter Avalos 	double start_time, total_time;
1449*ba1276acSMatthew Dillon 	int channel_did_enqueue = 0, r;
145018de8d7fSPeter Avalos 	u_int64_t ibytes, obytes;
1451ee116499SAntonio Huete Jimenez 	int conn_in_ready, conn_out_ready;
1452*ba1276acSMatthew Dillon 	sigset_t bsigset, osigset;
145318de8d7fSPeter Avalos 
145418de8d7fSPeter Avalos 	debug("Entering interactive session.");
1455*ba1276acSMatthew Dillon 	session_ident = ssh2_chan_id;
145618de8d7fSPeter Avalos 
1457e9778795SPeter Avalos 	if (options.control_master &&
1458e9778795SPeter Avalos 	    !option_clear_or_none(options.control_path)) {
1459e9778795SPeter Avalos 		debug("pledge: id");
14600cbfa66cSDaniel Fojt 		if (pledge("stdio rpath wpath cpath unix inet dns recvfd sendfd proc exec id tty",
1461e9778795SPeter Avalos 		    NULL) == -1)
146250a69bb5SSascha Wildner 			fatal_f("pledge(): %s", strerror(errno));
1463e9778795SPeter Avalos 
1464e9778795SPeter Avalos 	} else if (options.forward_x11 || options.permit_local_command) {
1465e9778795SPeter Avalos 		debug("pledge: exec");
1466e9778795SPeter Avalos 		if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1467e9778795SPeter Avalos 		    NULL) == -1)
146850a69bb5SSascha Wildner 			fatal_f("pledge(): %s", strerror(errno));
1469e9778795SPeter Avalos 
1470e9778795SPeter Avalos 	} else if (options.update_hostkeys) {
1471ee116499SAntonio Huete Jimenez 		debug("pledge: filesystem");
1472e9778795SPeter Avalos 		if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1473e9778795SPeter Avalos 		    NULL) == -1)
147450a69bb5SSascha Wildner 			fatal_f("pledge(): %s", strerror(errno));
1475e9778795SPeter Avalos 
1476e9778795SPeter Avalos 	} else if (!option_clear_or_none(options.proxy_command) ||
147750a69bb5SSascha Wildner 	    options.fork_after_authentication) {
1478e9778795SPeter Avalos 		debug("pledge: proc");
1479e9778795SPeter Avalos 		if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
148050a69bb5SSascha Wildner 			fatal_f("pledge(): %s", strerror(errno));
1481e9778795SPeter Avalos 
1482e9778795SPeter Avalos 	} else {
1483e9778795SPeter Avalos 		debug("pledge: network");
1484ce74bacaSMatthew Dillon 		if (pledge("stdio unix inet dns proc tty", NULL) == -1)
148550a69bb5SSascha Wildner 			fatal_f("pledge(): %s", strerror(errno));
1486e9778795SPeter Avalos 	}
1487e9778795SPeter Avalos 
1488*ba1276acSMatthew Dillon 	/* might be able to tighten now */
1489*ba1276acSMatthew Dillon 	client_repledge();
1490*ba1276acSMatthew Dillon 
1491664f4763Szrj 	start_time = monotime_double();
149218de8d7fSPeter Avalos 
149318de8d7fSPeter Avalos 	/* Initialize variables. */
149418de8d7fSPeter Avalos 	last_was_cr = 1;
149518de8d7fSPeter Avalos 	exit_status = -1;
1496664f4763Szrj 	connection_in = ssh_packet_get_connection_in(ssh);
1497664f4763Szrj 	connection_out = ssh_packet_get_connection_out(ssh);
149818de8d7fSPeter Avalos 
149918de8d7fSPeter Avalos 	quit_pending = 0;
150018de8d7fSPeter Avalos 
1501664f4763Szrj 	client_init_dispatch(ssh);
150218de8d7fSPeter Avalos 
150318de8d7fSPeter Avalos 	/*
150418de8d7fSPeter Avalos 	 * Set signal handlers, (e.g. to restore non-blocking mode)
150518de8d7fSPeter Avalos 	 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
150618de8d7fSPeter Avalos 	 */
15070cbfa66cSDaniel Fojt 	if (ssh_signal(SIGHUP, SIG_IGN) != SIG_IGN)
15080cbfa66cSDaniel Fojt 		ssh_signal(SIGHUP, signal_handler);
15090cbfa66cSDaniel Fojt 	if (ssh_signal(SIGINT, SIG_IGN) != SIG_IGN)
15100cbfa66cSDaniel Fojt 		ssh_signal(SIGINT, signal_handler);
15110cbfa66cSDaniel Fojt 	if (ssh_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
15120cbfa66cSDaniel Fojt 		ssh_signal(SIGQUIT, signal_handler);
15130cbfa66cSDaniel Fojt 	if (ssh_signal(SIGTERM, SIG_IGN) != SIG_IGN)
15140cbfa66cSDaniel Fojt 		ssh_signal(SIGTERM, signal_handler);
15150cbfa66cSDaniel Fojt 	ssh_signal(SIGWINCH, window_change_handler);
151618de8d7fSPeter Avalos 
151718de8d7fSPeter Avalos 	if (have_pty)
15181c188a7fSPeter Avalos 		enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
151918de8d7fSPeter Avalos 
15201c188a7fSPeter Avalos 	if (session_ident != -1) {
15211c188a7fSPeter Avalos 		if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1522ce74bacaSMatthew Dillon 			channel_register_filter(ssh, session_ident,
152318de8d7fSPeter Avalos 			    client_simple_escape_filter, NULL,
152418de8d7fSPeter Avalos 			    client_filter_cleanup,
15251c188a7fSPeter Avalos 			    client_new_escape_filter_ctx(
15261c188a7fSPeter Avalos 			    escape_char_arg));
15271c188a7fSPeter Avalos 		}
1528ce74bacaSMatthew Dillon 		channel_register_cleanup(ssh, session_ident,
152918de8d7fSPeter Avalos 		    client_channel_closed, 0);
15301c188a7fSPeter Avalos 	}
153118de8d7fSPeter Avalos 
153250a69bb5SSascha Wildner 	schedule_server_alive_check();
153350a69bb5SSascha Wildner 
1534*ba1276acSMatthew Dillon 	if (sigemptyset(&bsigset) == -1 ||
1535*ba1276acSMatthew Dillon 	    sigaddset(&bsigset, SIGHUP) == -1 ||
1536*ba1276acSMatthew Dillon 	    sigaddset(&bsigset, SIGINT) == -1 ||
1537*ba1276acSMatthew Dillon 	    sigaddset(&bsigset, SIGQUIT) == -1 ||
1538*ba1276acSMatthew Dillon 	    sigaddset(&bsigset, SIGTERM) == -1)
1539*ba1276acSMatthew Dillon 		error_f("bsigset setup: %s", strerror(errno));
1540*ba1276acSMatthew Dillon 
154118de8d7fSPeter Avalos 	/* Main loop of the client for the interactive session mode. */
154218de8d7fSPeter Avalos 	while (!quit_pending) {
1543*ba1276acSMatthew Dillon 		channel_did_enqueue = 0;
154418de8d7fSPeter Avalos 
154518de8d7fSPeter Avalos 		/* Process buffered packets sent by the server. */
1546664f4763Szrj 		client_process_buffered_input_packets(ssh);
154718de8d7fSPeter Avalos 
1548ce74bacaSMatthew Dillon 		if (session_closed && !channel_still_open(ssh))
154918de8d7fSPeter Avalos 			break;
155018de8d7fSPeter Avalos 
1551ce74bacaSMatthew Dillon 		if (ssh_packet_is_rekeying(ssh)) {
155218de8d7fSPeter Avalos 			debug("rekeying in progress");
1553e9778795SPeter Avalos 		} else if (need_rekeying) {
1554e9778795SPeter Avalos 			/* manual rekey request */
1555e9778795SPeter Avalos 			debug("need rekeying");
1556ce74bacaSMatthew Dillon 			if ((r = kex_start_rekex(ssh)) != 0)
155750a69bb5SSascha Wildner 				fatal_fr(r, "kex_start_rekex");
1558e9778795SPeter Avalos 			need_rekeying = 0;
155918de8d7fSPeter Avalos 		} else {
156018de8d7fSPeter Avalos 			/*
156118de8d7fSPeter Avalos 			 * Make packets from buffered channel data, and
156218de8d7fSPeter Avalos 			 * enqueue them for sending to the server.
156318de8d7fSPeter Avalos 			 */
1564664f4763Szrj 			if (ssh_packet_not_very_much_data_to_write(ssh))
1565*ba1276acSMatthew Dillon 				channel_did_enqueue = channel_output_poll(ssh);
156618de8d7fSPeter Avalos 
156718de8d7fSPeter Avalos 			/*
156818de8d7fSPeter Avalos 			 * Check if the window size has changed, and buffer a
156918de8d7fSPeter Avalos 			 * message about it to the server if so.
157018de8d7fSPeter Avalos 			 */
1571ce74bacaSMatthew Dillon 			client_check_window_change(ssh);
157218de8d7fSPeter Avalos 		}
157318de8d7fSPeter Avalos 		/*
157418de8d7fSPeter Avalos 		 * Wait until we have something to do (something becomes
157518de8d7fSPeter Avalos 		 * available on one of the descriptors).
157618de8d7fSPeter Avalos 		 */
1577*ba1276acSMatthew Dillon 		if (sigprocmask(SIG_BLOCK, &bsigset, &osigset) == -1)
1578*ba1276acSMatthew Dillon 			error_f("bsigset sigprocmask: %s", strerror(errno));
1579*ba1276acSMatthew Dillon 		if (quit_pending)
1580*ba1276acSMatthew Dillon 			break;
1581ee116499SAntonio Huete Jimenez 		client_wait_until_can_do_something(ssh, &pfd, &npfd_alloc,
1582*ba1276acSMatthew Dillon 		    &npfd_active, channel_did_enqueue, &osigset,
1583ee116499SAntonio Huete Jimenez 		    &conn_in_ready, &conn_out_ready);
1584*ba1276acSMatthew Dillon 		if (sigprocmask(SIG_SETMASK, &osigset, NULL) == -1)
1585*ba1276acSMatthew Dillon 			error_f("osigset sigprocmask: %s", strerror(errno));
158618de8d7fSPeter Avalos 
158718de8d7fSPeter Avalos 		if (quit_pending)
158818de8d7fSPeter Avalos 			break;
158918de8d7fSPeter Avalos 
1590ee116499SAntonio Huete Jimenez 		/* Do channel operations. */
1591ee116499SAntonio Huete Jimenez 		channel_after_poll(ssh, pfd, npfd_active);
159218de8d7fSPeter Avalos 
159318de8d7fSPeter Avalos 		/* Buffer input from the connection.  */
1594ee116499SAntonio Huete Jimenez 		if (conn_in_ready)
1595ee116499SAntonio Huete Jimenez 			client_process_net_input(ssh);
159618de8d7fSPeter Avalos 
159718de8d7fSPeter Avalos 		if (quit_pending)
159818de8d7fSPeter Avalos 			break;
159918de8d7fSPeter Avalos 
160050a69bb5SSascha Wildner 		/* A timeout may have triggered rekeying */
160150a69bb5SSascha Wildner 		if ((r = ssh_packet_check_rekey(ssh)) != 0)
160250a69bb5SSascha Wildner 			fatal_fr(r, "cannot start rekeying");
160350a69bb5SSascha Wildner 
160418de8d7fSPeter Avalos 		/*
160518de8d7fSPeter Avalos 		 * Send as much buffered packet data as possible to the
160618de8d7fSPeter Avalos 		 * sender.
160718de8d7fSPeter Avalos 		 */
1608ee116499SAntonio Huete Jimenez 		if (conn_out_ready) {
16090cbfa66cSDaniel Fojt 			if ((r = ssh_packet_write_poll(ssh)) != 0) {
16100cbfa66cSDaniel Fojt 				sshpkt_fatal(ssh, r,
16110cbfa66cSDaniel Fojt 				    "%s: ssh_packet_write_poll", __func__);
16120cbfa66cSDaniel Fojt 			}
16130cbfa66cSDaniel Fojt 		}
1614856ea928SPeter Avalos 
1615856ea928SPeter Avalos 		/*
1616856ea928SPeter Avalos 		 * If we are a backgrounded control master, and the
1617856ea928SPeter Avalos 		 * timeout has expired without any active client
1618856ea928SPeter Avalos 		 * connections, then quit.
1619856ea928SPeter Avalos 		 */
1620856ea928SPeter Avalos 		if (control_persist_exit_time > 0) {
162136e94dc5SPeter Avalos 			if (monotime() >= control_persist_exit_time) {
1622856ea928SPeter Avalos 				debug("ControlPersist timeout expired");
1623856ea928SPeter Avalos 				break;
1624856ea928SPeter Avalos 			}
1625856ea928SPeter Avalos 		}
162618de8d7fSPeter Avalos 	}
1627ee116499SAntonio Huete Jimenez 	free(pfd);
162818de8d7fSPeter Avalos 
162918de8d7fSPeter Avalos 	/* Terminate the session. */
163018de8d7fSPeter Avalos 
1631*ba1276acSMatthew Dillon 	/*
1632*ba1276acSMatthew Dillon 	 * In interactive mode (with pseudo tty) display a message indicating
1633*ba1276acSMatthew Dillon 	 * that the connection has been closed.
1634*ba1276acSMatthew Dillon 	 */
1635*ba1276acSMatthew Dillon 	if (have_pty && options.log_level >= SYSLOG_LEVEL_INFO)
1636*ba1276acSMatthew Dillon 		quit_message("Connection to %s closed.", host);
1637*ba1276acSMatthew Dillon 
1638*ba1276acSMatthew Dillon 
163918de8d7fSPeter Avalos 	/* Stop watching for window change. */
16400cbfa66cSDaniel Fojt 	ssh_signal(SIGWINCH, SIG_DFL);
164118de8d7fSPeter Avalos 
1642664f4763Szrj 	if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
1643664f4763Szrj 	    (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_BY_APPLICATION)) != 0 ||
1644664f4763Szrj 	    (r = sshpkt_put_cstring(ssh, "disconnected by user")) != 0 ||
1645664f4763Szrj 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||	/* language tag */
1646664f4763Szrj 	    (r = sshpkt_send(ssh)) != 0 ||
1647664f4763Szrj 	    (r = ssh_packet_write_wait(ssh)) != 0)
164850a69bb5SSascha Wildner 		fatal_fr(r, "send disconnect");
164940c002afSPeter Avalos 
1650ce74bacaSMatthew Dillon 	channel_free_all(ssh);
165118de8d7fSPeter Avalos 
165218de8d7fSPeter Avalos 	if (have_pty)
16531c188a7fSPeter Avalos 		leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
165418de8d7fSPeter Avalos 
165518de8d7fSPeter Avalos 	/*
165618de8d7fSPeter Avalos 	 * If there was no shell or command requested, there will be no remote
165718de8d7fSPeter Avalos 	 * exit status to be returned.  In that case, clear error code if the
165818de8d7fSPeter Avalos 	 * connection was deliberately terminated at this end.
165918de8d7fSPeter Avalos 	 */
166050a69bb5SSascha Wildner 	if (options.session_type == SESSION_TYPE_NONE &&
166150a69bb5SSascha Wildner 	    received_signal == SIGTERM) {
166218de8d7fSPeter Avalos 		received_signal = 0;
166318de8d7fSPeter Avalos 		exit_status = 0;
166418de8d7fSPeter Avalos 	}
166518de8d7fSPeter Avalos 
1666ce74bacaSMatthew Dillon 	if (received_signal) {
1667ce74bacaSMatthew Dillon 		verbose("Killed by signal %d.", (int) received_signal);
166850a69bb5SSascha Wildner 		cleanup_exit(255);
1669ce74bacaSMatthew Dillon 	}
167018de8d7fSPeter Avalos 
167118de8d7fSPeter Avalos 	/* Report bytes transferred, and transfer rates. */
1672664f4763Szrj 	total_time = monotime_double() - start_time;
1673664f4763Szrj 	ssh_packet_get_bytes(ssh, &ibytes, &obytes);
167418de8d7fSPeter Avalos 	verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
16759f304aafSPeter Avalos 	    (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
167618de8d7fSPeter Avalos 	if (total_time > 0)
167718de8d7fSPeter Avalos 		verbose("Bytes per second: sent %.1f, received %.1f",
167818de8d7fSPeter Avalos 		    obytes / total_time, ibytes / total_time);
167918de8d7fSPeter Avalos 	/* Return the exit status of the program. */
168018de8d7fSPeter Avalos 	debug("Exit status %d", exit_status);
168118de8d7fSPeter Avalos 	return exit_status;
168218de8d7fSPeter Avalos }
168318de8d7fSPeter Avalos 
168418de8d7fSPeter Avalos /*********/
168518de8d7fSPeter Avalos 
168618de8d7fSPeter Avalos static Channel *
client_request_forwarded_tcpip(struct ssh * ssh,const char * request_type,int rchan,u_int rwindow,u_int rmaxpack)1687ce74bacaSMatthew Dillon client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
1688ce74bacaSMatthew Dillon     int rchan, u_int rwindow, u_int rmaxpack)
168918de8d7fSPeter Avalos {
169018de8d7fSPeter Avalos 	Channel *c = NULL;
1691ce74bacaSMatthew Dillon 	struct sshbuf *b = NULL;
169218de8d7fSPeter Avalos 	char *listen_address, *originator_address;
1693664f4763Szrj 	u_int listen_port, originator_port;
1694ce74bacaSMatthew Dillon 	int r;
169518de8d7fSPeter Avalos 
169618de8d7fSPeter Avalos 	/* Get rest of the packet */
1697664f4763Szrj 	if ((r = sshpkt_get_cstring(ssh, &listen_address, NULL)) != 0 ||
1698664f4763Szrj 	    (r = sshpkt_get_u32(ssh, &listen_port)) != 0 ||
1699664f4763Szrj 	    (r = sshpkt_get_cstring(ssh, &originator_address, NULL)) != 0 ||
1700664f4763Szrj 	    (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1701664f4763Szrj 	    (r = sshpkt_get_end(ssh)) != 0)
170250a69bb5SSascha Wildner 		fatal_fr(r, "parse packet");
170318de8d7fSPeter Avalos 
170450a69bb5SSascha Wildner 	debug_f("listen %s port %d, originator %s port %d",
170536e94dc5SPeter Avalos 	    listen_address, listen_port, originator_address, originator_port);
170618de8d7fSPeter Avalos 
1707664f4763Szrj 	if (listen_port > 0xffff)
170850a69bb5SSascha Wildner 		error_f("invalid listen port");
1709664f4763Szrj 	else if (originator_port > 0xffff)
171050a69bb5SSascha Wildner 		error_f("invalid originator port");
1711664f4763Szrj 	else {
1712664f4763Szrj 		c = channel_connect_by_listen_address(ssh,
1713664f4763Szrj 		    listen_address, listen_port, "forwarded-tcpip",
1714664f4763Szrj 		    originator_address);
1715664f4763Szrj 	}
171618de8d7fSPeter Avalos 
1717ce74bacaSMatthew Dillon 	if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1718ce74bacaSMatthew Dillon 		if ((b = sshbuf_new()) == NULL) {
171950a69bb5SSascha Wildner 			error_f("alloc reply");
1720ce74bacaSMatthew Dillon 			goto out;
1721ce74bacaSMatthew Dillon 		}
1722ce74bacaSMatthew Dillon 		/* reconstruct and send to muxclient */
1723ce74bacaSMatthew Dillon 		if ((r = sshbuf_put_u8(b, 0)) != 0 ||	/* padlen */
1724ce74bacaSMatthew Dillon 		    (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1725ce74bacaSMatthew Dillon 		    (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1726ce74bacaSMatthew Dillon 		    (r = sshbuf_put_u32(b, rchan)) != 0 ||
1727ce74bacaSMatthew Dillon 		    (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1728ce74bacaSMatthew Dillon 		    (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1729ce74bacaSMatthew Dillon 		    (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1730ce74bacaSMatthew Dillon 		    (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1731ce74bacaSMatthew Dillon 		    (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1732ce74bacaSMatthew Dillon 		    (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1733ce74bacaSMatthew Dillon 		    (r = sshbuf_put_stringb(c->output, b)) != 0) {
173450a69bb5SSascha Wildner 			error_fr(r, "compose for muxclient");
1735ce74bacaSMatthew Dillon 			goto out;
1736ce74bacaSMatthew Dillon 		}
1737ce74bacaSMatthew Dillon 	}
1738ce74bacaSMatthew Dillon 
1739ce74bacaSMatthew Dillon  out:
1740ce74bacaSMatthew Dillon 	sshbuf_free(b);
174136e94dc5SPeter Avalos 	free(originator_address);
174236e94dc5SPeter Avalos 	free(listen_address);
174336e94dc5SPeter Avalos 	return c;
174436e94dc5SPeter Avalos }
174536e94dc5SPeter Avalos 
174636e94dc5SPeter Avalos static Channel *
client_request_forwarded_streamlocal(struct ssh * ssh,const char * request_type,int rchan)1747ce74bacaSMatthew Dillon client_request_forwarded_streamlocal(struct ssh *ssh,
1748ce74bacaSMatthew Dillon     const char *request_type, int rchan)
174936e94dc5SPeter Avalos {
175036e94dc5SPeter Avalos 	Channel *c = NULL;
175136e94dc5SPeter Avalos 	char *listen_path;
1752664f4763Szrj 	int r;
175336e94dc5SPeter Avalos 
175436e94dc5SPeter Avalos 	/* Get the remote path. */
1755664f4763Szrj 	if ((r = sshpkt_get_cstring(ssh, &listen_path, NULL)) != 0 ||
1756664f4763Szrj 	    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 ||	/* reserved */
1757664f4763Szrj 	    (r = sshpkt_get_end(ssh)) != 0)
175850a69bb5SSascha Wildner 		fatal_fr(r, "parse packet");
175936e94dc5SPeter Avalos 
176050a69bb5SSascha Wildner 	debug_f("request: %s", listen_path);
176136e94dc5SPeter Avalos 
1762ce74bacaSMatthew Dillon 	c = channel_connect_by_listen_path(ssh, listen_path,
176336e94dc5SPeter Avalos 	    "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
176436e94dc5SPeter Avalos 	free(listen_path);
176518de8d7fSPeter Avalos 	return c;
176618de8d7fSPeter Avalos }
176718de8d7fSPeter Avalos 
176818de8d7fSPeter Avalos static Channel *
client_request_x11(struct ssh * ssh,const char * request_type,int rchan)1769ce74bacaSMatthew Dillon client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
177018de8d7fSPeter Avalos {
177118de8d7fSPeter Avalos 	Channel *c = NULL;
177218de8d7fSPeter Avalos 	char *originator;
1773664f4763Szrj 	u_int originator_port;
1774664f4763Szrj 	int r, sock;
177518de8d7fSPeter Avalos 
177618de8d7fSPeter Avalos 	if (!options.forward_x11) {
177718de8d7fSPeter Avalos 		error("Warning: ssh server tried X11 forwarding.");
177818de8d7fSPeter Avalos 		error("Warning: this is probably a break-in attempt by a "
177918de8d7fSPeter Avalos 		    "malicious server.");
178018de8d7fSPeter Avalos 		return NULL;
178118de8d7fSPeter Avalos 	}
1782*ba1276acSMatthew Dillon 	if (x11_refuse_time != 0 && monotime() >= x11_refuse_time) {
1783856ea928SPeter Avalos 		verbose("Rejected X11 connection after ForwardX11Timeout "
1784856ea928SPeter Avalos 		    "expired");
1785856ea928SPeter Avalos 		return NULL;
1786856ea928SPeter Avalos 	}
1787664f4763Szrj 	if ((r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
1788664f4763Szrj 	    (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1789664f4763Szrj 	    (r = sshpkt_get_end(ssh)) != 0)
179050a69bb5SSascha Wildner 		fatal_fr(r, "parse packet");
179118de8d7fSPeter Avalos 	/* XXX check permission */
1792664f4763Szrj 	/* XXX range check originator port? */
1793664f4763Szrj 	debug("client_request_x11: request from %s %u", originator,
179418de8d7fSPeter Avalos 	    originator_port);
179536e94dc5SPeter Avalos 	free(originator);
1796ce74bacaSMatthew Dillon 	sock = x11_connect_display(ssh);
179718de8d7fSPeter Avalos 	if (sock < 0)
179818de8d7fSPeter Avalos 		return NULL;
1799*ba1276acSMatthew Dillon 	c = channel_new(ssh, "x11-connection",
180018de8d7fSPeter Avalos 	    SSH_CHANNEL_X11_OPEN, sock, sock, -1,
180118de8d7fSPeter Avalos 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
180218de8d7fSPeter Avalos 	c->force_drain = 1;
180318de8d7fSPeter Avalos 	return c;
180418de8d7fSPeter Avalos }
180518de8d7fSPeter Avalos 
180618de8d7fSPeter Avalos static Channel *
client_request_agent(struct ssh * ssh,const char * request_type,int rchan)1807ce74bacaSMatthew Dillon client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
180818de8d7fSPeter Avalos {
180918de8d7fSPeter Avalos 	Channel *c = NULL;
1810e9778795SPeter Avalos 	int r, sock;
181118de8d7fSPeter Avalos 
181218de8d7fSPeter Avalos 	if (!options.forward_agent) {
181318de8d7fSPeter Avalos 		error("Warning: ssh server tried agent forwarding.");
181418de8d7fSPeter Avalos 		error("Warning: this is probably a break-in attempt by a "
181518de8d7fSPeter Avalos 		    "malicious server.");
181618de8d7fSPeter Avalos 		return NULL;
181718de8d7fSPeter Avalos 	}
18180cbfa66cSDaniel Fojt 	if (forward_agent_sock_path == NULL) {
18190cbfa66cSDaniel Fojt 		r = ssh_get_authentication_socket(&sock);
18200cbfa66cSDaniel Fojt 	} else {
18210cbfa66cSDaniel Fojt 		r = ssh_get_authentication_socket_path(forward_agent_sock_path, &sock);
18220cbfa66cSDaniel Fojt 	}
18230cbfa66cSDaniel Fojt 	if (r != 0) {
1824e9778795SPeter Avalos 		if (r != SSH_ERR_AGENT_NOT_PRESENT)
182550a69bb5SSascha Wildner 			debug_fr(r, "ssh_get_authentication_socket");
182618de8d7fSPeter Avalos 		return NULL;
1827e9778795SPeter Avalos 	}
1828ee116499SAntonio Huete Jimenez 	if ((r = ssh_agent_bind_hostkey(sock, ssh->kex->initial_hostkey,
1829ee116499SAntonio Huete Jimenez 	    ssh->kex->session_id, ssh->kex->initial_sig, 1)) == 0)
1830ee116499SAntonio Huete Jimenez 		debug_f("bound agent to hostkey");
1831ee116499SAntonio Huete Jimenez 	else
1832ee116499SAntonio Huete Jimenez 		debug2_fr(r, "ssh_agent_bind_hostkey");
1833ee116499SAntonio Huete Jimenez 
1834*ba1276acSMatthew Dillon 	c = channel_new(ssh, "agent-connection",
183518de8d7fSPeter Avalos 	    SSH_CHANNEL_OPEN, sock, sock, -1,
183618de8d7fSPeter Avalos 	    CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
183718de8d7fSPeter Avalos 	    "authentication agent connection", 1);
183818de8d7fSPeter Avalos 	c->force_drain = 1;
183918de8d7fSPeter Avalos 	return c;
184018de8d7fSPeter Avalos }
184118de8d7fSPeter Avalos 
1842664f4763Szrj char *
client_request_tun_fwd(struct ssh * ssh,int tun_mode,int local_tun,int remote_tun,channel_open_fn * cb,void * cbctx)1843ce74bacaSMatthew Dillon client_request_tun_fwd(struct ssh *ssh, int tun_mode,
18440cbfa66cSDaniel Fojt     int local_tun, int remote_tun, channel_open_fn *cb, void *cbctx)
184518de8d7fSPeter Avalos {
184618de8d7fSPeter Avalos 	Channel *c;
1847664f4763Szrj 	int r, fd;
1848664f4763Szrj 	char *ifname = NULL;
184918de8d7fSPeter Avalos 
185018de8d7fSPeter Avalos 	if (tun_mode == SSH_TUNMODE_NO)
185118de8d7fSPeter Avalos 		return 0;
185218de8d7fSPeter Avalos 
185318de8d7fSPeter Avalos 	debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
185418de8d7fSPeter Avalos 
185518de8d7fSPeter Avalos 	/* Open local tunnel device */
1856664f4763Szrj 	if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) {
185718de8d7fSPeter Avalos 		error("Tunnel device open failed.");
1858664f4763Szrj 		return NULL;
185918de8d7fSPeter Avalos 	}
1860664f4763Szrj 	debug("Tunnel forwarding using interface %s", ifname);
186118de8d7fSPeter Avalos 
1862*ba1276acSMatthew Dillon 	c = channel_new(ssh, "tun-connection", SSH_CHANNEL_OPENING, fd, fd, -1,
186318de8d7fSPeter Avalos 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
186418de8d7fSPeter Avalos 	c->datagram = 1;
186518de8d7fSPeter Avalos 
186618de8d7fSPeter Avalos #if defined(SSH_TUN_FILTER)
186718de8d7fSPeter Avalos 	if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1868ce74bacaSMatthew Dillon 		channel_register_filter(ssh, c->self, sys_tun_infilter,
186918de8d7fSPeter Avalos 		    sys_tun_outfilter, NULL, NULL);
187018de8d7fSPeter Avalos #endif
187118de8d7fSPeter Avalos 
18720cbfa66cSDaniel Fojt 	if (cb != NULL)
18730cbfa66cSDaniel Fojt 		channel_register_open_confirm(ssh, c->self, cb, cbctx);
18740cbfa66cSDaniel Fojt 
1875664f4763Szrj 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1876664f4763Szrj 	    (r = sshpkt_put_cstring(ssh, "tun@openssh.com")) != 0 ||
1877664f4763Szrj 	    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1878664f4763Szrj 	    (r = sshpkt_put_u32(ssh, c->local_window_max)) != 0 ||
1879664f4763Szrj 	    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1880664f4763Szrj 	    (r = sshpkt_put_u32(ssh, tun_mode)) != 0 ||
1881664f4763Szrj 	    (r = sshpkt_put_u32(ssh, remote_tun)) != 0 ||
1882664f4763Szrj 	    (r = sshpkt_send(ssh)) != 0)
1883664f4763Szrj 		sshpkt_fatal(ssh, r, "%s: send reply", __func__);
188418de8d7fSPeter Avalos 
1885664f4763Szrj 	return ifname;
188618de8d7fSPeter Avalos }
188718de8d7fSPeter Avalos 
188818de8d7fSPeter Avalos /* XXXX move to generic input handler */
1889e9778795SPeter Avalos static int
client_input_channel_open(int type,u_int32_t seq,struct ssh * ssh)1890ce74bacaSMatthew Dillon client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
189118de8d7fSPeter Avalos {
189218de8d7fSPeter Avalos 	Channel *c = NULL;
1893664f4763Szrj 	char *ctype = NULL;
1894664f4763Szrj 	int r;
1895664f4763Szrj 	u_int rchan;
1896664f4763Szrj 	size_t len;
1897664f4763Szrj 	u_int rmaxpack, rwindow;
189818de8d7fSPeter Avalos 
1899664f4763Szrj 	if ((r = sshpkt_get_cstring(ssh, &ctype, &len)) != 0 ||
1900664f4763Szrj 	    (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
1901664f4763Szrj 	    (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
1902664f4763Szrj 	    (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
1903664f4763Szrj 		goto out;
190418de8d7fSPeter Avalos 
190518de8d7fSPeter Avalos 	debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
190618de8d7fSPeter Avalos 	    ctype, rchan, rwindow, rmaxpack);
190718de8d7fSPeter Avalos 
190818de8d7fSPeter Avalos 	if (strcmp(ctype, "forwarded-tcpip") == 0) {
1909ce74bacaSMatthew Dillon 		c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1910ce74bacaSMatthew Dillon 		    rmaxpack);
191136e94dc5SPeter Avalos 	} else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1912ce74bacaSMatthew Dillon 		c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
191318de8d7fSPeter Avalos 	} else if (strcmp(ctype, "x11") == 0) {
1914ce74bacaSMatthew Dillon 		c = client_request_x11(ssh, ctype, rchan);
191518de8d7fSPeter Avalos 	} else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1916ce74bacaSMatthew Dillon 		c = client_request_agent(ssh, ctype, rchan);
191718de8d7fSPeter Avalos 	}
1918ce74bacaSMatthew Dillon 	if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1919ce74bacaSMatthew Dillon 		debug3("proxied to downstream: %s", ctype);
1920ce74bacaSMatthew Dillon 	} else if (c != NULL) {
192118de8d7fSPeter Avalos 		debug("confirm %s", ctype);
192218de8d7fSPeter Avalos 		c->remote_id = rchan;
1923ce74bacaSMatthew Dillon 		c->have_remote_id = 1;
192418de8d7fSPeter Avalos 		c->remote_window = rwindow;
192518de8d7fSPeter Avalos 		c->remote_maxpacket = rmaxpack;
192618de8d7fSPeter Avalos 		if (c->type != SSH_CHANNEL_CONNECTING) {
1927664f4763Szrj 			if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1928664f4763Szrj 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1929664f4763Szrj 			    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1930664f4763Szrj 			    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1931664f4763Szrj 			    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1932664f4763Szrj 			    (r = sshpkt_send(ssh)) != 0)
1933664f4763Szrj 				sshpkt_fatal(ssh, r, "%s: send reply", __func__);
193418de8d7fSPeter Avalos 		}
193518de8d7fSPeter Avalos 	} else {
193618de8d7fSPeter Avalos 		debug("failure %s", ctype);
1937664f4763Szrj 		if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1938664f4763Szrj 		    (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
1939664f4763Szrj 		    (r = sshpkt_put_u32(ssh, SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED)) != 0 ||
1940664f4763Szrj 		    (r = sshpkt_put_cstring(ssh, "open failed")) != 0 ||
1941664f4763Szrj 		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1942664f4763Szrj 		    (r = sshpkt_send(ssh)) != 0)
1943664f4763Szrj 			sshpkt_fatal(ssh, r, "%s: send failure", __func__);
194418de8d7fSPeter Avalos 	}
1945664f4763Szrj 	r = 0;
1946664f4763Szrj  out:
194736e94dc5SPeter Avalos 	free(ctype);
1948664f4763Szrj 	return r;
194918de8d7fSPeter Avalos }
1950e9778795SPeter Avalos 
1951e9778795SPeter Avalos static int
client_input_channel_req(int type,u_int32_t seq,struct ssh * ssh)1952ce74bacaSMatthew Dillon client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
195318de8d7fSPeter Avalos {
195418de8d7fSPeter Avalos 	Channel *c = NULL;
1955664f4763Szrj 	char *rtype = NULL;
1956664f4763Szrj 	u_char reply;
1957664f4763Szrj 	u_int id, exitval;
1958664f4763Szrj 	int r, success = 0;
195918de8d7fSPeter Avalos 
1960664f4763Szrj 	if ((r = sshpkt_get_u32(ssh, &id)) != 0)
1961664f4763Szrj 		return r;
1962664f4763Szrj 	if (id <= INT_MAX)
1963ce74bacaSMatthew Dillon 		c = channel_lookup(ssh, id);
1964ce74bacaSMatthew Dillon 	if (channel_proxy_upstream(c, type, seq, ssh))
1965ce74bacaSMatthew Dillon 		return 0;
1966664f4763Szrj 	if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
1967664f4763Szrj 	    (r = sshpkt_get_u8(ssh, &reply)) != 0)
1968664f4763Szrj 		goto out;
196918de8d7fSPeter Avalos 
1970664f4763Szrj 	debug("client_input_channel_req: channel %u rtype %s reply %d",
197118de8d7fSPeter Avalos 	    id, rtype, reply);
197218de8d7fSPeter Avalos 
1973664f4763Szrj 	if (c == NULL) {
197418de8d7fSPeter Avalos 		error("client_input_channel_req: channel %d: "
197518de8d7fSPeter Avalos 		    "unknown channel", id);
197618de8d7fSPeter Avalos 	} else if (strcmp(rtype, "eow@openssh.com") == 0) {
1977664f4763Szrj 		if ((r = sshpkt_get_end(ssh)) != 0)
1978664f4763Szrj 			goto out;
1979ce74bacaSMatthew Dillon 		chan_rcvd_eow(ssh, c);
198018de8d7fSPeter Avalos 	} else if (strcmp(rtype, "exit-status") == 0) {
1981664f4763Szrj 		if ((r = sshpkt_get_u32(ssh, &exitval)) != 0)
1982664f4763Szrj 			goto out;
1983856ea928SPeter Avalos 		if (c->ctl_chan != -1) {
1984ce74bacaSMatthew Dillon 			mux_exit_message(ssh, c, exitval);
1985856ea928SPeter Avalos 			success = 1;
1986664f4763Szrj 		} else if ((int)id == session_ident) {
1987856ea928SPeter Avalos 			/* Record exit value of local session */
198818de8d7fSPeter Avalos 			success = 1;
198918de8d7fSPeter Avalos 			exit_status = exitval;
199018de8d7fSPeter Avalos 		} else {
1991856ea928SPeter Avalos 			/* Probably for a mux channel that has already closed */
199250a69bb5SSascha Wildner 			debug_f("no sink for exit-status on channel %d",
199350a69bb5SSascha Wildner 			    id);
199418de8d7fSPeter Avalos 		}
1995664f4763Szrj 		if ((r = sshpkt_get_end(ssh)) != 0)
1996664f4763Szrj 			goto out;
199718de8d7fSPeter Avalos 	}
199836e94dc5SPeter Avalos 	if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1999ce74bacaSMatthew Dillon 		if (!c->have_remote_id)
200050a69bb5SSascha Wildner 			fatal_f("channel %d: no remote_id", c->self);
2001664f4763Szrj 		if ((r = sshpkt_start(ssh, success ?
2002664f4763Szrj 		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
2003664f4763Szrj 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2004664f4763Szrj 		    (r = sshpkt_send(ssh)) != 0)
2005664f4763Szrj 			sshpkt_fatal(ssh, r, "%s: send failure", __func__);
200618de8d7fSPeter Avalos 	}
2007664f4763Szrj 	r = 0;
2008664f4763Szrj  out:
200936e94dc5SPeter Avalos 	free(rtype);
2010664f4763Szrj 	return r;
201118de8d7fSPeter Avalos }
2012e9778795SPeter Avalos 
2013e9778795SPeter Avalos struct hostkeys_update_ctx {
2014e9778795SPeter Avalos 	/* The hostname and (optionally) IP address string for the server */
2015e9778795SPeter Avalos 	char *host_str, *ip_str;
2016e9778795SPeter Avalos 
2017e9778795SPeter Avalos 	/*
2018e9778795SPeter Avalos 	 * Keys received from the server and a flag for each indicating
2019e9778795SPeter Avalos 	 * whether they already exist in known_hosts.
202050a69bb5SSascha Wildner 	 * keys_match is filled in by hostkeys_find() and later (for new
2021*ba1276acSMatthew Dillon 	 * keys) by client_global_hostkeys_prove_confirm().
2022e9778795SPeter Avalos 	 */
2023e9778795SPeter Avalos 	struct sshkey **keys;
202450a69bb5SSascha Wildner 	u_int *keys_match;	/* mask of HKF_MATCH_* from hostfile.h */
202550a69bb5SSascha Wildner 	int *keys_verified;	/* flag for new keys verified by server */
202650a69bb5SSascha Wildner 	size_t nkeys, nnew, nincomplete; /* total, new keys, incomplete match */
2027e9778795SPeter Avalos 
2028e9778795SPeter Avalos 	/*
2029e9778795SPeter Avalos 	 * Keys that are in known_hosts, but were not present in the update
2030e9778795SPeter Avalos 	 * from the server (i.e. scheduled to be deleted).
2031e9778795SPeter Avalos 	 * Filled in by hostkeys_find().
2032e9778795SPeter Avalos 	 */
2033e9778795SPeter Avalos 	struct sshkey **old_keys;
2034e9778795SPeter Avalos 	size_t nold;
203550a69bb5SSascha Wildner 
203650a69bb5SSascha Wildner 	/* Various special cases. */
203750a69bb5SSascha Wildner 	int complex_hostspec;	/* wildcard or manual pattern-list host name */
203850a69bb5SSascha Wildner 	int ca_available;	/* saw CA key for this host */
203950a69bb5SSascha Wildner 	int old_key_seen;	/* saw old key with other name/addr */
204050a69bb5SSascha Wildner 	int other_name_seen;	/* saw key with other name/addr */
2041e9778795SPeter Avalos };
2042e9778795SPeter Avalos 
204318de8d7fSPeter Avalos static void
hostkeys_update_ctx_free(struct hostkeys_update_ctx * ctx)2044e9778795SPeter Avalos hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
2045e9778795SPeter Avalos {
2046e9778795SPeter Avalos 	size_t i;
2047e9778795SPeter Avalos 
2048e9778795SPeter Avalos 	if (ctx == NULL)
2049e9778795SPeter Avalos 		return;
2050e9778795SPeter Avalos 	for (i = 0; i < ctx->nkeys; i++)
2051e9778795SPeter Avalos 		sshkey_free(ctx->keys[i]);
2052e9778795SPeter Avalos 	free(ctx->keys);
205350a69bb5SSascha Wildner 	free(ctx->keys_match);
205450a69bb5SSascha Wildner 	free(ctx->keys_verified);
2055e9778795SPeter Avalos 	for (i = 0; i < ctx->nold; i++)
2056e9778795SPeter Avalos 		sshkey_free(ctx->old_keys[i]);
2057e9778795SPeter Avalos 	free(ctx->old_keys);
2058e9778795SPeter Avalos 	free(ctx->host_str);
2059e9778795SPeter Avalos 	free(ctx->ip_str);
2060e9778795SPeter Avalos 	free(ctx);
2061e9778795SPeter Avalos }
2062e9778795SPeter Avalos 
206350a69bb5SSascha Wildner /*
206450a69bb5SSascha Wildner  * Returns non-zero if a known_hosts hostname list is not of a form that
206550a69bb5SSascha Wildner  * can be handled by UpdateHostkeys. These include wildcard hostnames and
206650a69bb5SSascha Wildner  * hostnames lists that do not follow the form host[,ip].
206750a69bb5SSascha Wildner  */
206850a69bb5SSascha Wildner static int
hostspec_is_complex(const char * hosts)206950a69bb5SSascha Wildner hostspec_is_complex(const char *hosts)
207050a69bb5SSascha Wildner {
207150a69bb5SSascha Wildner 	char *cp;
207250a69bb5SSascha Wildner 
207350a69bb5SSascha Wildner 	/* wildcard */
207450a69bb5SSascha Wildner 	if (strchr(hosts, '*') != NULL || strchr(hosts, '?') != NULL)
207550a69bb5SSascha Wildner 		return 1;
207650a69bb5SSascha Wildner 	/* single host/ip = ok */
207750a69bb5SSascha Wildner 	if ((cp = strchr(hosts, ',')) == NULL)
207850a69bb5SSascha Wildner 		return 0;
207950a69bb5SSascha Wildner 	/* more than two entries on the line */
208050a69bb5SSascha Wildner 	if (strchr(cp + 1, ',') != NULL)
208150a69bb5SSascha Wildner 		return 1;
208250a69bb5SSascha Wildner 	/* XXX maybe parse cp+1 and ensure it is an IP? */
208350a69bb5SSascha Wildner 	return 0;
208450a69bb5SSascha Wildner }
208550a69bb5SSascha Wildner 
208650a69bb5SSascha Wildner /* callback to search for ctx->keys in known_hosts */
2087e9778795SPeter Avalos static int
hostkeys_find(struct hostkey_foreach_line * l,void * _ctx)2088e9778795SPeter Avalos hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
2089e9778795SPeter Avalos {
2090e9778795SPeter Avalos 	struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2091e9778795SPeter Avalos 	size_t i;
2092e9778795SPeter Avalos 	struct sshkey **tmp;
2093e9778795SPeter Avalos 
209450a69bb5SSascha Wildner 	if (l->key == NULL)
2095e9778795SPeter Avalos 		return 0;
209650a69bb5SSascha Wildner 	if (l->status != HKF_STATUS_MATCHED) {
209750a69bb5SSascha Wildner 		/* Record if one of the keys appears on a non-matching line */
209850a69bb5SSascha Wildner 		for (i = 0; i < ctx->nkeys; i++) {
209950a69bb5SSascha Wildner 			if (sshkey_equal(l->key, ctx->keys[i])) {
210050a69bb5SSascha Wildner 				ctx->other_name_seen = 1;
210150a69bb5SSascha Wildner 				debug3_f("found %s key under different "
210250a69bb5SSascha Wildner 				    "name/addr at %s:%ld",
210350a69bb5SSascha Wildner 				    sshkey_ssh_name(ctx->keys[i]),
210450a69bb5SSascha Wildner 				    l->path, l->linenum);
210550a69bb5SSascha Wildner 				return 0;
210650a69bb5SSascha Wildner 			}
210750a69bb5SSascha Wildner 		}
210850a69bb5SSascha Wildner 		return 0;
210950a69bb5SSascha Wildner 	}
211050a69bb5SSascha Wildner 	/* Don't proceed if revocation or CA markers are present */
211150a69bb5SSascha Wildner 	/* XXX relax this */
211250a69bb5SSascha Wildner 	if (l->marker != MRK_NONE) {
211350a69bb5SSascha Wildner 		debug3_f("hostkeys file %s:%ld has CA/revocation marker",
211450a69bb5SSascha Wildner 		    l->path, l->linenum);
211550a69bb5SSascha Wildner 		ctx->complex_hostspec = 1;
211650a69bb5SSascha Wildner 		return 0;
211750a69bb5SSascha Wildner 	}
211850a69bb5SSascha Wildner 
211950a69bb5SSascha Wildner 	/* If CheckHostIP is enabled, then check for mismatched hostname/addr */
212050a69bb5SSascha Wildner 	if (ctx->ip_str != NULL && strchr(l->hosts, ',') != NULL) {
212150a69bb5SSascha Wildner 		if ((l->match & HKF_MATCH_HOST) == 0) {
212250a69bb5SSascha Wildner 			/* Record if address matched a different hostname. */
212350a69bb5SSascha Wildner 			ctx->other_name_seen = 1;
212450a69bb5SSascha Wildner 			debug3_f("found address %s against different hostname "
212550a69bb5SSascha Wildner 			    "at %s:%ld", ctx->ip_str, l->path, l->linenum);
212650a69bb5SSascha Wildner 			return 0;
212750a69bb5SSascha Wildner 		} else if ((l->match & HKF_MATCH_IP) == 0) {
212850a69bb5SSascha Wildner 			/* Record if hostname matched a different address. */
212950a69bb5SSascha Wildner 			ctx->other_name_seen = 1;
213050a69bb5SSascha Wildner 			debug3_f("found hostname %s against different address "
213150a69bb5SSascha Wildner 			    "at %s:%ld", ctx->host_str, l->path, l->linenum);
213250a69bb5SSascha Wildner 		}
213350a69bb5SSascha Wildner 	}
213450a69bb5SSascha Wildner 
213550a69bb5SSascha Wildner 	/*
213650a69bb5SSascha Wildner 	 * UpdateHostkeys is skipped for wildcard host names and hostnames
213750a69bb5SSascha Wildner 	 * that contain more than two entries (ssh never writes these).
213850a69bb5SSascha Wildner 	 */
213950a69bb5SSascha Wildner 	if (hostspec_is_complex(l->hosts)) {
214050a69bb5SSascha Wildner 		debug3_f("hostkeys file %s:%ld complex host specification",
214150a69bb5SSascha Wildner 		    l->path, l->linenum);
214250a69bb5SSascha Wildner 		ctx->complex_hostspec = 1;
214350a69bb5SSascha Wildner 		return 0;
214450a69bb5SSascha Wildner 	}
2145e9778795SPeter Avalos 
2146e9778795SPeter Avalos 	/* Mark off keys we've already seen for this host */
2147e9778795SPeter Avalos 	for (i = 0; i < ctx->nkeys; i++) {
214850a69bb5SSascha Wildner 		if (!sshkey_equal(l->key, ctx->keys[i]))
214950a69bb5SSascha Wildner 			continue;
215050a69bb5SSascha Wildner 		debug3_f("found %s key at %s:%ld",
2151e9778795SPeter Avalos 		    sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
215250a69bb5SSascha Wildner 		ctx->keys_match[i] |= l->match;
2153e9778795SPeter Avalos 		return 0;
2154e9778795SPeter Avalos 	}
2155e9778795SPeter Avalos 	/* This line contained a key that not offered by the server */
215650a69bb5SSascha Wildner 	debug3_f("deprecated %s key at %s:%ld", sshkey_ssh_name(l->key),
215750a69bb5SSascha Wildner 	    l->path, l->linenum);
2158ce74bacaSMatthew Dillon 	if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
2159e9778795SPeter Avalos 	    sizeof(*ctx->old_keys))) == NULL)
216050a69bb5SSascha Wildner 		fatal_f("recallocarray failed nold = %zu", ctx->nold);
2161e9778795SPeter Avalos 	ctx->old_keys = tmp;
2162e9778795SPeter Avalos 	ctx->old_keys[ctx->nold++] = l->key;
2163e9778795SPeter Avalos 	l->key = NULL;
2164e9778795SPeter Avalos 
2165e9778795SPeter Avalos 	return 0;
2166e9778795SPeter Avalos }
2167e9778795SPeter Avalos 
216850a69bb5SSascha Wildner /* callback to search for ctx->old_keys in known_hosts under other names */
216950a69bb5SSascha Wildner static int
hostkeys_check_old(struct hostkey_foreach_line * l,void * _ctx)217050a69bb5SSascha Wildner hostkeys_check_old(struct hostkey_foreach_line *l, void *_ctx)
217150a69bb5SSascha Wildner {
217250a69bb5SSascha Wildner 	struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
217350a69bb5SSascha Wildner 	size_t i;
217450a69bb5SSascha Wildner 	int hashed;
217550a69bb5SSascha Wildner 
217650a69bb5SSascha Wildner 	/* only care about lines that *don't* match the active host spec */
217750a69bb5SSascha Wildner 	if (l->status == HKF_STATUS_MATCHED || l->key == NULL)
217850a69bb5SSascha Wildner 		return 0;
217950a69bb5SSascha Wildner 
218050a69bb5SSascha Wildner 	hashed = l->match & (HKF_MATCH_HOST_HASHED|HKF_MATCH_IP_HASHED);
218150a69bb5SSascha Wildner 	for (i = 0; i < ctx->nold; i++) {
218250a69bb5SSascha Wildner 		if (!sshkey_equal(l->key, ctx->old_keys[i]))
218350a69bb5SSascha Wildner 			continue;
218450a69bb5SSascha Wildner 		debug3_f("found deprecated %s key at %s:%ld as %s",
218550a69bb5SSascha Wildner 		    sshkey_ssh_name(ctx->old_keys[i]), l->path, l->linenum,
218650a69bb5SSascha Wildner 		    hashed ? "[HASHED]" : l->hosts);
218750a69bb5SSascha Wildner 		ctx->old_key_seen = 1;
218850a69bb5SSascha Wildner 		break;
218950a69bb5SSascha Wildner 	}
219050a69bb5SSascha Wildner 	return 0;
219150a69bb5SSascha Wildner }
219250a69bb5SSascha Wildner 
219350a69bb5SSascha Wildner /*
219450a69bb5SSascha Wildner  * Check known_hosts files for deprecated keys under other names. Returns 0
219550a69bb5SSascha Wildner  * on success or -1 on failure. Updates ctx->old_key_seen if deprecated keys
219650a69bb5SSascha Wildner  * exist under names other than the active hostname/IP.
219750a69bb5SSascha Wildner  */
219850a69bb5SSascha Wildner static int
check_old_keys_othernames(struct hostkeys_update_ctx * ctx)219950a69bb5SSascha Wildner check_old_keys_othernames(struct hostkeys_update_ctx *ctx)
220050a69bb5SSascha Wildner {
220150a69bb5SSascha Wildner 	size_t i;
220250a69bb5SSascha Wildner 	int r;
220350a69bb5SSascha Wildner 
220450a69bb5SSascha Wildner 	debug2_f("checking for %zu deprecated keys", ctx->nold);
220550a69bb5SSascha Wildner 	for (i = 0; i < options.num_user_hostfiles; i++) {
220650a69bb5SSascha Wildner 		debug3_f("searching %s for %s / %s",
220750a69bb5SSascha Wildner 		    options.user_hostfiles[i], ctx->host_str,
220850a69bb5SSascha Wildner 		    ctx->ip_str ? ctx->ip_str : "(none)");
220950a69bb5SSascha Wildner 		if ((r = hostkeys_foreach(options.user_hostfiles[i],
221050a69bb5SSascha Wildner 		    hostkeys_check_old, ctx, ctx->host_str, ctx->ip_str,
221150a69bb5SSascha Wildner 		    HKF_WANT_PARSE_KEY, 0)) != 0) {
221250a69bb5SSascha Wildner 			if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
221350a69bb5SSascha Wildner 				debug_f("hostkeys file %s does not exist",
221450a69bb5SSascha Wildner 				    options.user_hostfiles[i]);
221550a69bb5SSascha Wildner 				continue;
221650a69bb5SSascha Wildner 			}
221750a69bb5SSascha Wildner 			error_fr(r, "hostkeys_foreach failed for %s",
221850a69bb5SSascha Wildner 			    options.user_hostfiles[i]);
221950a69bb5SSascha Wildner 			return -1;
222050a69bb5SSascha Wildner 		}
222150a69bb5SSascha Wildner 	}
222250a69bb5SSascha Wildner 	return 0;
222350a69bb5SSascha Wildner }
222450a69bb5SSascha Wildner 
2225e9778795SPeter Avalos static void
hostkey_change_preamble(LogLevel loglevel)22260cbfa66cSDaniel Fojt hostkey_change_preamble(LogLevel loglevel)
22270cbfa66cSDaniel Fojt {
22280cbfa66cSDaniel Fojt 	do_log2(loglevel, "The server has updated its host keys.");
22290cbfa66cSDaniel Fojt 	do_log2(loglevel, "These changes were verified by the server's "
22300cbfa66cSDaniel Fojt 	    "existing trusted key.");
22310cbfa66cSDaniel Fojt }
22320cbfa66cSDaniel Fojt 
22330cbfa66cSDaniel Fojt static void
update_known_hosts(struct hostkeys_update_ctx * ctx)2234e9778795SPeter Avalos update_known_hosts(struct hostkeys_update_ctx *ctx)
2235e9778795SPeter Avalos {
22360cbfa66cSDaniel Fojt 	int r, was_raw = 0, first = 1;
22370cbfa66cSDaniel Fojt 	int asking = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK;
22380cbfa66cSDaniel Fojt 	LogLevel loglevel = asking ?  SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
2239e9778795SPeter Avalos 	char *fp, *response;
2240e9778795SPeter Avalos 	size_t i;
22410cbfa66cSDaniel Fojt 	struct stat sb;
2242e9778795SPeter Avalos 
2243e9778795SPeter Avalos 	for (i = 0; i < ctx->nkeys; i++) {
224450a69bb5SSascha Wildner 		if (!ctx->keys_verified[i])
2245e9778795SPeter Avalos 			continue;
2246e9778795SPeter Avalos 		if ((fp = sshkey_fingerprint(ctx->keys[i],
2247e9778795SPeter Avalos 		    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
224850a69bb5SSascha Wildner 			fatal_f("sshkey_fingerprint failed");
22490cbfa66cSDaniel Fojt 		if (first && asking)
22500cbfa66cSDaniel Fojt 			hostkey_change_preamble(loglevel);
2251e9778795SPeter Avalos 		do_log2(loglevel, "Learned new hostkey: %s %s",
2252e9778795SPeter Avalos 		    sshkey_type(ctx->keys[i]), fp);
22530cbfa66cSDaniel Fojt 		first = 0;
2254e9778795SPeter Avalos 		free(fp);
2255e9778795SPeter Avalos 	}
2256e9778795SPeter Avalos 	for (i = 0; i < ctx->nold; i++) {
2257e9778795SPeter Avalos 		if ((fp = sshkey_fingerprint(ctx->old_keys[i],
2258e9778795SPeter Avalos 		    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
225950a69bb5SSascha Wildner 			fatal_f("sshkey_fingerprint failed");
22600cbfa66cSDaniel Fojt 		if (first && asking)
22610cbfa66cSDaniel Fojt 			hostkey_change_preamble(loglevel);
2262e9778795SPeter Avalos 		do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
2263e9778795SPeter Avalos 		    sshkey_type(ctx->old_keys[i]), fp);
22640cbfa66cSDaniel Fojt 		first = 0;
2265e9778795SPeter Avalos 		free(fp);
2266e9778795SPeter Avalos 	}
2267e9778795SPeter Avalos 	if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
2268e9778795SPeter Avalos 		if (get_saved_tio() != NULL) {
2269e9778795SPeter Avalos 			leave_raw_mode(1);
2270e9778795SPeter Avalos 			was_raw = 1;
2271e9778795SPeter Avalos 		}
2272e9778795SPeter Avalos 		response = NULL;
2273e9778795SPeter Avalos 		for (i = 0; !quit_pending && i < 3; i++) {
2274e9778795SPeter Avalos 			free(response);
2275e9778795SPeter Avalos 			response = read_passphrase("Accept updated hostkeys? "
2276e9778795SPeter Avalos 			    "(yes/no): ", RP_ECHO);
2277*ba1276acSMatthew Dillon 			if (response != NULL && strcasecmp(response, "yes") == 0)
2278e9778795SPeter Avalos 				break;
2279e9778795SPeter Avalos 			else if (quit_pending || response == NULL ||
2280e9778795SPeter Avalos 			    strcasecmp(response, "no") == 0) {
2281e9778795SPeter Avalos 				options.update_hostkeys = 0;
2282e9778795SPeter Avalos 				break;
2283e9778795SPeter Avalos 			} else {
2284e9778795SPeter Avalos 				do_log2(loglevel, "Please enter "
2285e9778795SPeter Avalos 				    "\"yes\" or \"no\"");
2286e9778795SPeter Avalos 			}
2287e9778795SPeter Avalos 		}
2288e9778795SPeter Avalos 		if (quit_pending || i >= 3 || response == NULL)
2289e9778795SPeter Avalos 			options.update_hostkeys = 0;
2290e9778795SPeter Avalos 		free(response);
2291e9778795SPeter Avalos 		if (was_raw)
2292e9778795SPeter Avalos 			enter_raw_mode(1);
2293e9778795SPeter Avalos 	}
22940cbfa66cSDaniel Fojt 	if (options.update_hostkeys == 0)
22950cbfa66cSDaniel Fojt 		return;
2296e9778795SPeter Avalos 	/*
2297e9778795SPeter Avalos 	 * Now that all the keys are verified, we can go ahead and replace
2298e9778795SPeter Avalos 	 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
2299e9778795SPeter Avalos 	 * cancel the operation).
2300e9778795SPeter Avalos 	 */
23010cbfa66cSDaniel Fojt 	for (i = 0; i < options.num_user_hostfiles; i++) {
23020cbfa66cSDaniel Fojt 		/*
23030cbfa66cSDaniel Fojt 		 * NB. keys are only added to hostfiles[0], for the rest we
23040cbfa66cSDaniel Fojt 		 * just delete the hostname entries.
23050cbfa66cSDaniel Fojt 		 */
23060cbfa66cSDaniel Fojt 		if (stat(options.user_hostfiles[i], &sb) != 0) {
23070cbfa66cSDaniel Fojt 			if (errno == ENOENT) {
230850a69bb5SSascha Wildner 				debug_f("known hosts file %s does not "
230950a69bb5SSascha Wildner 				    "exist", options.user_hostfiles[i]);
23100cbfa66cSDaniel Fojt 			} else {
231150a69bb5SSascha Wildner 				error_f("known hosts file %s "
231250a69bb5SSascha Wildner 				    "inaccessible: %s",
231350a69bb5SSascha Wildner 				    options.user_hostfiles[i], strerror(errno));
23140cbfa66cSDaniel Fojt 			}
23150cbfa66cSDaniel Fojt 			continue;
23160cbfa66cSDaniel Fojt 		}
23170cbfa66cSDaniel Fojt 		if ((r = hostfile_replace_entries(options.user_hostfiles[i],
23180cbfa66cSDaniel Fojt 		    ctx->host_str, ctx->ip_str,
23190cbfa66cSDaniel Fojt 		    i == 0 ? ctx->keys : NULL, i == 0 ? ctx->nkeys : 0,
2320e9778795SPeter Avalos 		    options.hash_known_hosts, 0,
23210cbfa66cSDaniel Fojt 		    options.fingerprint_hash)) != 0) {
232250a69bb5SSascha Wildner 			error_fr(r, "hostfile_replace_entries failed for %s",
232350a69bb5SSascha Wildner 			    options.user_hostfiles[i]);
23240cbfa66cSDaniel Fojt 		}
23250cbfa66cSDaniel Fojt 	}
2326e9778795SPeter Avalos }
2327e9778795SPeter Avalos 
2328e9778795SPeter Avalos static void
client_global_hostkeys_prove_confirm(struct ssh * ssh,int type,u_int32_t seq,void * _ctx)2329*ba1276acSMatthew Dillon client_global_hostkeys_prove_confirm(struct ssh *ssh, int type,
2330ce74bacaSMatthew Dillon     u_int32_t seq, void *_ctx)
2331e9778795SPeter Avalos {
2332e9778795SPeter Avalos 	struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2333e9778795SPeter Avalos 	size_t i, ndone;
2334e9778795SPeter Avalos 	struct sshbuf *signdata;
2335ee116499SAntonio Huete Jimenez 	int r, plaintype;
2336e9778795SPeter Avalos 	const u_char *sig;
2337ee116499SAntonio Huete Jimenez 	const char *rsa_kexalg = NULL;
2338ee116499SAntonio Huete Jimenez 	char *alg = NULL;
2339e9778795SPeter Avalos 	size_t siglen;
2340e9778795SPeter Avalos 
2341e9778795SPeter Avalos 	if (ctx->nnew == 0)
234250a69bb5SSascha Wildner 		fatal_f("ctx->nnew == 0"); /* sanity */
2343e9778795SPeter Avalos 	if (type != SSH2_MSG_REQUEST_SUCCESS) {
2344e9778795SPeter Avalos 		error("Server failed to confirm ownership of "
2345e9778795SPeter Avalos 		    "private host keys");
2346e9778795SPeter Avalos 		hostkeys_update_ctx_free(ctx);
2347e9778795SPeter Avalos 		return;
2348e9778795SPeter Avalos 	}
2349ee116499SAntonio Huete Jimenez 	if (sshkey_type_plain(sshkey_type_from_name(
2350ee116499SAntonio Huete Jimenez 	    ssh->kex->hostkey_alg)) == KEY_RSA)
2351ee116499SAntonio Huete Jimenez 		rsa_kexalg = ssh->kex->hostkey_alg;
2352e9778795SPeter Avalos 	if ((signdata = sshbuf_new()) == NULL)
235350a69bb5SSascha Wildner 		fatal_f("sshbuf_new failed");
2354e9778795SPeter Avalos 	/*
2355e9778795SPeter Avalos 	 * Expect a signature for each of the ctx->nnew private keys we
2356e9778795SPeter Avalos 	 * haven't seen before. They will be in the same order as the
235750a69bb5SSascha Wildner 	 * ctx->keys where the corresponding ctx->keys_match[i] == 0.
2358e9778795SPeter Avalos 	 */
2359e9778795SPeter Avalos 	for (ndone = i = 0; i < ctx->nkeys; i++) {
236050a69bb5SSascha Wildner 		if (ctx->keys_match[i])
2361e9778795SPeter Avalos 			continue;
2362ee116499SAntonio Huete Jimenez 		plaintype = sshkey_type_plain(ctx->keys[i]->type);
2363e9778795SPeter Avalos 		/* Prepare data to be signed: session ID, unique string, key */
2364e9778795SPeter Avalos 		sshbuf_reset(signdata);
2365e9778795SPeter Avalos 		if ( (r = sshbuf_put_cstring(signdata,
2366e9778795SPeter Avalos 		    "hostkeys-prove-00@openssh.com")) != 0 ||
236750a69bb5SSascha Wildner 		    (r = sshbuf_put_stringb(signdata,
236850a69bb5SSascha Wildner 		    ssh->kex->session_id)) != 0 ||
2369e9778795SPeter Avalos 		    (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
237050a69bb5SSascha Wildner 			fatal_fr(r, "compose signdata");
2371e9778795SPeter Avalos 		/* Extract and verify signature */
2372e9778795SPeter Avalos 		if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
237350a69bb5SSascha Wildner 			error_fr(r, "parse sig");
2374e9778795SPeter Avalos 			goto out;
2375e9778795SPeter Avalos 		}
2376ee116499SAntonio Huete Jimenez 		if ((r = sshkey_get_sigtype(sig, siglen, &alg)) != 0) {
2377ee116499SAntonio Huete Jimenez 			error_fr(r, "server gave unintelligible signature "
2378ee116499SAntonio Huete Jimenez 			    "for %s key %zu", sshkey_type(ctx->keys[i]), i);
2379ee116499SAntonio Huete Jimenez 			goto out;
2380ee116499SAntonio Huete Jimenez 		}
2381664f4763Szrj 		/*
2382ee116499SAntonio Huete Jimenez 		 * Special case for RSA keys: if a RSA hostkey was negotiated,
2383ee116499SAntonio Huete Jimenez 		 * then use its signature type for verification of RSA hostkey
2384ee116499SAntonio Huete Jimenez 		 * proofs. Otherwise, accept only RSA-SHA256/512 signatures.
2385664f4763Szrj 		 */
2386ee116499SAntonio Huete Jimenez 		if (plaintype == KEY_RSA && rsa_kexalg == NULL &&
2387ee116499SAntonio Huete Jimenez 		    match_pattern_list(alg, HOSTKEY_PROOF_RSA_ALGS, 0) != 1) {
2388ee116499SAntonio Huete Jimenez 			debug_f("server used untrusted RSA signature algorithm "
2389ee116499SAntonio Huete Jimenez 			    "%s for key %zu, disregarding", alg, i);
2390ee116499SAntonio Huete Jimenez 			free(alg);
2391ee116499SAntonio Huete Jimenez 			/* zap the key from the list */
2392ee116499SAntonio Huete Jimenez 			sshkey_free(ctx->keys[i]);
2393ee116499SAntonio Huete Jimenez 			ctx->keys[i] = NULL;
2394ee116499SAntonio Huete Jimenez 			ndone++;
2395ee116499SAntonio Huete Jimenez 			continue;
2396ee116499SAntonio Huete Jimenez 		}
2397ee116499SAntonio Huete Jimenez 		debug3_f("verify %s key %zu using sigalg %s",
2398ee116499SAntonio Huete Jimenez 		    sshkey_type(ctx->keys[i]), i, alg);
2399ee116499SAntonio Huete Jimenez 		free(alg);
2400e9778795SPeter Avalos 		if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
2401664f4763Szrj 		    sshbuf_ptr(signdata), sshbuf_len(signdata),
2402ee116499SAntonio Huete Jimenez 		    plaintype == KEY_RSA ? rsa_kexalg : NULL, 0, NULL)) != 0) {
240350a69bb5SSascha Wildner 			error_fr(r, "server gave bad signature for %s key %zu",
240450a69bb5SSascha Wildner 			    sshkey_type(ctx->keys[i]), i);
2405e9778795SPeter Avalos 			goto out;
2406e9778795SPeter Avalos 		}
2407e9778795SPeter Avalos 		/* Key is good. Mark it as 'seen' */
240850a69bb5SSascha Wildner 		ctx->keys_verified[i] = 1;
2409e9778795SPeter Avalos 		ndone++;
2410e9778795SPeter Avalos 	}
241150a69bb5SSascha Wildner 	/* Shouldn't happen */
2412e9778795SPeter Avalos 	if (ndone != ctx->nnew)
241350a69bb5SSascha Wildner 		fatal_f("ndone != ctx->nnew (%zu / %zu)", ndone, ctx->nnew);
2414664f4763Szrj 	if ((r = sshpkt_get_end(ssh)) != 0) {
241550a69bb5SSascha Wildner 		error_f("protocol error");
2416664f4763Szrj 		goto out;
2417664f4763Szrj 	}
2418e9778795SPeter Avalos 
2419e9778795SPeter Avalos 	/* Make the edits to known_hosts */
2420e9778795SPeter Avalos 	update_known_hosts(ctx);
2421e9778795SPeter Avalos  out:
2422e9778795SPeter Avalos 	hostkeys_update_ctx_free(ctx);
2423*ba1276acSMatthew Dillon 	hostkeys_update_complete = 1;
2424*ba1276acSMatthew Dillon 	client_repledge();
2425ce74bacaSMatthew Dillon }
2426ce74bacaSMatthew Dillon 
2427ce74bacaSMatthew Dillon /*
2428e9778795SPeter Avalos  * Handle hostkeys-00@openssh.com global request to inform the client of all
2429e9778795SPeter Avalos  * the server's hostkeys. The keys are checked against the user's
2430e9778795SPeter Avalos  * HostkeyAlgorithms preference before they are accepted.
2431e9778795SPeter Avalos  */
2432e9778795SPeter Avalos static int
client_input_hostkeys(struct ssh * ssh)2433664f4763Szrj client_input_hostkeys(struct ssh *ssh)
2434e9778795SPeter Avalos {
2435e9778795SPeter Avalos 	const u_char *blob = NULL;
2436e9778795SPeter Avalos 	size_t i, len = 0;
2437e9778795SPeter Avalos 	struct sshbuf *buf = NULL;
2438e9778795SPeter Avalos 	struct sshkey *key = NULL, **tmp;
2439*ba1276acSMatthew Dillon 	int r, prove_sent = 0;
2440e9778795SPeter Avalos 	char *fp;
2441e9778795SPeter Avalos 	static int hostkeys_seen = 0; /* XXX use struct ssh */
2442e9778795SPeter Avalos 	extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
2443e9778795SPeter Avalos 	struct hostkeys_update_ctx *ctx = NULL;
244450a69bb5SSascha Wildner 	u_int want;
2445e9778795SPeter Avalos 
2446e9778795SPeter Avalos 	if (hostkeys_seen)
244750a69bb5SSascha Wildner 		fatal_f("server already sent hostkeys");
2448*ba1276acSMatthew Dillon 	if (!can_update_hostkeys())
2449e9778795SPeter Avalos 		return 1;
2450*ba1276acSMatthew Dillon 	hostkeys_seen = 1;
2451e9778795SPeter Avalos 
2452e9778795SPeter Avalos 	ctx = xcalloc(1, sizeof(*ctx));
2453e9778795SPeter Avalos 	while (ssh_packet_remaining(ssh) > 0) {
2454e9778795SPeter Avalos 		sshkey_free(key);
2455e9778795SPeter Avalos 		key = NULL;
2456e9778795SPeter Avalos 		if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
245750a69bb5SSascha Wildner 			error_fr(r, "parse key");
2458e9778795SPeter Avalos 			goto out;
2459e9778795SPeter Avalos 		}
2460e9778795SPeter Avalos 		if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
246150a69bb5SSascha Wildner 			do_log2_fr(r, r == SSH_ERR_KEY_TYPE_UNKNOWN ?
24620cbfa66cSDaniel Fojt 			    SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_ERROR,
246350a69bb5SSascha Wildner 			    "convert key");
24640cbfa66cSDaniel Fojt 			continue;
2465e9778795SPeter Avalos 		}
2466e9778795SPeter Avalos 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
2467e9778795SPeter Avalos 		    SSH_FP_DEFAULT);
246850a69bb5SSascha Wildner 		debug3_f("received %s key %s", sshkey_type(key), fp);
2469e9778795SPeter Avalos 		free(fp);
2470e9778795SPeter Avalos 
2471*ba1276acSMatthew Dillon 		if (!hostkey_accepted_by_hostkeyalgs(key)) {
247250a69bb5SSascha Wildner 			debug3_f("%s key not permitted by "
247350a69bb5SSascha Wildner 			    "HostkeyAlgorithms", sshkey_ssh_name(key));
2474e9778795SPeter Avalos 			continue;
2475e9778795SPeter Avalos 		}
2476e9778795SPeter Avalos 		/* Skip certs */
2477e9778795SPeter Avalos 		if (sshkey_is_cert(key)) {
247850a69bb5SSascha Wildner 			debug3_f("%s key is a certificate; skipping",
247950a69bb5SSascha Wildner 			    sshkey_ssh_name(key));
2480e9778795SPeter Avalos 			continue;
2481e9778795SPeter Avalos 		}
2482e9778795SPeter Avalos 		/* Ensure keys are unique */
2483e9778795SPeter Avalos 		for (i = 0; i < ctx->nkeys; i++) {
2484e9778795SPeter Avalos 			if (sshkey_equal(key, ctx->keys[i])) {
248550a69bb5SSascha Wildner 				error_f("received duplicated %s host key",
248650a69bb5SSascha Wildner 				    sshkey_ssh_name(key));
2487e9778795SPeter Avalos 				goto out;
2488e9778795SPeter Avalos 			}
2489e9778795SPeter Avalos 		}
2490e9778795SPeter Avalos 		/* Key is good, record it */
2491ce74bacaSMatthew Dillon 		if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
2492e9778795SPeter Avalos 		    sizeof(*ctx->keys))) == NULL)
249350a69bb5SSascha Wildner 			fatal_f("recallocarray failed nkeys = %zu",
249450a69bb5SSascha Wildner 			    ctx->nkeys);
2495e9778795SPeter Avalos 		ctx->keys = tmp;
2496e9778795SPeter Avalos 		ctx->keys[ctx->nkeys++] = key;
2497e9778795SPeter Avalos 		key = NULL;
2498e9778795SPeter Avalos 	}
2499e9778795SPeter Avalos 
2500e9778795SPeter Avalos 	if (ctx->nkeys == 0) {
250150a69bb5SSascha Wildner 		debug_f("server sent no hostkeys");
2502e9778795SPeter Avalos 		goto out;
2503e9778795SPeter Avalos 	}
2504e9778795SPeter Avalos 
250550a69bb5SSascha Wildner 	if ((ctx->keys_match = calloc(ctx->nkeys,
250650a69bb5SSascha Wildner 	    sizeof(*ctx->keys_match))) == NULL ||
250750a69bb5SSascha Wildner 	    (ctx->keys_verified = calloc(ctx->nkeys,
250850a69bb5SSascha Wildner 	    sizeof(*ctx->keys_verified))) == NULL)
250950a69bb5SSascha Wildner 		fatal_f("calloc failed");
2510e9778795SPeter Avalos 
2511e9778795SPeter Avalos 	get_hostfile_hostname_ipaddr(host,
2512e9778795SPeter Avalos 	    options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2513e9778795SPeter Avalos 	    options.port, &ctx->host_str,
2514e9778795SPeter Avalos 	    options.check_host_ip ? &ctx->ip_str : NULL);
2515e9778795SPeter Avalos 
2516e9778795SPeter Avalos 	/* Find which keys we already know about. */
25170cbfa66cSDaniel Fojt 	for (i = 0; i < options.num_user_hostfiles; i++) {
251850a69bb5SSascha Wildner 		debug_f("searching %s for %s / %s",
25190cbfa66cSDaniel Fojt 		    options.user_hostfiles[i], ctx->host_str,
25200cbfa66cSDaniel Fojt 		    ctx->ip_str ? ctx->ip_str : "(none)");
25210cbfa66cSDaniel Fojt 		if ((r = hostkeys_foreach(options.user_hostfiles[i],
25220cbfa66cSDaniel Fojt 		    hostkeys_find, ctx, ctx->host_str, ctx->ip_str,
252350a69bb5SSascha Wildner 		    HKF_WANT_PARSE_KEY, 0)) != 0) {
25240cbfa66cSDaniel Fojt 			if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
252550a69bb5SSascha Wildner 				debug_f("hostkeys file %s does not exist",
252650a69bb5SSascha Wildner 				    options.user_hostfiles[i]);
25270cbfa66cSDaniel Fojt 				continue;
25280cbfa66cSDaniel Fojt 			}
252950a69bb5SSascha Wildner 			error_fr(r, "hostkeys_foreach failed for %s",
253050a69bb5SSascha Wildner 			    options.user_hostfiles[i]);
2531e9778795SPeter Avalos 			goto out;
2532e9778795SPeter Avalos 		}
25330cbfa66cSDaniel Fojt 	}
2534e9778795SPeter Avalos 
2535e9778795SPeter Avalos 	/* Figure out if we have any new keys to add */
253650a69bb5SSascha Wildner 	ctx->nnew = ctx->nincomplete = 0;
253750a69bb5SSascha Wildner 	want = HKF_MATCH_HOST | ( options.check_host_ip ? HKF_MATCH_IP : 0);
2538e9778795SPeter Avalos 	for (i = 0; i < ctx->nkeys; i++) {
253950a69bb5SSascha Wildner 		if (ctx->keys_match[i] == 0)
2540e9778795SPeter Avalos 			ctx->nnew++;
254150a69bb5SSascha Wildner 		if ((ctx->keys_match[i] & want) != want)
254250a69bb5SSascha Wildner 			ctx->nincomplete++;
2543e9778795SPeter Avalos 	}
2544e9778795SPeter Avalos 
254550a69bb5SSascha Wildner 	debug3_f("%zu server keys: %zu new, %zu retained, "
254650a69bb5SSascha Wildner 	    "%zu incomplete match. %zu to remove", ctx->nkeys, ctx->nnew,
254750a69bb5SSascha Wildner 	    ctx->nkeys - ctx->nnew - ctx->nincomplete,
254850a69bb5SSascha Wildner 	    ctx->nincomplete, ctx->nold);
2549e9778795SPeter Avalos 
255050a69bb5SSascha Wildner 	if (ctx->nnew == 0 && ctx->nold == 0) {
255150a69bb5SSascha Wildner 		debug_f("no new or deprecated keys from server");
255250a69bb5SSascha Wildner 		goto out;
255350a69bb5SSascha Wildner 	}
255450a69bb5SSascha Wildner 
255550a69bb5SSascha Wildner 	/* Various reasons why we cannot proceed with the update */
255650a69bb5SSascha Wildner 	if (ctx->complex_hostspec) {
255750a69bb5SSascha Wildner 		debug_f("CA/revocation marker, manual host list or wildcard "
255850a69bb5SSascha Wildner 		    "host pattern found, skipping UserKnownHostsFile update");
255950a69bb5SSascha Wildner 		goto out;
256050a69bb5SSascha Wildner 	}
256150a69bb5SSascha Wildner 	if (ctx->other_name_seen) {
256250a69bb5SSascha Wildner 		debug_f("host key found matching a different name/address, "
256350a69bb5SSascha Wildner 		    "skipping UserKnownHostsFile update");
256450a69bb5SSascha Wildner 		goto out;
256550a69bb5SSascha Wildner 	}
2566e9778795SPeter Avalos 	/*
256750a69bb5SSascha Wildner 	 * If removing keys, check whether they appear under different
256850a69bb5SSascha Wildner 	 * names/addresses and refuse to proceed if they do. This avoids
256950a69bb5SSascha Wildner 	 * cases such as hosts with multiple names becoming inconsistent
257050a69bb5SSascha Wildner 	 * with regards to CheckHostIP entries.
257150a69bb5SSascha Wildner 	 * XXX UpdateHostkeys=force to override this (and other) checks?
257250a69bb5SSascha Wildner 	 */
257350a69bb5SSascha Wildner 	if (ctx->nold != 0) {
257450a69bb5SSascha Wildner 		if (check_old_keys_othernames(ctx) != 0)
257550a69bb5SSascha Wildner 			goto out; /* error already logged */
257650a69bb5SSascha Wildner 		if (ctx->old_key_seen) {
257750a69bb5SSascha Wildner 			debug_f("key(s) for %s%s%s exist under other names; "
257850a69bb5SSascha Wildner 			    "skipping UserKnownHostsFile update",
257950a69bb5SSascha Wildner 			    ctx->host_str, ctx->ip_str == NULL ? "" : ",",
258050a69bb5SSascha Wildner 			    ctx->ip_str == NULL ? "" : ctx->ip_str);
258150a69bb5SSascha Wildner 			goto out;
258250a69bb5SSascha Wildner 		}
258350a69bb5SSascha Wildner 	}
258450a69bb5SSascha Wildner 
258550a69bb5SSascha Wildner 	if (ctx->nnew == 0) {
258650a69bb5SSascha Wildner 		/*
258750a69bb5SSascha Wildner 		 * We have some keys to remove or fix matching for.
258850a69bb5SSascha Wildner 		 * We can proceed to do this without requiring a fresh proof
258950a69bb5SSascha Wildner 		 * from the server.
259050a69bb5SSascha Wildner 		 */
259150a69bb5SSascha Wildner 		update_known_hosts(ctx);
259250a69bb5SSascha Wildner 		goto out;
259350a69bb5SSascha Wildner 	}
259450a69bb5SSascha Wildner 	/*
259550a69bb5SSascha Wildner 	 * We have received previously-unseen keys from the server.
2596e9778795SPeter Avalos 	 * Ask the server to confirm ownership of the private halves.
2597e9778795SPeter Avalos 	 */
259850a69bb5SSascha Wildner 	debug3_f("asking server to prove ownership for %zu keys", ctx->nnew);
2599e9778795SPeter Avalos 	if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2600e9778795SPeter Avalos 	    (r = sshpkt_put_cstring(ssh,
2601e9778795SPeter Avalos 	    "hostkeys-prove-00@openssh.com")) != 0 ||
2602e9778795SPeter Avalos 	    (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
260350a69bb5SSascha Wildner 		fatal_fr(r, "prepare hostkeys-prove");
2604e9778795SPeter Avalos 	if ((buf = sshbuf_new()) == NULL)
260550a69bb5SSascha Wildner 		fatal_f("sshbuf_new");
2606e9778795SPeter Avalos 	for (i = 0; i < ctx->nkeys; i++) {
260750a69bb5SSascha Wildner 		if (ctx->keys_match[i])
2608e9778795SPeter Avalos 			continue;
2609e9778795SPeter Avalos 		sshbuf_reset(buf);
261050a69bb5SSascha Wildner 		if ((r = sshkey_putb(ctx->keys[i], buf)) != 0 ||
261150a69bb5SSascha Wildner 		    (r = sshpkt_put_stringb(ssh, buf)) != 0)
261250a69bb5SSascha Wildner 			fatal_fr(r, "assemble hostkeys-prove");
2613e9778795SPeter Avalos 	}
2614e9778795SPeter Avalos 	if ((r = sshpkt_send(ssh)) != 0)
261550a69bb5SSascha Wildner 		fatal_fr(r, "send hostkeys-prove");
2616e9778795SPeter Avalos 	client_register_global_confirm(
2617*ba1276acSMatthew Dillon 	    client_global_hostkeys_prove_confirm, ctx);
2618e9778795SPeter Avalos 	ctx = NULL;  /* will be freed in callback */
2619*ba1276acSMatthew Dillon 	prove_sent = 1;
2620e9778795SPeter Avalos 
2621e9778795SPeter Avalos 	/* Success */
2622e9778795SPeter Avalos  out:
2623e9778795SPeter Avalos 	hostkeys_update_ctx_free(ctx);
2624e9778795SPeter Avalos 	sshkey_free(key);
2625e9778795SPeter Avalos 	sshbuf_free(buf);
2626*ba1276acSMatthew Dillon 	if (!prove_sent) {
2627*ba1276acSMatthew Dillon 		/* UpdateHostkeys handling completed */
2628*ba1276acSMatthew Dillon 		hostkeys_update_complete = 1;
2629*ba1276acSMatthew Dillon 		client_repledge();
2630*ba1276acSMatthew Dillon 	}
2631e9778795SPeter Avalos 	/*
2632e9778795SPeter Avalos 	 * NB. Return success for all cases. The server doesn't need to know
2633e9778795SPeter Avalos 	 * what the client does with its hosts file.
2634e9778795SPeter Avalos 	 */
2635e9778795SPeter Avalos 	return 1;
2636e9778795SPeter Avalos }
2637e9778795SPeter Avalos 
2638e9778795SPeter Avalos static int
client_input_global_request(int type,u_int32_t seq,struct ssh * ssh)2639ce74bacaSMatthew Dillon client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
264018de8d7fSPeter Avalos {
264118de8d7fSPeter Avalos 	char *rtype;
2642664f4763Szrj 	u_char want_reply;
2643664f4763Szrj 	int r, success = 0;
264418de8d7fSPeter Avalos 
2645664f4763Szrj 	if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
2646664f4763Szrj 	    (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
2647664f4763Szrj 		goto out;
264818de8d7fSPeter Avalos 	debug("client_input_global_request: rtype %s want_reply %d",
264918de8d7fSPeter Avalos 	    rtype, want_reply);
2650e9778795SPeter Avalos 	if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2651664f4763Szrj 		success = client_input_hostkeys(ssh);
265218de8d7fSPeter Avalos 	if (want_reply) {
2653664f4763Szrj 		if ((r = sshpkt_start(ssh, success ? SSH2_MSG_REQUEST_SUCCESS :
2654664f4763Szrj 		    SSH2_MSG_REQUEST_FAILURE)) != 0 ||
2655664f4763Szrj 		    (r = sshpkt_send(ssh)) != 0 ||
2656664f4763Szrj 		    (r = ssh_packet_write_wait(ssh)) != 0)
2657664f4763Szrj 			goto out;
265818de8d7fSPeter Avalos 	}
2659664f4763Szrj 	r = 0;
2660664f4763Szrj  out:
266136e94dc5SPeter Avalos 	free(rtype);
2662664f4763Szrj 	return r;
266318de8d7fSPeter Avalos }
266418de8d7fSPeter Avalos 
266550a69bb5SSascha Wildner static void
client_send_env(struct ssh * ssh,int id,const char * name,const char * val)266650a69bb5SSascha Wildner client_send_env(struct ssh *ssh, int id, const char *name, const char *val)
266750a69bb5SSascha Wildner {
266850a69bb5SSascha Wildner 	int r;
266950a69bb5SSascha Wildner 
267050a69bb5SSascha Wildner 	debug("channel %d: setting env %s = \"%s\"", id, name, val);
267150a69bb5SSascha Wildner 	channel_request_start(ssh, id, "env", 0);
267250a69bb5SSascha Wildner 	if ((r = sshpkt_put_cstring(ssh, name)) != 0 ||
267350a69bb5SSascha Wildner 	    (r = sshpkt_put_cstring(ssh, val)) != 0 ||
267450a69bb5SSascha Wildner 	    (r = sshpkt_send(ssh)) != 0)
267550a69bb5SSascha Wildner 		fatal_fr(r, "send setenv");
267650a69bb5SSascha Wildner }
267750a69bb5SSascha Wildner 
267818de8d7fSPeter Avalos void
client_session2_setup(struct ssh * ssh,int id,int want_tty,int want_subsystem,const char * term,struct termios * tiop,int in_fd,struct sshbuf * cmd,char ** env)2679ce74bacaSMatthew Dillon client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
2680664f4763Szrj     const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd,
2681664f4763Szrj     char **env)
268218de8d7fSPeter Avalos {
2683ee116499SAntonio Huete Jimenez 	size_t i, j, len;
2684ee116499SAntonio Huete Jimenez 	int matched, r;
2685664f4763Szrj 	char *name, *val;
268618de8d7fSPeter Avalos 	Channel *c = NULL;
268718de8d7fSPeter Avalos 
268850a69bb5SSascha Wildner 	debug2_f("id %d", id);
268918de8d7fSPeter Avalos 
2690ce74bacaSMatthew Dillon 	if ((c = channel_lookup(ssh, id)) == NULL)
269150a69bb5SSascha Wildner 		fatal_f("channel %d: unknown channel", id);
269218de8d7fSPeter Avalos 
2693664f4763Szrj 	ssh_packet_set_interactive(ssh, want_tty,
26949f304aafSPeter Avalos 	    options.ip_qos_interactive, options.ip_qos_bulk);
26959f304aafSPeter Avalos 
269618de8d7fSPeter Avalos 	if (want_tty) {
269718de8d7fSPeter Avalos 		struct winsize ws;
269818de8d7fSPeter Avalos 
269918de8d7fSPeter Avalos 		/* Store window size in the packet. */
27000cbfa66cSDaniel Fojt 		if (ioctl(in_fd, TIOCGWINSZ, &ws) == -1)
270118de8d7fSPeter Avalos 			memset(&ws, 0, sizeof(ws));
270218de8d7fSPeter Avalos 
2703ce74bacaSMatthew Dillon 		channel_request_start(ssh, id, "pty-req", 1);
2704ce74bacaSMatthew Dillon 		client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
2705664f4763Szrj 		if ((r = sshpkt_put_cstring(ssh, term != NULL ? term : ""))
2706664f4763Szrj 		    != 0 ||
2707664f4763Szrj 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
2708664f4763Szrj 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
2709664f4763Szrj 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
2710664f4763Szrj 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0)
271150a69bb5SSascha Wildner 			fatal_fr(r, "build pty-req");
271218de8d7fSPeter Avalos 		if (tiop == NULL)
271318de8d7fSPeter Avalos 			tiop = get_saved_tio();
2714664f4763Szrj 		ssh_tty_make_modes(ssh, -1, tiop);
2715664f4763Szrj 		if ((r = sshpkt_send(ssh)) != 0)
271650a69bb5SSascha Wildner 			fatal_fr(r, "send pty-req");
271718de8d7fSPeter Avalos 		/* XXX wait for reply */
271818de8d7fSPeter Avalos 		c->client_tty = 1;
271918de8d7fSPeter Avalos 	}
272018de8d7fSPeter Avalos 
272118de8d7fSPeter Avalos 	/* Transfer any environment variables from client to server */
272218de8d7fSPeter Avalos 	if (options.num_send_env != 0 && env != NULL) {
272318de8d7fSPeter Avalos 		debug("Sending environment.");
272418de8d7fSPeter Avalos 		for (i = 0; env[i] != NULL; i++) {
272518de8d7fSPeter Avalos 			/* Split */
272618de8d7fSPeter Avalos 			name = xstrdup(env[i]);
272718de8d7fSPeter Avalos 			if ((val = strchr(name, '=')) == NULL) {
272836e94dc5SPeter Avalos 				free(name);
272918de8d7fSPeter Avalos 				continue;
273018de8d7fSPeter Avalos 			}
273118de8d7fSPeter Avalos 			*val++ = '\0';
273218de8d7fSPeter Avalos 
273318de8d7fSPeter Avalos 			matched = 0;
273418de8d7fSPeter Avalos 			for (j = 0; j < options.num_send_env; j++) {
273518de8d7fSPeter Avalos 				if (match_pattern(name, options.send_env[j])) {
273618de8d7fSPeter Avalos 					matched = 1;
273718de8d7fSPeter Avalos 					break;
273818de8d7fSPeter Avalos 				}
273918de8d7fSPeter Avalos 			}
274018de8d7fSPeter Avalos 			if (!matched) {
274118de8d7fSPeter Avalos 				debug3("Ignored env %s", name);
274236e94dc5SPeter Avalos 				free(name);
274318de8d7fSPeter Avalos 				continue;
274418de8d7fSPeter Avalos 			}
274550a69bb5SSascha Wildner 			client_send_env(ssh, id, name, val);
274636e94dc5SPeter Avalos 			free(name);
274718de8d7fSPeter Avalos 		}
274818de8d7fSPeter Avalos 	}
2749664f4763Szrj 	for (i = 0; i < options.num_setenv; i++) {
2750664f4763Szrj 		/* Split */
2751664f4763Szrj 		name = xstrdup(options.setenv[i]);
2752664f4763Szrj 		if ((val = strchr(name, '=')) == NULL) {
2753664f4763Szrj 			free(name);
2754664f4763Szrj 			continue;
2755664f4763Szrj 		}
2756664f4763Szrj 		*val++ = '\0';
275750a69bb5SSascha Wildner 		client_send_env(ssh, id, name, val);
2758664f4763Szrj 		free(name);
2759664f4763Szrj 	}
2760664f4763Szrj 
2761664f4763Szrj 	len = sshbuf_len(cmd);
276218de8d7fSPeter Avalos 	if (len > 0) {
276318de8d7fSPeter Avalos 		if (len > 900)
276418de8d7fSPeter Avalos 			len = 900;
276518de8d7fSPeter Avalos 		if (want_subsystem) {
276618de8d7fSPeter Avalos 			debug("Sending subsystem: %.*s",
2767ee116499SAntonio Huete Jimenez 			    (int)len, (const u_char*)sshbuf_ptr(cmd));
2768ce74bacaSMatthew Dillon 			channel_request_start(ssh, id, "subsystem", 1);
2769ce74bacaSMatthew Dillon 			client_expect_confirm(ssh, id, "subsystem",
2770ce74bacaSMatthew Dillon 			    CONFIRM_CLOSE);
277118de8d7fSPeter Avalos 		} else {
277218de8d7fSPeter Avalos 			debug("Sending command: %.*s",
2773ee116499SAntonio Huete Jimenez 			    (int)len, (const u_char*)sshbuf_ptr(cmd));
2774ce74bacaSMatthew Dillon 			channel_request_start(ssh, id, "exec", 1);
2775ce74bacaSMatthew Dillon 			client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
277618de8d7fSPeter Avalos 		}
2777664f4763Szrj 		if ((r = sshpkt_put_stringb(ssh, cmd)) != 0 ||
2778664f4763Szrj 		    (r = sshpkt_send(ssh)) != 0)
277950a69bb5SSascha Wildner 			fatal_fr(r, "send command");
278018de8d7fSPeter Avalos 	} else {
2781ce74bacaSMatthew Dillon 		channel_request_start(ssh, id, "shell", 1);
2782ce74bacaSMatthew Dillon 		client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
278350a69bb5SSascha Wildner 		if ((r = sshpkt_send(ssh)) != 0)
278450a69bb5SSascha Wildner 			fatal_fr(r, "send shell");
278518de8d7fSPeter Avalos 	}
2786*ba1276acSMatthew Dillon 
2787*ba1276acSMatthew Dillon 	session_setup_complete = 1;
2788*ba1276acSMatthew Dillon 	client_repledge();
278918de8d7fSPeter Avalos }
279018de8d7fSPeter Avalos 
279118de8d7fSPeter Avalos static void
client_init_dispatch(struct ssh * ssh)2792664f4763Szrj client_init_dispatch(struct ssh *ssh)
279318de8d7fSPeter Avalos {
2794664f4763Szrj 	ssh_dispatch_init(ssh, &dispatch_protocol_error);
279518de8d7fSPeter Avalos 
2796664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2797664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2798664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2799664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2800664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2801664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2802664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2803664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2804664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2805664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2806664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2807664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
280818de8d7fSPeter Avalos 
280918de8d7fSPeter Avalos 	/* rekeying */
2810664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
281118de8d7fSPeter Avalos 
281218de8d7fSPeter Avalos 	/* global request reply messages */
2813664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2814664f4763Szrj 	ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
281518de8d7fSPeter Avalos }
281618de8d7fSPeter Avalos 
28171c188a7fSPeter Avalos void
client_stop_mux(void)28181c188a7fSPeter Avalos client_stop_mux(void)
28191c188a7fSPeter Avalos {
28201c188a7fSPeter Avalos 	if (options.control_path != NULL && muxserver_sock != -1)
28211c188a7fSPeter Avalos 		unlink(options.control_path);
28221c188a7fSPeter Avalos 	/*
282336e94dc5SPeter Avalos 	 * If we are in persist mode, or don't have a shell, signal that we
282436e94dc5SPeter Avalos 	 * should close when all active channels are closed.
28251c188a7fSPeter Avalos 	 */
282650a69bb5SSascha Wildner 	if (options.control_persist || options.session_type == SESSION_TYPE_NONE) {
28271c188a7fSPeter Avalos 		session_closed = 1;
28281c188a7fSPeter Avalos 		setproctitle("[stopped mux]");
28291c188a7fSPeter Avalos 	}
28301c188a7fSPeter Avalos }
28311c188a7fSPeter Avalos 
283218de8d7fSPeter Avalos /* client specific fatal cleanup */
283318de8d7fSPeter Avalos void
cleanup_exit(int i)283418de8d7fSPeter Avalos cleanup_exit(int i)
283518de8d7fSPeter Avalos {
28361c188a7fSPeter Avalos 	leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
283718de8d7fSPeter Avalos 	if (options.control_path != NULL && muxserver_sock != -1)
283818de8d7fSPeter Avalos 		unlink(options.control_path);
28399f304aafSPeter Avalos 	ssh_kill_proxy_command();
284018de8d7fSPeter Avalos 	_exit(i);
284118de8d7fSPeter Avalos }
2842