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