xref: /netbsd-src/crypto/external/bsd/openssh/dist/sshconnect.c (revision 2718af68c3efc72c9769069b5c7f9ed36f6b9def)
1 /*	$NetBSD: sshconnect.c,v 1.32 2022/02/23 19:07:20 christos Exp $	*/
2 /* $OpenBSD: sshconnect.c,v 1.356 2021/12/19 22:10:24 djm Exp $ */
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * Code to connect to a remote host, and to perform the client side of the
8  * login (authentication) dialog.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  */
16 
17 #include "includes.h"
18 __RCSID("$NetBSD: sshconnect.c,v 1.32 2022/02/23 19:07:20 christos Exp $");
19 
20 #include <sys/param.h>	/* roundup */
21 #include <sys/types.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
24 #include <sys/stat.h>
25 #include <sys/socket.h>
26 #include <sys/time.h>
27 
28 #include <net/if.h>
29 #include <netinet/in.h>
30 #include <rpc/rpc.h>
31 
32 #include <ctype.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <netdb.h>
36 #include <limits.h>
37 #include <paths.h>
38 #include <signal.h>
39 #include <pwd.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <stdarg.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <ifaddrs.h>
46 
47 #include "xmalloc.h"
48 #include "ssh.h"
49 #include "sshbuf.h"
50 #include "packet.h"
51 #include "compat.h"
52 #include "sshkey.h"
53 #include "sshconnect.h"
54 #include "hostfile.h"
55 #include "log.h"
56 #include "misc.h"
57 #include "readconf.h"
58 #include "atomicio.h"
59 #include "dns.h"
60 #include "monitor_fdpass.h"
61 #include "ssh2.h"
62 #include "version.h"
63 #include "authfile.h"
64 #include "ssherr.h"
65 #include "authfd.h"
66 #include "kex.h"
67 
68 struct sshkey *previous_host_key = NULL;
69 
70 static int matching_host_key_dns = 0;
71 
72 static pid_t proxy_command_pid = 0;
73 
74 /* import */
75 extern int debug_flag;
76 extern Options options;
77 extern char *__progname;
78 
79 static int show_other_keys(struct hostkeys *, struct sshkey *);
80 static void warn_changed_key(struct sshkey *);
81 
82 /* Expand a proxy command */
83 static char *
84 expand_proxy_command(const char *proxy_command, const char *user,
85     const char *host, const char *host_arg, int port)
86 {
87 	char *tmp, *ret, strport[NI_MAXSERV];
88 	const char *keyalias = options.host_key_alias ?
89 	    options.host_key_alias : host_arg;
90 
91 	snprintf(strport, sizeof strport, "%d", port);
92 	xasprintf(&tmp, "exec %s", proxy_command);
93 	ret = percent_expand(tmp,
94 	    "h", host,
95 	    "k", keyalias,
96 	    "n", host_arg,
97 	    "p", strport,
98 	    "r", options.user,
99 	    (char *)NULL);
100 	free(tmp);
101 	return ret;
102 }
103 
104 /*
105  * Connect to the given ssh server using a proxy command that passes a
106  * a connected fd back to us.
107  */
108 static int
109 ssh_proxy_fdpass_connect(struct ssh *ssh, const char *host,
110     const char *host_arg, u_short port, const char *proxy_command)
111 {
112 	char *command_string;
113 	int sp[2], sock;
114 	pid_t pid;
115 	const char *shell;
116 
117 	if ((shell = getenv("SHELL")) == NULL)
118 		shell = _PATH_BSHELL;
119 
120 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, sp) == -1)
121 		fatal("Could not create socketpair to communicate with "
122 		    "proxy dialer: %.100s", strerror(errno));
123 	close(sp[1]);
124 
125 	command_string = expand_proxy_command(proxy_command, options.user,
126 	    host, host_arg, port);
127 	debug("Executing proxy dialer command: %.500s", command_string);
128 
129 	/* Fork and execute the proxy command. */
130 	if ((pid = fork()) == 0) {
131 		char *argv[10];
132 
133 		close(sp[1]);
134 		/* Redirect stdin and stdout. */
135 		if (sp[0] != 0) {
136 			if (dup2(sp[0], 0) == -1)
137 				perror("dup2 stdin");
138 		}
139 		if (sp[0] != 1) {
140 			if (dup2(sp[0], 1) == -1)
141 				perror("dup2 stdout");
142 		}
143 		if (sp[0] >= 2)
144 			close(sp[0]);
145 
146 		/*
147 		 * Stderr is left for non-ControlPersist connections is so
148 		 * error messages may be printed on the user's terminal.
149 		 */
150 		if (!debug_flag && options.control_path != NULL &&
151 		    options.control_persist && stdfd_devnull(0, 0, 1) == -1)
152 			error_f("stdfd_devnull failed");
153 
154 		argv[0] = __UNCONST(shell);
155 		argv[1] = __UNCONST("-c");
156 		argv[2] = command_string;
157 		argv[3] = NULL;
158 
159 		/*
160 		 * Execute the proxy command.
161 		 * Note that we gave up any extra privileges above.
162 		 */
163 		execv(argv[0], argv);
164 		perror(argv[0]);
165 		exit(1);
166 	}
167 	/* Parent. */
168 	if (pid == -1)
169 		fatal("fork failed: %.100s", strerror(errno));
170 	close(sp[0]);
171 	free(command_string);
172 
173 	if ((sock = mm_receive_fd(sp[1])) == -1)
174 		fatal("proxy dialer did not pass back a connection");
175 	close(sp[1]);
176 
177 	while (waitpid(pid, NULL, 0) == -1)
178 		if (errno != EINTR)
179 			fatal("Couldn't wait for child: %s", strerror(errno));
180 
181 	/* Set the connection file descriptors. */
182 	if (ssh_packet_set_connection(ssh, sock, sock) == NULL)
183 		return -1; /* ssh_packet_set_connection logs error */
184 
185 	return 0;
186 }
187 
188 /*
189  * Connect to the given ssh server using a proxy command.
190  */
191 static int
192 ssh_proxy_connect(struct ssh *ssh, const char *host, const char *host_arg,
193     u_short port, const char *proxy_command)
194 {
195 	char *command_string;
196 	int pin[2], pout[2];
197 	pid_t pid;
198 	char *shell;
199 
200 	if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
201 		shell = __UNCONST(_PATH_BSHELL);
202 
203 	/* Create pipes for communicating with the proxy. */
204 	if (pipe(pin) == -1 || pipe(pout) == -1)
205 		fatal("Could not create pipes to communicate with the proxy: %.100s",
206 		    strerror(errno));
207 
208 	command_string = expand_proxy_command(proxy_command, options.user,
209 	    host, host_arg, port);
210 	debug("Executing proxy command: %.500s", command_string);
211 
212 	/* Fork and execute the proxy command. */
213 	if ((pid = fork()) == 0) {
214 		char *argv[10];
215 
216 		/* Redirect stdin and stdout. */
217 		close(pin[1]);
218 		if (pin[0] != 0) {
219 			if (dup2(pin[0], 0) == -1)
220 				perror("dup2 stdin");
221 			close(pin[0]);
222 		}
223 		close(pout[0]);
224 		if (dup2(pout[1], 1) == -1)
225 			perror("dup2 stdout");
226 		/* Cannot be 1 because pin allocated two descriptors. */
227 		close(pout[1]);
228 
229 		/*
230 		 * Stderr is left for non-ControlPersist connections is so
231 		 * error messages may be printed on the user's terminal.
232 		 */
233 		if (!debug_flag && options.control_path != NULL &&
234 		    options.control_persist && stdfd_devnull(0, 0, 1) == -1)
235 			error_f("stdfd_devnull failed");
236 
237 		argv[0] = shell;
238 		argv[1] = __UNCONST("-c");
239 		argv[2] = command_string;
240 		argv[3] = NULL;
241 
242 		/*
243 		 * Execute the proxy command.  Note that we gave up any
244 		 * extra privileges above.
245 		 */
246 		ssh_signal(SIGPIPE, SIG_DFL);
247 		execv(argv[0], argv);
248 		perror(argv[0]);
249 		exit(1);
250 	}
251 	/* Parent. */
252 	if (pid == -1)
253 		fatal("fork failed: %.100s", strerror(errno));
254 	else
255 		proxy_command_pid = pid; /* save pid to clean up later */
256 
257 	/* Close child side of the descriptors. */
258 	close(pin[0]);
259 	close(pout[1]);
260 
261 	/* Free the command name. */
262 	free(command_string);
263 
264 	/* Set the connection file descriptors. */
265 	if (ssh_packet_set_connection(ssh, pout[0], pin[1]) == NULL)
266 		return -1; /* ssh_packet_set_connection logs error */
267 
268 	return 0;
269 }
270 
271 void
272 ssh_kill_proxy_command(void)
273 {
274 	/*
275 	 * Send SIGHUP to proxy command if used. We don't wait() in
276 	 * case it hangs and instead rely on init to reap the child
277 	 */
278 	if (proxy_command_pid > 1)
279 		kill(proxy_command_pid, SIGHUP);
280 }
281 
282 /*
283  * Set TCP receive buffer if requested.
284  * Note: tuning needs to happen after the socket is
285  * created but before the connection happens
286  * so winscale is negotiated properly -cjr
287  */
288 static void
289 ssh_set_socket_recvbuf(int sock)
290 {
291 	void *buf = (void *)&options.tcp_rcv_buf;
292 	int sz = sizeof(options.tcp_rcv_buf);
293 	int socksize;
294 	socklen_t socksizelen = sizeof(int);
295 
296 	debug("setsockopt Attempting to set SO_RCVBUF to %d", options.tcp_rcv_buf);
297 	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, buf, sz) >= 0) {
298 	  getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &socksize, &socksizelen);
299 	  debug("setsockopt SO_RCVBUF: %.100s %d", strerror(errno), socksize);
300 	}
301 	else
302 		error("Couldn't set socket receive buffer to %d: %.100s",
303 		    options.tcp_rcv_buf, strerror(errno));
304 }
305 
306 /*
307  * Search a interface address list (returned from getifaddrs(3)) for an
308  * address that matches the desired address family on the specified interface.
309  * Returns 0 and fills in *resultp and *rlenp on success. Returns -1 on failure.
310  */
311 static int
312 check_ifaddrs(const char *ifname, int af, const struct ifaddrs *ifaddrs,
313     struct sockaddr_storage *resultp, socklen_t *rlenp)
314 {
315 	struct sockaddr_in6 *sa6;
316 	struct sockaddr_in *sa;
317 	struct in6_addr *v6addr;
318 	const struct ifaddrs *ifa;
319 	int allow_local;
320 
321 	/*
322 	 * Prefer addresses that are not loopback or linklocal, but use them
323 	 * if nothing else matches.
324 	 */
325 	for (allow_local = 0; allow_local < 2; allow_local++) {
326 		for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
327 			if (ifa->ifa_addr == NULL || ifa->ifa_name == NULL ||
328 			    (ifa->ifa_flags & IFF_UP) == 0 ||
329 			    ifa->ifa_addr->sa_family != af ||
330 			    strcmp(ifa->ifa_name, options.bind_interface) != 0)
331 				continue;
332 			switch (ifa->ifa_addr->sa_family) {
333 			case AF_INET:
334 				sa = (struct sockaddr_in *)ifa->ifa_addr;
335 				if (!allow_local && sa->sin_addr.s_addr ==
336 				    htonl(INADDR_LOOPBACK))
337 					continue;
338 				if (*rlenp < sizeof(struct sockaddr_in)) {
339 					error_f("v4 addr doesn't fit");
340 					return -1;
341 				}
342 				*rlenp = sizeof(struct sockaddr_in);
343 				memcpy(resultp, sa, *rlenp);
344 				return 0;
345 			case AF_INET6:
346 				sa6 = (struct sockaddr_in6 *)ifa->ifa_addr;
347 				v6addr = &sa6->sin6_addr;
348 				if (!allow_local &&
349 				    (IN6_IS_ADDR_LINKLOCAL(v6addr) ||
350 				    IN6_IS_ADDR_LOOPBACK(v6addr)))
351 					continue;
352 				if (*rlenp < sizeof(struct sockaddr_in6)) {
353 					error_f("v6 addr doesn't fit");
354 					return -1;
355 				}
356 				*rlenp = sizeof(struct sockaddr_in6);
357 				memcpy(resultp, sa6, *rlenp);
358 				return 0;
359 			}
360 		}
361 	}
362 	return -1;
363 }
364 
365 /*
366  * Creates a socket for use as the ssh connection.
367  */
368 static int
369 ssh_create_socket(struct addrinfo *ai)
370 {
371 	int sock, r;
372 	struct sockaddr_storage bindaddr;
373 	socklen_t bindaddrlen = 0;
374 	struct addrinfo hints, *res = NULL;
375 	struct ifaddrs *ifaddrs = NULL;
376 	char ntop[NI_MAXHOST];
377 
378 	sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
379 	if (sock == -1) {
380 		error("socket: %s", strerror(errno));
381 		return -1;
382 	}
383 	fcntl(sock, F_SETFD, FD_CLOEXEC);
384 
385 	if (options.tcp_rcv_buf > 0)
386 		ssh_set_socket_recvbuf(sock);
387 
388 	/* Use interactive QOS (if specified) until authentication completed */
389 	if (options.ip_qos_interactive != INT_MAX)
390 		set_sock_tos(sock, options.ip_qos_interactive);
391 
392 	/* Bind the socket to an alternative local IP address */
393 	if (options.bind_address == NULL && options.bind_interface == NULL)
394 		return sock;
395 
396 	if (options.bind_address != NULL) {
397 		memset(&hints, 0, sizeof(hints));
398 		hints.ai_family = ai->ai_family;
399 		hints.ai_socktype = ai->ai_socktype;
400 		hints.ai_protocol = ai->ai_protocol;
401 		hints.ai_flags = AI_PASSIVE;
402 		if ((r = getaddrinfo(options.bind_address, NULL,
403 		    &hints, &res)) != 0) {
404 			error("getaddrinfo: %s: %s", options.bind_address,
405 			    ssh_gai_strerror(r));
406 			goto fail;
407 		}
408 		if (res == NULL) {
409 			error("getaddrinfo: no addrs");
410 			goto fail;
411 		}
412 		memcpy(&bindaddr, res->ai_addr, res->ai_addrlen);
413 		bindaddrlen = res->ai_addrlen;
414 	} else if (options.bind_interface != NULL) {
415 		if ((r = getifaddrs(&ifaddrs)) != 0) {
416 			error("getifaddrs: %s: %s", options.bind_interface,
417 			    strerror(errno));
418 			goto fail;
419 		}
420 		bindaddrlen = sizeof(bindaddr);
421 		if (check_ifaddrs(options.bind_interface, ai->ai_family,
422 		    ifaddrs, &bindaddr, &bindaddrlen) != 0) {
423 			logit("getifaddrs: %s: no suitable addresses",
424 			    options.bind_interface);
425 			goto fail;
426 		}
427 	}
428 	if ((r = getnameinfo((struct sockaddr *)&bindaddr, bindaddrlen,
429 	    ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST)) != 0) {
430 		error_f("getnameinfo failed: %s", ssh_gai_strerror(r));
431 		goto fail;
432 	}
433 	if (bind(sock, (struct sockaddr *)&bindaddr, bindaddrlen) != 0) {
434 		error("bind %s: %s", ntop, strerror(errno));
435 		goto fail;
436 	}
437 	debug_f("bound to %s", ntop);
438 	/* success */
439 	goto out;
440 fail:
441 	close(sock);
442 	sock = -1;
443  out:
444 	if (res != NULL)
445 		freeaddrinfo(res);
446 	if (ifaddrs != NULL)
447 		freeifaddrs(ifaddrs);
448 	return sock;
449 }
450 
451 /*
452  * Opens a TCP/IP connection to the remote server on the given host.
453  * The address of the remote host will be returned in hostaddr.
454  * If port is 0, the default port will be used.
455  * Connection_attempts specifies the maximum number of tries (one per
456  * second).  If proxy_command is non-NULL, it specifies the command (with %h
457  * and %p substituted for host and port, respectively) to use to contact
458  * the daemon.
459  */
460 static int
461 ssh_connect_direct(struct ssh *ssh, const char *host, struct addrinfo *aitop,
462     struct sockaddr_storage *hostaddr, u_short port, int connection_attempts,
463     int *timeout_ms, int want_keepalive)
464 {
465 	int on = 1, saved_timeout_ms = *timeout_ms;
466 	int oerrno, sock = -1, attempt;
467 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
468 	struct addrinfo *ai;
469 
470 	debug3_f("entering");
471 	memset(ntop, 0, sizeof(ntop));
472 	memset(strport, 0, sizeof(strport));
473 
474 	for (attempt = 0; attempt < connection_attempts; attempt++) {
475 		if (attempt > 0) {
476 			/* Sleep a moment before retrying. */
477 			sleep(1);
478 			debug("Trying again...");
479 		}
480 		/*
481 		 * Loop through addresses for this host, and try each one in
482 		 * sequence until the connection succeeds.
483 		 */
484 		for (ai = aitop; ai; ai = ai->ai_next) {
485 			if (ai->ai_family != AF_INET &&
486 			    ai->ai_family != AF_INET6) {
487 				errno = EAFNOSUPPORT;
488 				continue;
489 			}
490 			if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
491 			    ntop, sizeof(ntop), strport, sizeof(strport),
492 			    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
493 				oerrno = errno;
494 				error_f("getnameinfo failed");
495 				errno = oerrno;
496 				continue;
497 			}
498 			debug("Connecting to %.200s [%.100s] port %s.",
499 				host, ntop, strport);
500 
501 			/* Create a socket for connecting. */
502 			sock = ssh_create_socket(ai);
503 			if (sock < 0) {
504 				/* Any error is already output */
505 				errno = 0;
506 				continue;
507 			}
508 
509 			*timeout_ms = saved_timeout_ms;
510 			if (timeout_connect(sock, ai->ai_addr, ai->ai_addrlen,
511 			    timeout_ms) >= 0) {
512 				/* Successful connection. */
513 				memcpy(hostaddr, ai->ai_addr, ai->ai_addrlen);
514 				break;
515 			} else {
516 				oerrno = errno;
517 				debug("connect to address %s port %s: %s",
518 				    ntop, strport, strerror(errno));
519 				close(sock);
520 				sock = -1;
521 				errno = oerrno;
522 			}
523 		}
524 		if (sock != -1)
525 			break;	/* Successful connection. */
526 	}
527 
528 	/* Return failure if we didn't get a successful connection. */
529 	if (sock == -1) {
530 		error("ssh: connect to host %s port %s: %s",
531 		    host, strport, errno == 0 ? "failure" : strerror(errno));
532 		return -1;
533 	}
534 
535 	debug("Connection established.");
536 
537 	/* Set SO_KEEPALIVE if requested. */
538 	if (want_keepalive &&
539 	    setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
540 	    sizeof(on)) == -1)
541 		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
542 
543 	/* Set the connection. */
544 	if (ssh_packet_set_connection(ssh, sock, sock) == NULL)
545 		return -1; /* ssh_packet_set_connection logs error */
546 
547 	return 0;
548 }
549 
550 int
551 ssh_connect(struct ssh *ssh, const char *host, const char *host_arg,
552     struct addrinfo *addrs, struct sockaddr_storage *hostaddr, u_short port,
553     int connection_attempts, int *timeout_ms, int want_keepalive)
554 {
555 	int in, out;
556 
557 	if (options.proxy_command == NULL) {
558 		return ssh_connect_direct(ssh, host, addrs, hostaddr, port,
559 		    connection_attempts, timeout_ms, want_keepalive);
560 	} else if (strcmp(options.proxy_command, "-") == 0) {
561 		if ((in = dup(STDIN_FILENO)) == -1 ||
562 		    (out = dup(STDOUT_FILENO)) == -1) {
563 			if (in >= 0)
564 				close(in);
565 			error_f("dup() in/out failed");
566 			return -1; /* ssh_packet_set_connection logs error */
567 		}
568 		if ((ssh_packet_set_connection(ssh, in, out)) == NULL)
569 			return -1; /* ssh_packet_set_connection logs error */
570 		return 0;
571 	} else if (options.proxy_use_fdpass) {
572 		return ssh_proxy_fdpass_connect(ssh, host, host_arg, port,
573 		    options.proxy_command);
574 	}
575 	return ssh_proxy_connect(ssh, host, host_arg, port,
576 	    options.proxy_command);
577 }
578 
579 /* defaults to 'no' */
580 static int
581 confirm(const char *prompt, const char *fingerprint)
582 {
583 	const char *msg, *again = "Please type 'yes' or 'no': ";
584 	const char *again_fp = "Please type 'yes', 'no' or the fingerprint: ";
585 	char *p, *cp;
586 	int ret = -1;
587 
588 	if (options.batch_mode)
589 		return 0;
590 	for (msg = prompt;;msg = fingerprint ? again_fp : again) {
591 		cp = p = read_passphrase(msg, RP_ECHO);
592 		if (p == NULL)
593 			return 0;
594 		p += strspn(p, " \t"); /* skip leading whitespace */
595 		p[strcspn(p, " \t\n")] = '\0'; /* remove trailing whitespace */
596 		if (p[0] == '\0' || strcasecmp(p, "no") == 0)
597 			ret = 0;
598 		else if (strcasecmp(p, "yes") == 0 || (fingerprint != NULL &&
599 		    strcmp(p, fingerprint) == 0))
600 			ret = 1;
601 		free(cp);
602 		if (ret != -1)
603 			return ret;
604 	}
605 }
606 
607 static int
608 sockaddr_is_local(struct sockaddr *hostaddr)
609 {
610 	switch (hostaddr->sa_family) {
611 	case AF_INET:
612 		return (ntohl(((struct sockaddr_in *)hostaddr)->
613 		    sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
614 	case AF_INET6:
615 		return IN6_IS_ADDR_LOOPBACK(
616 		    &(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
617 	default:
618 		return 0;
619 	}
620 }
621 
622 /*
623  * Prepare the hostname and ip address strings that are used to lookup
624  * host keys in known_hosts files. These may have a port number appended.
625  */
626 void
627 get_hostfile_hostname_ipaddr(char *hostname, struct sockaddr *hostaddr,
628     u_short port, char **hostfile_hostname, char **hostfile_ipaddr)
629 {
630 	char ntop[NI_MAXHOST];
631 
632 	/*
633 	 * We don't have the remote ip-address for connections
634 	 * using a proxy command
635 	 */
636 	if (hostfile_ipaddr != NULL) {
637 		if (options.proxy_command == NULL) {
638 			if (getnameinfo(hostaddr, hostaddr->sa_len,
639 			    ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST) != 0)
640 			fatal_f("getnameinfo failed");
641 			*hostfile_ipaddr = put_host_port(ntop, port);
642 		} else {
643 			*hostfile_ipaddr = xstrdup("<no hostip for proxy "
644 			    "command>");
645 		}
646 	}
647 
648 	/*
649 	 * Allow the user to record the key under a different name or
650 	 * differentiate a non-standard port.  This is useful for ssh
651 	 * tunneling over forwarded connections or if you run multiple
652 	 * sshd's on different ports on the same machine.
653 	 */
654 	if (hostfile_hostname != NULL) {
655 		if (options.host_key_alias != NULL) {
656 			*hostfile_hostname = xstrdup(options.host_key_alias);
657 			debug("using hostkeyalias: %s", *hostfile_hostname);
658 		} else {
659 			*hostfile_hostname = put_host_port(hostname, port);
660 		}
661 	}
662 }
663 
664 /* returns non-zero if path appears in hostfiles, or 0 if not. */
665 static int
666 path_in_hostfiles(const char *path, char **hostfiles, u_int num_hostfiles)
667 {
668 	u_int i;
669 
670 	for (i = 0; i < num_hostfiles; i++) {
671 		if (strcmp(path, hostfiles[i]) == 0)
672 			return 1;
673 	}
674 	return 0;
675 }
676 
677 struct find_by_key_ctx {
678 	const char *host, *ip;
679 	const struct sshkey *key;
680 	char **names;
681 	u_int nnames;
682 };
683 
684 /* Try to replace home directory prefix (per $HOME) with a ~/ sequence */
685 static char *
686 try_tilde_unexpand(const char *path)
687 {
688 	char *home, *ret = NULL;
689 	size_t l;
690 
691 	if (*path != '/')
692 		return xstrdup(path);
693 	if ((home = getenv("HOME")) == NULL || (l = strlen(home)) == 0)
694 		return xstrdup(path);
695 	if (strncmp(path, home, l) != 0)
696 		return xstrdup(path);
697 	/*
698 	 * ensure we have matched on a path boundary: either the $HOME that
699 	 * we just compared ends with a '/' or the next character of the path
700 	 * must be a '/'.
701 	 */
702 	if (home[l - 1] != '/' && path[l] != '/')
703 		return xstrdup(path);
704 	if (path[l] == '/')
705 		l++;
706 	xasprintf(&ret, "~/%s", path + l);
707 	return ret;
708 }
709 
710 static int
711 hostkeys_find_by_key_cb(struct hostkey_foreach_line *l, void *_ctx)
712 {
713 	struct find_by_key_ctx *ctx = (struct find_by_key_ctx *)_ctx;
714 	char *path;
715 
716 	/* we are looking for keys with names that *do not* match */
717 	if ((l->match & HKF_MATCH_HOST) != 0)
718 		return 0;
719 	/* not interested in marker lines */
720 	if (l->marker != MRK_NONE)
721 		return 0;
722 	/* we are only interested in exact key matches */
723 	if (l->key == NULL || !sshkey_equal(ctx->key, l->key))
724 		return 0;
725 	path = try_tilde_unexpand(l->path);
726 	debug_f("found matching key in %s:%lu", path, l->linenum);
727 	ctx->names = xrecallocarray(ctx->names,
728 	    ctx->nnames, ctx->nnames + 1, sizeof(*ctx->names));
729 	xasprintf(&ctx->names[ctx->nnames], "%s:%lu: %s", path, l->linenum,
730 	    strncmp(l->hosts, HASH_MAGIC, strlen(HASH_MAGIC)) == 0 ?
731 	    "[hashed name]" : l->hosts);
732 	ctx->nnames++;
733 	free(path);
734 	return 0;
735 }
736 
737 static int
738 hostkeys_find_by_key_hostfile(const char *file, const char *which,
739     struct find_by_key_ctx *ctx)
740 {
741 	int r;
742 
743 	debug3_f("trying %s hostfile \"%s\"", which, file);
744 	if ((r = hostkeys_foreach(file, hostkeys_find_by_key_cb, ctx,
745 	    ctx->host, ctx->ip, HKF_WANT_PARSE_KEY, 0)) != 0) {
746 		if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
747 			debug_f("hostkeys file %s does not exist", file);
748 			return 0;
749 		}
750 		error_fr(r, "hostkeys_foreach failed for %s", file);
751 		return r;
752 	}
753 	return 0;
754 }
755 
756 /*
757  * Find 'key' in known hosts file(s) that do not match host/ip.
758  * Used to display also-known-as information for previously-unseen hostkeys.
759  */
760 static void
761 hostkeys_find_by_key(const char *host, const char *ip, const struct sshkey *key,
762     char **user_hostfiles, u_int num_user_hostfiles,
763     char **system_hostfiles, u_int num_system_hostfiles,
764     char ***names, u_int *nnames)
765 {
766 	struct find_by_key_ctx ctx = {0, 0, 0, 0, 0};
767 	u_int i;
768 
769 	*names = NULL;
770 	*nnames = 0;
771 
772 	if (key == NULL || sshkey_is_cert(key))
773 		return;
774 
775 	ctx.host = host;
776 	ctx.ip = ip;
777 	ctx.key = key;
778 
779 	for (i = 0; i < num_user_hostfiles; i++) {
780 		if (hostkeys_find_by_key_hostfile(user_hostfiles[i],
781 		    "user", &ctx) != 0)
782 			goto fail;
783 	}
784 	for (i = 0; i < num_system_hostfiles; i++) {
785 		if (hostkeys_find_by_key_hostfile(system_hostfiles[i],
786 		    "system", &ctx) != 0)
787 			goto fail;
788 	}
789 	/* success */
790 	*names = ctx.names;
791 	*nnames = ctx.nnames;
792 	ctx.names = NULL;
793 	ctx.nnames = 0;
794 	return;
795  fail:
796 	for (i = 0; i < ctx.nnames; i++)
797 		free(ctx.names[i]);
798 	free(ctx.names);
799 }
800 
801 #define MAX_OTHER_NAMES	8 /* Maximum number of names to list */
802 static char *
803 other_hostkeys_message(const char *host, const char *ip,
804     const struct sshkey *key,
805     char **user_hostfiles, u_int num_user_hostfiles,
806     char **system_hostfiles, u_int num_system_hostfiles)
807 {
808 	char *ret = NULL, **othernames = NULL;
809 	u_int i, n, num_othernames = 0;
810 
811 	hostkeys_find_by_key(host, ip, key,
812 	    user_hostfiles, num_user_hostfiles,
813 	    system_hostfiles, num_system_hostfiles,
814 	    &othernames, &num_othernames);
815 	if (num_othernames == 0)
816 		return xstrdup("This key is not known by any other names");
817 
818 	xasprintf(&ret, "This host key is known by the following other "
819 	    "names/addresses:");
820 
821 	n = num_othernames;
822 	if (n > MAX_OTHER_NAMES)
823 		n = MAX_OTHER_NAMES;
824 	for (i = 0; i < n; i++) {
825 		xextendf(&ret, "\n", "    %s", othernames[i]);
826 	}
827 	if (n < num_othernames) {
828 		xextendf(&ret, "\n", "    (%d additional names omitted)",
829 		    num_othernames - n);
830 	}
831 	for (i = 0; i < num_othernames; i++)
832 		free(othernames[i]);
833 	free(othernames);
834 	return ret;
835 }
836 
837 void
838 load_hostkeys_command(struct hostkeys *hostkeys, const char *command_template,
839     const char *invocation, const struct ssh_conn_info *cinfo,
840     const struct sshkey *host_key, const char *hostfile_hostname)
841 {
842 	int r, i, ac = 0;
843 	char *key_fp = NULL, *keytext = NULL, *tmp;
844 	char *command = NULL, *tag = NULL, **av = NULL;
845 	FILE *f = NULL;
846 	pid_t pid;
847 	void (*osigchld)(int);
848 
849 	xasprintf(&tag, "KnownHostsCommand-%s", invocation);
850 
851 	if (host_key != NULL) {
852 		if ((key_fp = sshkey_fingerprint(host_key,
853 		    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
854 			fatal_f("sshkey_fingerprint failed");
855 		if ((r = sshkey_to_base64(host_key, &keytext)) != 0)
856 			fatal_fr(r, "sshkey_to_base64 failed");
857 	}
858 	/*
859 	 * NB. all returns later this function should go via "out" to
860 	 * ensure the original SIGCHLD handler is restored properly.
861 	 */
862 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
863 
864 	/* Turn the command into an argument vector */
865 	if (argv_split(command_template, &ac, &av, 0) != 0) {
866 		error("%s \"%s\" contains invalid quotes", tag,
867 		    command_template);
868 		goto out;
869 	}
870 	if (ac == 0) {
871 		error("%s \"%s\" yielded no arguments", tag,
872 		    command_template);
873 		goto out;
874 	}
875 	for (i = 1; i < ac; i++) {
876 		tmp = percent_dollar_expand(av[i],
877 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
878 		    "H", hostfile_hostname,
879 		    "I", invocation,
880 		    "t", host_key == NULL ? "NONE" : sshkey_ssh_name(host_key),
881 		    "f", key_fp == NULL ? "NONE" : key_fp,
882 		    "K", keytext == NULL ? "NONE" : keytext,
883 		    (char *)NULL);
884 		if (tmp == NULL)
885 			fatal_f("percent_expand failed");
886 		free(av[i]);
887 		av[i] = tmp;
888 	}
889 	/* Prepare a printable command for logs, etc. */
890 	command = argv_assemble(ac, av);
891 
892 	if ((pid = subprocess(tag, command, ac, av, &f,
893 	    SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_UNSAFE_PATH|
894 	    SSH_SUBPROCESS_PRESERVE_ENV, NULL, NULL, NULL)) == 0)
895 		goto out;
896 
897 	load_hostkeys_file(hostkeys, hostfile_hostname, tag, f, 1);
898 
899 	if (exited_cleanly(pid, tag, command, 0) != 0)
900 		fatal("KnownHostsCommand failed");
901 
902  out:
903 	if (f != NULL)
904 		fclose(f);
905 	ssh_signal(SIGCHLD, osigchld);
906 	for (i = 0; i < ac; i++)
907 		free(av[i]);
908 	free(av);
909 	free(tag);
910 	free(command);
911 	free(key_fp);
912 	free(keytext);
913 }
914 
915 /*
916  * check whether the supplied host key is valid, return -1 if the key
917  * is not valid. user_hostfile[0] will not be updated if 'readonly' is true.
918  */
919 #define RDRW	0
920 #define RDONLY	1
921 #define ROQUIET	2
922 static int
923 check_host_key(char *hostname, const struct ssh_conn_info *cinfo,
924     struct sockaddr *hostaddr, u_short port,
925     struct sshkey *host_key, int readonly, int clobber_port,
926     char **user_hostfiles, u_int num_user_hostfiles,
927     char **system_hostfiles, u_int num_system_hostfiles,
928     const char *hostfile_command)
929 {
930 	HostStatus host_status = -1, ip_status = -1;
931 	struct sshkey *raw_key = NULL;
932 	char *ip = NULL, *host = NULL;
933 	char hostline[1000], *hostp, *fp, *ra;
934 	char msg[1024];
935 	const char *type, *fail_reason;
936 	const struct hostkey_entry *host_found = NULL, *ip_found = NULL;
937 	int len, cancelled_forwarding = 0, confirmed;
938 	int local = sockaddr_is_local(hostaddr);
939 	int r, want_cert = sshkey_is_cert(host_key), host_ip_differ = 0;
940 	int hostkey_trusted = 0; /* Known or explicitly accepted by user */
941 	struct hostkeys *host_hostkeys, *ip_hostkeys;
942 	u_int i;
943 
944 	/*
945 	 * Force accepting of the host key for loopback/localhost. The
946 	 * problem is that if the home directory is NFS-mounted to multiple
947 	 * machines, localhost will refer to a different machine in each of
948 	 * them, and the user will get bogus HOST_CHANGED warnings.  This
949 	 * essentially disables host authentication for localhost; however,
950 	 * this is probably not a real problem.
951 	 */
952 	if (options.no_host_authentication_for_localhost == 1 && local &&
953 	    options.host_key_alias == NULL) {
954 		debug("Forcing accepting of host key for "
955 		    "loopback/localhost.");
956 		options.update_hostkeys = 0;
957 		return 0;
958 	}
959 
960 	/*
961 	 * Prepare the hostname and address strings used for hostkey lookup.
962 	 * In some cases, these will have a port number appended.
963 	 */
964 	get_hostfile_hostname_ipaddr(hostname, hostaddr,
965 	    clobber_port ? 0 : port, &host, &ip);
966 
967 	/*
968 	 * Turn off check_host_ip if the connection is to localhost, via proxy
969 	 * command or if we don't have a hostname to compare with
970 	 */
971 	if (options.check_host_ip && (local ||
972 	    strcmp(hostname, ip) == 0 || options.proxy_command != NULL))
973 		options.check_host_ip = 0;
974 
975 	host_hostkeys = init_hostkeys();
976 	for (i = 0; i < num_user_hostfiles; i++)
977 		load_hostkeys(host_hostkeys, host, user_hostfiles[i], 0);
978 	for (i = 0; i < num_system_hostfiles; i++)
979 		load_hostkeys(host_hostkeys, host, system_hostfiles[i], 0);
980 	if (hostfile_command != NULL && !clobber_port) {
981 		load_hostkeys_command(host_hostkeys, hostfile_command,
982 		    "HOSTNAME", cinfo, host_key, host);
983 	}
984 
985 	ip_hostkeys = NULL;
986 	if (!want_cert && options.check_host_ip) {
987 		ip_hostkeys = init_hostkeys();
988 		for (i = 0; i < num_user_hostfiles; i++)
989 			load_hostkeys(ip_hostkeys, ip, user_hostfiles[i], 0);
990 		for (i = 0; i < num_system_hostfiles; i++)
991 			load_hostkeys(ip_hostkeys, ip, system_hostfiles[i], 0);
992 		if (hostfile_command != NULL && !clobber_port) {
993 			load_hostkeys_command(ip_hostkeys, hostfile_command,
994 			    "ADDRESS", cinfo, host_key, ip);
995 		}
996 	}
997 
998  retry:
999 	/* Reload these as they may have changed on cert->key downgrade */
1000 	want_cert = sshkey_is_cert(host_key);
1001 	type = sshkey_type(host_key);
1002 
1003 	/*
1004 	 * Check if the host key is present in the user's list of known
1005 	 * hosts or in the systemwide list.
1006 	 */
1007 	host_status = check_key_in_hostkeys(host_hostkeys, host_key,
1008 	    &host_found);
1009 
1010 	/*
1011 	 * If there are no hostfiles, or if the hostkey was found via
1012 	 * KnownHostsCommand, then don't try to touch the disk.
1013 	 */
1014 	if (!readonly && (num_user_hostfiles == 0 ||
1015 	    (host_found != NULL && host_found->note != 0)))
1016 		readonly = RDONLY;
1017 
1018 	/*
1019 	 * Also perform check for the ip address, skip the check if we are
1020 	 * localhost, looking for a certificate, or the hostname was an ip
1021 	 * address to begin with.
1022 	 */
1023 	if (!want_cert && ip_hostkeys != NULL) {
1024 		ip_status = check_key_in_hostkeys(ip_hostkeys, host_key,
1025 		    &ip_found);
1026 		if (host_status == HOST_CHANGED &&
1027 		    (ip_status != HOST_CHANGED ||
1028 		    (ip_found != NULL &&
1029 		    !sshkey_equal(ip_found->key, host_found->key))))
1030 			host_ip_differ = 1;
1031 	} else
1032 		ip_status = host_status;
1033 
1034 	switch (host_status) {
1035 	case HOST_OK:
1036 		/* The host is known and the key matches. */
1037 		debug("Host '%.200s' is known and matches the %s host %s.",
1038 		    host, type, want_cert ? "certificate" : "key");
1039 		debug("Found %s in %s:%lu", want_cert ? "CA key" : "key",
1040 		    host_found->file, host_found->line);
1041 		if (want_cert) {
1042 			if (sshkey_cert_check_host(host_key,
1043 			    options.host_key_alias == NULL ?
1044 			    hostname : options.host_key_alias, 0,
1045 			    options.ca_sign_algorithms, &fail_reason) != 0) {
1046 				error("%s", fail_reason);
1047 				goto fail;
1048 			}
1049 			/*
1050 			 * Do not attempt hostkey update if a certificate was
1051 			 * successfully matched.
1052 			 */
1053 			if (options.update_hostkeys != 0) {
1054 				options.update_hostkeys = 0;
1055 				debug3_f("certificate host key in use; "
1056 				    "disabling UpdateHostkeys");
1057 			}
1058 		}
1059 		/* Turn off UpdateHostkeys if key was in system known_hosts */
1060 		if (options.update_hostkeys != 0 &&
1061 		    (path_in_hostfiles(host_found->file,
1062 		    system_hostfiles, num_system_hostfiles) ||
1063 		    (ip_status == HOST_OK && ip_found != NULL &&
1064 		    path_in_hostfiles(ip_found->file,
1065 		    system_hostfiles, num_system_hostfiles)))) {
1066 			options.update_hostkeys = 0;
1067 			debug3_f("host key found in GlobalKnownHostsFile; "
1068 			    "disabling UpdateHostkeys");
1069 		}
1070 		if (options.update_hostkeys != 0 && host_found->note) {
1071 			options.update_hostkeys = 0;
1072 			debug3_f("host key found via KnownHostsCommand; "
1073 			    "disabling UpdateHostkeys");
1074 		}
1075 		if (options.check_host_ip && ip_status == HOST_NEW) {
1076 			if (readonly || want_cert)
1077 				logit("%s host key for IP address "
1078 				    "'%.128s' not in list of known hosts.",
1079 				    type, ip);
1080 			else if (!add_host_to_hostfile(user_hostfiles[0], ip,
1081 			    host_key, options.hash_known_hosts))
1082 				logit("Failed to add the %s host key for IP "
1083 				    "address '%.128s' to the list of known "
1084 				    "hosts (%.500s).", type, ip,
1085 				    user_hostfiles[0]);
1086 			else
1087 				logit("Warning: Permanently added the %s host "
1088 				    "key for IP address '%.128s' to the list "
1089 				    "of known hosts.", type, ip);
1090 		} else if (options.visual_host_key) {
1091 			fp = sshkey_fingerprint(host_key,
1092 			    options.fingerprint_hash, SSH_FP_DEFAULT);
1093 			ra = sshkey_fingerprint(host_key,
1094 			    options.fingerprint_hash, SSH_FP_RANDOMART);
1095 			if (fp == NULL || ra == NULL)
1096 				fatal_f("sshkey_fingerprint failed");
1097 			logit("Host key fingerprint is %s\n%s", fp, ra);
1098 			free(ra);
1099 			free(fp);
1100 		}
1101 		hostkey_trusted = 1;
1102 		break;
1103 	case HOST_NEW:
1104 		if (options.host_key_alias == NULL && port != 0 &&
1105 		    port != SSH_DEFAULT_PORT && !clobber_port) {
1106 			debug("checking without port identifier");
1107 			if (check_host_key(hostname, cinfo, hostaddr, 0,
1108 			    host_key, ROQUIET, 1,
1109 			    user_hostfiles, num_user_hostfiles,
1110 			    system_hostfiles, num_system_hostfiles,
1111 			    hostfile_command) == 0) {
1112 				debug("found matching key w/out port");
1113 				break;
1114 			}
1115 		}
1116 		if (readonly || want_cert)
1117 			goto fail;
1118 		/* The host is new. */
1119 		if (options.strict_host_key_checking ==
1120 		    SSH_STRICT_HOSTKEY_YES) {
1121 			/*
1122 			 * User has requested strict host key checking.  We
1123 			 * will not add the host key automatically.  The only
1124 			 * alternative left is to abort.
1125 			 */
1126 			error("No %s host key is known for %.200s and you "
1127 			    "have requested strict checking.", type, host);
1128 			goto fail;
1129 		} else if (options.strict_host_key_checking ==
1130 		    SSH_STRICT_HOSTKEY_ASK) {
1131 			char *msg1 = NULL, *msg2 = NULL;
1132 
1133 			xasprintf(&msg1, "The authenticity of host "
1134 			    "'%.200s (%s)' can't be established", host, ip);
1135 
1136 			if (show_other_keys(host_hostkeys, host_key)) {
1137 				xextendf(&msg1, "\n", "but keys of different "
1138 				    "type are already known for this host.");
1139 			} else
1140 				xextendf(&msg1, "", ".");
1141 
1142 			fp = sshkey_fingerprint(host_key,
1143 			    options.fingerprint_hash, SSH_FP_DEFAULT);
1144 			ra = sshkey_fingerprint(host_key,
1145 			    options.fingerprint_hash, SSH_FP_RANDOMART);
1146 			if (fp == NULL || ra == NULL)
1147 				fatal_f("sshkey_fingerprint failed");
1148 			xextendf(&msg1, "\n", "%s key fingerprint is %s.",
1149 			    type, fp);
1150 			if (options.visual_host_key)
1151 				xextendf(&msg1, "\n", "%s", ra);
1152 			if (options.verify_host_key_dns) {
1153 				xextendf(&msg1, "\n",
1154 				    "%s host key fingerprint found in DNS.",
1155 				    matching_host_key_dns ?
1156 				    "Matching" : "No matching");
1157 			}
1158 			/* msg2 informs for other names matching this key */
1159 			if ((msg2 = other_hostkeys_message(host, ip, host_key,
1160 			    user_hostfiles, num_user_hostfiles,
1161 			    system_hostfiles, num_system_hostfiles)) != NULL)
1162 				xextendf(&msg1, "\n", "%s", msg2);
1163 
1164 			xextendf(&msg1, "\n",
1165 			    "Are you sure you want to continue connecting "
1166 			    "(yes/no/[fingerprint])? ");
1167 
1168 			confirmed = confirm(msg1, fp);
1169 			free(ra);
1170 			free(fp);
1171 			free(msg1);
1172 			free(msg2);
1173 			if (!confirmed)
1174 				goto fail;
1175 			hostkey_trusted = 1; /* user explicitly confirmed */
1176 		}
1177 		/*
1178 		 * If in "new" or "off" strict mode, add the key automatically
1179 		 * to the local known_hosts file.
1180 		 */
1181 		if (options.check_host_ip && ip_status == HOST_NEW) {
1182 			snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1183 			hostp = hostline;
1184 			if (options.hash_known_hosts) {
1185 				/* Add hash of host and IP separately */
1186 				r = add_host_to_hostfile(user_hostfiles[0],
1187 				    host, host_key, options.hash_known_hosts) &&
1188 				    add_host_to_hostfile(user_hostfiles[0], ip,
1189 				    host_key, options.hash_known_hosts);
1190 			} else {
1191 				/* Add unhashed "host,ip" */
1192 				r = add_host_to_hostfile(user_hostfiles[0],
1193 				    hostline, host_key,
1194 				    options.hash_known_hosts);
1195 			}
1196 		} else {
1197 			r = add_host_to_hostfile(user_hostfiles[0], host,
1198 			    host_key, options.hash_known_hosts);
1199 			hostp = host;
1200 		}
1201 
1202 		if (!r)
1203 			logit("Failed to add the host to the list of known "
1204 			    "hosts (%.500s).", user_hostfiles[0]);
1205 		else
1206 			logit("Warning: Permanently added '%.200s' (%s) to the "
1207 			    "list of known hosts.", hostp, type);
1208 		break;
1209 	case HOST_REVOKED:
1210 		error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1211 		error("@       WARNING: REVOKED HOST KEY DETECTED!               @");
1212 		error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1213 		error("The %s host key for %s is marked as revoked.", type, host);
1214 		error("This could mean that a stolen key is being used to");
1215 		error("impersonate this host.");
1216 
1217 		/*
1218 		 * If strict host key checking is in use, the user will have
1219 		 * to edit the key manually and we can only abort.
1220 		 */
1221 		if (options.strict_host_key_checking !=
1222 		    SSH_STRICT_HOSTKEY_OFF) {
1223 			error("%s host key for %.200s was revoked and you have "
1224 			    "requested strict checking.", type, host);
1225 			goto fail;
1226 		}
1227 		goto continue_unsafe;
1228 
1229 	case HOST_CHANGED:
1230 		if (want_cert) {
1231 			/*
1232 			 * This is only a debug() since it is valid to have
1233 			 * CAs with wildcard DNS matches that don't match
1234 			 * all hosts that one might visit.
1235 			 */
1236 			debug("Host certificate authority does not "
1237 			    "match %s in %s:%lu", CA_MARKER,
1238 			    host_found->file, host_found->line);
1239 			goto fail;
1240 		}
1241 		if (readonly == ROQUIET)
1242 			goto fail;
1243 		if (options.check_host_ip && host_ip_differ) {
1244 			const char *key_msg;
1245 			if (ip_status == HOST_NEW)
1246 				key_msg = "is unknown";
1247 			else if (ip_status == HOST_OK)
1248 				key_msg = "is unchanged";
1249 			else
1250 				key_msg = "has a different value";
1251 			error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1252 			error("@       WARNING: POSSIBLE DNS SPOOFING DETECTED!          @");
1253 			error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1254 			error("The %s host key for %s has changed,", type, host);
1255 			error("and the key for the corresponding IP address %s", ip);
1256 			error("%s. This could either mean that", key_msg);
1257 			error("DNS SPOOFING is happening or the IP address for the host");
1258 			error("and its host key have changed at the same time.");
1259 			if (ip_status != HOST_NEW)
1260 				error("Offending key for IP in %s:%lu",
1261 				    ip_found->file, ip_found->line);
1262 		}
1263 		/* The host key has changed. */
1264 		warn_changed_key(host_key);
1265 		error("Add correct host key in %.100s to get rid of this message.",
1266 		    user_hostfiles[0]);
1267 		error("Offending %s key in %s:%lu",
1268 		    sshkey_type(host_found->key),
1269 		    host_found->file, host_found->line);
1270 
1271 		/*
1272 		 * If strict host key checking is in use, the user will have
1273 		 * to edit the key manually and we can only abort.
1274 		 */
1275 		if (options.strict_host_key_checking !=
1276 		    SSH_STRICT_HOSTKEY_OFF) {
1277 			error("Host key for %.200s has changed and you have "
1278 			    "requested strict checking.", host);
1279 			goto fail;
1280 		}
1281 
1282  continue_unsafe:
1283 		/*
1284 		 * If strict host key checking has not been requested, allow
1285 		 * the connection but without MITM-able authentication or
1286 		 * forwarding.
1287 		 */
1288 		if (options.password_authentication) {
1289 			error("Password authentication is disabled to avoid "
1290 			    "man-in-the-middle attacks.");
1291 			options.password_authentication = 0;
1292 			cancelled_forwarding = 1;
1293 		}
1294 		if (options.kbd_interactive_authentication) {
1295 			error("Keyboard-interactive authentication is disabled"
1296 			    " to avoid man-in-the-middle attacks.");
1297 			options.kbd_interactive_authentication = 0;
1298 			cancelled_forwarding = 1;
1299 		}
1300 		if (options.forward_agent) {
1301 			error("Agent forwarding is disabled to avoid "
1302 			    "man-in-the-middle attacks.");
1303 			options.forward_agent = 0;
1304 			cancelled_forwarding = 1;
1305 		}
1306 		if (options.forward_x11) {
1307 			error("X11 forwarding is disabled to avoid "
1308 			    "man-in-the-middle attacks.");
1309 			options.forward_x11 = 0;
1310 			cancelled_forwarding = 1;
1311 		}
1312 		if (options.num_local_forwards > 0 ||
1313 		    options.num_remote_forwards > 0) {
1314 			error("Port forwarding is disabled to avoid "
1315 			    "man-in-the-middle attacks.");
1316 			options.num_local_forwards =
1317 			    options.num_remote_forwards = 0;
1318 			cancelled_forwarding = 1;
1319 		}
1320 		if (options.tun_open != SSH_TUNMODE_NO) {
1321 			error("Tunnel forwarding is disabled to avoid "
1322 			    "man-in-the-middle attacks.");
1323 			options.tun_open = SSH_TUNMODE_NO;
1324 			cancelled_forwarding = 1;
1325 		}
1326 		if (options.update_hostkeys != 0) {
1327 			error("UpdateHostkeys is disabled because the host "
1328 			    "key is not trusted.");
1329 			options.update_hostkeys = 0;
1330 		}
1331 		if (options.exit_on_forward_failure && cancelled_forwarding)
1332 			fatal("Error: forwarding disabled due to host key "
1333 			    "check failure");
1334 
1335 		/*
1336 		 * XXX Should permit the user to change to use the new id.
1337 		 * This could be done by converting the host key to an
1338 		 * identifying sentence, tell that the host identifies itself
1339 		 * by that sentence, and ask the user if they wish to
1340 		 * accept the authentication.
1341 		 */
1342 		break;
1343 	case HOST_FOUND:
1344 		fatal("internal error");
1345 		break;
1346 	}
1347 
1348 	if (options.check_host_ip && host_status != HOST_CHANGED &&
1349 	    ip_status == HOST_CHANGED) {
1350 		snprintf(msg, sizeof(msg),
1351 		    "Warning: the %s host key for '%.200s' "
1352 		    "differs from the key for the IP address '%.128s'"
1353 		    "\nOffending key for IP in %s:%lu",
1354 		    type, host, ip, ip_found->file, ip_found->line);
1355 		if (host_status == HOST_OK) {
1356 			len = strlen(msg);
1357 			snprintf(msg + len, sizeof(msg) - len,
1358 			    "\nMatching host key in %s:%lu",
1359 			    host_found->file, host_found->line);
1360 		}
1361 		if (options.strict_host_key_checking ==
1362 		    SSH_STRICT_HOSTKEY_ASK) {
1363 			strlcat(msg, "\nAre you sure you want "
1364 			    "to continue connecting (yes/no)? ", sizeof(msg));
1365 			if (!confirm(msg, NULL))
1366 				goto fail;
1367 		} else if (options.strict_host_key_checking !=
1368 		    SSH_STRICT_HOSTKEY_OFF) {
1369 			logit("%s", msg);
1370 			error("Exiting, you have requested strict checking.");
1371 			goto fail;
1372 		} else {
1373 			logit("%s", msg);
1374 		}
1375 	}
1376 
1377 	if (!hostkey_trusted && options.update_hostkeys) {
1378 		debug_f("hostkey not known or explicitly trusted: "
1379 		    "disabling UpdateHostkeys");
1380 		options.update_hostkeys = 0;
1381 	}
1382 
1383 	free(ip);
1384 	free(host);
1385 	if (host_hostkeys != NULL)
1386 		free_hostkeys(host_hostkeys);
1387 	if (ip_hostkeys != NULL)
1388 		free_hostkeys(ip_hostkeys);
1389 	return 0;
1390 
1391 fail:
1392 	if (want_cert && host_status != HOST_REVOKED) {
1393 		/*
1394 		 * No matching certificate. Downgrade cert to raw key and
1395 		 * search normally.
1396 		 */
1397 		debug("No matching CA found. Retry with plain key");
1398 		if ((r = sshkey_from_private(host_key, &raw_key)) != 0)
1399 			fatal_fr(r, "decode key");
1400 		if ((r = sshkey_drop_cert(raw_key)) != 0)
1401 			fatal_r(r, "Couldn't drop certificate");
1402 		host_key = raw_key;
1403 		goto retry;
1404 	}
1405 	sshkey_free(raw_key);
1406 	free(ip);
1407 	free(host);
1408 	if (host_hostkeys != NULL)
1409 		free_hostkeys(host_hostkeys);
1410 	if (ip_hostkeys != NULL)
1411 		free_hostkeys(ip_hostkeys);
1412 	return -1;
1413 }
1414 
1415 /* returns 0 if key verifies or -1 if key does NOT verify */
1416 int
1417 verify_host_key(char *host, struct sockaddr *hostaddr, struct sshkey *host_key,
1418     const struct ssh_conn_info *cinfo)
1419 {
1420 	u_int i;
1421 	int r = -1, flags = 0;
1422 	char valid[64], *fp = NULL, *cafp = NULL;
1423 	struct sshkey *plain = NULL;
1424 
1425 	if ((fp = sshkey_fingerprint(host_key,
1426 	    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
1427 		error_fr(r, "fingerprint host key");
1428 		r = -1;
1429 		goto out;
1430 	}
1431 
1432 	if (sshkey_is_cert(host_key)) {
1433 		if ((cafp = sshkey_fingerprint(host_key->cert->signature_key,
1434 		    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
1435 			error_fr(r, "fingerprint CA key");
1436 			r = -1;
1437 			goto out;
1438 		}
1439 		sshkey_format_cert_validity(host_key->cert,
1440 		    valid, sizeof(valid));
1441 		debug("Server host certificate: %s %s, serial %llu "
1442 		    "ID \"%s\" CA %s %s valid %s",
1443 		    sshkey_ssh_name(host_key), fp,
1444 		    (unsigned long long)host_key->cert->serial,
1445 		    host_key->cert->key_id,
1446 		    sshkey_ssh_name(host_key->cert->signature_key), cafp,
1447 		    valid);
1448 		for (i = 0; i < host_key->cert->nprincipals; i++) {
1449 			debug2("Server host certificate hostname: %s",
1450 			    host_key->cert->principals[i]);
1451 		}
1452 	} else {
1453 		debug("Server host key: %s %s", sshkey_ssh_name(host_key), fp);
1454 	}
1455 
1456 	if (sshkey_equal(previous_host_key, host_key)) {
1457 		debug2_f("server host key %s %s matches cached key",
1458 		    sshkey_type(host_key), fp);
1459 		r = 0;
1460 		goto out;
1461 	}
1462 
1463 	/* Check in RevokedHostKeys file if specified */
1464 	if (options.revoked_host_keys != NULL) {
1465 		r = sshkey_check_revoked(host_key, options.revoked_host_keys);
1466 		switch (r) {
1467 		case 0:
1468 			break; /* not revoked */
1469 		case SSH_ERR_KEY_REVOKED:
1470 			error("Host key %s %s revoked by file %s",
1471 			    sshkey_type(host_key), fp,
1472 			    options.revoked_host_keys);
1473 			r = -1;
1474 			goto out;
1475 		default:
1476 			error_r(r, "Error checking host key %s %s in "
1477 			    "revoked keys file %s", sshkey_type(host_key),
1478 			    fp, options.revoked_host_keys);
1479 			r = -1;
1480 			goto out;
1481 		}
1482 	}
1483 
1484 	if (options.verify_host_key_dns) {
1485 		/*
1486 		 * XXX certs are not yet supported for DNS, so downgrade
1487 		 * them and try the plain key.
1488 		 */
1489 		if ((r = sshkey_from_private(host_key, &plain)) != 0)
1490 			goto out;
1491 		if (sshkey_is_cert(plain))
1492 			sshkey_drop_cert(plain);
1493 		if (verify_host_key_dns(host, hostaddr, plain, &flags) == 0) {
1494 			if (flags & DNS_VERIFY_FOUND) {
1495 				if (options.verify_host_key_dns == 1 &&
1496 				    flags & DNS_VERIFY_MATCH &&
1497 				    flags & DNS_VERIFY_SECURE) {
1498 					r = 0;
1499 					goto out;
1500 				}
1501 				if (flags & DNS_VERIFY_MATCH) {
1502 					matching_host_key_dns = 1;
1503 				} else {
1504 					warn_changed_key(plain);
1505 					error("Update the SSHFP RR in DNS "
1506 					    "with the new host key to get rid "
1507 					    "of this message.");
1508 				}
1509 			}
1510 		}
1511 	}
1512 	r = check_host_key(host, cinfo, hostaddr, options.port, host_key,
1513 	    RDRW, 0, options.user_hostfiles, options.num_user_hostfiles,
1514 	    options.system_hostfiles, options.num_system_hostfiles,
1515 	    options.known_hosts_command);
1516 
1517 out:
1518 	sshkey_free(plain);
1519 	free(fp);
1520 	free(cafp);
1521 	if (r == 0 && host_key != NULL) {
1522 		sshkey_free(previous_host_key);
1523 		r = sshkey_from_private(host_key, &previous_host_key);
1524 	}
1525 
1526 	return r;
1527 }
1528 
1529 /*
1530  * Starts a dialog with the server, and authenticates the current user on the
1531  * server.  This does not need any extra privileges.  The basic connection
1532  * to the server must already have been established before this is called.
1533  * If login fails, this function prints an error and never returns.
1534  * This function does not require super-user privileges.
1535  */
1536 void
1537 ssh_login(struct ssh *ssh, Sensitive *sensitive, const char *orighost,
1538     struct sockaddr *hostaddr, u_short port, struct passwd *pw, int timeout_ms,
1539     const struct ssh_conn_info *cinfo)
1540 {
1541 	char *host;
1542 	char *server_user, *local_user;
1543 	int r;
1544 
1545 	local_user = xstrdup(pw->pw_name);
1546 	server_user = options.user ? options.user : local_user;
1547 
1548 	/* Convert the user-supplied hostname into all lowercase. */
1549 	host = xstrdup(orighost);
1550 	lowercase(host);
1551 
1552 	/* Exchange protocol version identification strings with the server. */
1553 	if ((r = kex_exchange_identification(ssh, timeout_ms, NULL)) != 0)
1554 		sshpkt_fatal(ssh, r, "banner exchange");
1555 
1556 	/* Put the connection into non-blocking mode. */
1557 	ssh_packet_set_nonblocking(ssh);
1558 
1559 	/* key exchange */
1560 	/* authenticate user */
1561 	debug("Authenticating to %s:%d as '%s'", host, port, server_user);
1562 	ssh_kex2(ssh, host, hostaddr, port, cinfo);
1563 	ssh_userauth2(ssh, local_user, server_user, host, sensitive);
1564 	free(local_user);
1565 	free(host);
1566 }
1567 
1568 /* print all known host keys for a given host, but skip keys of given type */
1569 static int
1570 show_other_keys(struct hostkeys *hostkeys, struct sshkey *key)
1571 {
1572 	int type[] = {
1573 		KEY_RSA,
1574 		KEY_DSA,
1575 		KEY_ECDSA,
1576 		KEY_ED25519,
1577 		KEY_XMSS,
1578 		-1
1579 	};
1580 	int i, ret = 0;
1581 	char *fp, *ra;
1582 	const struct hostkey_entry *found;
1583 
1584 	for (i = 0; type[i] != -1; i++) {
1585 		if (type[i] == key->type)
1586 			continue;
1587 		if (!lookup_key_in_hostkeys_by_type(hostkeys, type[i],
1588 		    -1, &found))
1589 			continue;
1590 		fp = sshkey_fingerprint(found->key,
1591 		    options.fingerprint_hash, SSH_FP_DEFAULT);
1592 		ra = sshkey_fingerprint(found->key,
1593 		    options.fingerprint_hash, SSH_FP_RANDOMART);
1594 		if (fp == NULL || ra == NULL)
1595 			fatal_f("sshkey_fingerprint fail");
1596 		logit("WARNING: %s key found for host %s\n"
1597 		    "in %s:%lu\n"
1598 		    "%s key fingerprint %s.",
1599 		    sshkey_type(found->key),
1600 		    found->host, found->file, found->line,
1601 		    sshkey_type(found->key), fp);
1602 		if (options.visual_host_key)
1603 			logit("%s", ra);
1604 		free(ra);
1605 		free(fp);
1606 		ret = 1;
1607 	}
1608 	return ret;
1609 }
1610 
1611 static void
1612 warn_changed_key(struct sshkey *host_key)
1613 {
1614 	char *fp;
1615 
1616 	fp = sshkey_fingerprint(host_key, options.fingerprint_hash,
1617 	    SSH_FP_DEFAULT);
1618 	if (fp == NULL)
1619 		fatal_f("sshkey_fingerprint fail");
1620 
1621 	error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1622 	error("@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @");
1623 	error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1624 	error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1625 	error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1626 	error("It is also possible that a host key has just been changed.");
1627 	error("The fingerprint for the %s key sent by the remote host is\n%s.",
1628 	    sshkey_type(host_key), fp);
1629 	error("Please contact your system administrator.");
1630 
1631 	free(fp);
1632 }
1633 
1634 /*
1635  * Execute a local command
1636  */
1637 int
1638 ssh_local_cmd(const char *args)
1639 {
1640 	const char *shell;
1641 	pid_t pid;
1642 	int status;
1643 	void (*osighand)(int);
1644 
1645 	if (!options.permit_local_command ||
1646 	    args == NULL || !*args)
1647 		return (1);
1648 
1649 	if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
1650 		shell = _PATH_BSHELL;
1651 
1652 	osighand = ssh_signal(SIGCHLD, SIG_DFL);
1653 	pid = fork();
1654 	if (pid == 0) {
1655 		ssh_signal(SIGPIPE, SIG_DFL);
1656 		debug3("Executing %s -c \"%s\"", shell, args);
1657 		execl(shell, shell, "-c", args, (char *)NULL);
1658 		error("Couldn't execute %s -c \"%s\": %s",
1659 		    shell, args, strerror(errno));
1660 		_exit(1);
1661 	} else if (pid == -1)
1662 		fatal("fork failed: %.100s", strerror(errno));
1663 	while (waitpid(pid, &status, 0) == -1)
1664 		if (errno != EINTR)
1665 			fatal("Couldn't wait for child: %s", strerror(errno));
1666 	ssh_signal(SIGCHLD, osighand);
1667 
1668 	if (!WIFEXITED(status))
1669 		return (1);
1670 
1671 	return (WEXITSTATUS(status));
1672 }
1673 
1674 void
1675 maybe_add_key_to_agent(const char *authfile, struct sshkey *private,
1676     const char *comment, const char *passphrase)
1677 {
1678 	int auth_sock = -1, r;
1679 	const char *skprovider = NULL;
1680 
1681 	if (options.add_keys_to_agent == 0)
1682 		return;
1683 
1684 	if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
1685 		debug3("no authentication agent, not adding key");
1686 		return;
1687 	}
1688 
1689 	if (options.add_keys_to_agent == 2 &&
1690 	    !ask_permission("Add key %s (%s) to agent?", authfile, comment)) {
1691 		debug3("user denied adding this key");
1692 		close(auth_sock);
1693 		return;
1694 	}
1695 	if (sshkey_is_sk(private))
1696 		skprovider = options.sk_provider;
1697 	if ((r = ssh_add_identity_constrained(auth_sock, private,
1698 	    comment == NULL ? authfile : comment,
1699 	    options.add_keys_to_agent_lifespan,
1700 	    (options.add_keys_to_agent == 3), 0, skprovider, NULL, 0)) == 0)
1701 		debug("identity added to agent: %s", authfile);
1702 	else
1703 		debug("could not add identity to agent: %s (%d)", authfile, r);
1704 	close(auth_sock);
1705 }
1706