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