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