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