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