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