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