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