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