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