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