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