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