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