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