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