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