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