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