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