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