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