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