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