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