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