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