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