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