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