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