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