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