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