xref: /netbsd-src/crypto/external/bsd/openssh/dist/sshconnect.c (revision 62f324d0121177eaf2e0384f92fd9ca2a751c795)
1 /*	$NetBSD: sshconnect.c,v 1.8 2013/03/29 16:19:45 christos Exp $	*/
2 /* $OpenBSD: sshconnect.c,v 1.236 2012/09/14 16:51:34 markus 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.8 2013/03/29 16:19:45 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 
59 char *client_version_string = NULL;
60 char *server_version_string = NULL;
61 
62 static int matching_host_key_dns = 0;
63 
64 static pid_t proxy_command_pid = 0;
65 
66 /* import */
67 extern Options options;
68 extern char *__progname;
69 extern uid_t original_real_uid;
70 extern uid_t original_effective_uid;
71 
72 static int show_other_keys(struct hostkeys *, Key *);
73 static void warn_changed_key(Key *);
74 
75 /*
76  * Connect to the given ssh server using a proxy command.
77  */
78 static int
79 ssh_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 
167 void
168 ssh_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  */
184 static void
185 ssh_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  */
205 static int
206 ssh_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 
272 static int
273 timeout_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  */
366 int
367 ssh_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 static void
466 send_client_banner(int connection_out, int minor1)
467 {
468 	/* Send our own protocol version identification. */
469 	if (compat20) {
470 		xasprintf(&client_version_string, "SSH-%d.%d-%.100s\r\n",
471 		    PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION);
472 	} else {
473 		xasprintf(&client_version_string, "SSH-%d.%d-%.100s\n",
474 		    PROTOCOL_MAJOR_1, minor1, SSH_VERSION);
475 	}
476 	if (roaming_atomicio(vwrite, connection_out, client_version_string,
477 	    strlen(client_version_string)) != strlen(client_version_string))
478 		fatal("write: %.100s", strerror(errno));
479 	chop(client_version_string);
480 	debug("Local version string %.100s", client_version_string);
481 }
482 
483 /*
484  * Waits for the server identification string, and sends our own
485  * identification string.
486  */
487 void
488 ssh_exchange_identification(int timeout_ms)
489 {
490 	char buf[256], remote_version[256];	/* must be same size! */
491 	int remote_major, remote_minor, mismatch;
492 	int connection_in = packet_get_connection_in();
493 	int connection_out = packet_get_connection_out();
494 	int minor1 = PROTOCOL_MINOR_1, client_banner_sent = 0;
495 	u_int i, n;
496 	size_t len;
497 	int fdsetsz, remaining, rc;
498 	struct timeval t_start, t_remaining;
499 	fd_set *fdset;
500 
501 	fdsetsz = howmany(connection_in + 1, NFDBITS) * sizeof(fd_mask);
502 	fdset = xcalloc(1, fdsetsz);
503 
504 	/*
505 	 * If we are SSH2-only then we can send the banner immediately and
506 	 * save a round-trip.
507 	 */
508 	if (options.protocol == SSH_PROTO_2) {
509 		enable_compat20();
510 		send_client_banner(connection_out, 0);
511 		client_banner_sent = 1;
512 	}
513 
514 	/* Read other side's version identification. */
515 	remaining = timeout_ms;
516 	for (n = 0;;) {
517 		for (i = 0; i < sizeof(buf) - 1; i++) {
518 			if (timeout_ms > 0) {
519 				gettimeofday(&t_start, NULL);
520 				ms_to_timeval(&t_remaining, remaining);
521 				FD_SET(connection_in, fdset);
522 				rc = select(connection_in + 1, fdset, NULL,
523 				    fdset, &t_remaining);
524 				ms_subtract_diff(&t_start, &remaining);
525 				if (rc == 0 || remaining <= 0)
526 					fatal("Connection timed out during "
527 					    "banner exchange");
528 				if (rc == -1) {
529 					if (errno == EINTR)
530 						continue;
531 					fatal("ssh_exchange_identification: "
532 					    "select: %s", strerror(errno));
533 				}
534 			}
535 
536 			len = roaming_atomicio(read, connection_in, &buf[i], 1);
537 
538 			if (len != 1 && errno == EPIPE)
539 				fatal("ssh_exchange_identification: "
540 				    "Connection closed by remote host");
541 			else if (len != 1)
542 				fatal("ssh_exchange_identification: "
543 				    "read: %.100s", strerror(errno));
544 			if (buf[i] == '\r') {
545 				buf[i] = '\n';
546 				buf[i + 1] = 0;
547 				continue;		/**XXX wait for \n */
548 			}
549 			if (buf[i] == '\n') {
550 				buf[i + 1] = 0;
551 				break;
552 			}
553 			if (++n > 65536)
554 				fatal("ssh_exchange_identification: "
555 				    "No banner received");
556 		}
557 		buf[sizeof(buf) - 1] = 0;
558 		if (strncmp(buf, "SSH-", 4) == 0)
559 			break;
560 		debug("ssh_exchange_identification: %s", buf);
561 	}
562 	server_version_string = xstrdup(buf);
563 	xfree(fdset);
564 
565 	/*
566 	 * Check that the versions match.  In future this might accept
567 	 * several versions and set appropriate flags to handle them.
568 	 */
569 	if (sscanf(server_version_string, "SSH-%d.%d-%[^\n]\n",
570 	    &remote_major, &remote_minor, remote_version) != 3)
571 		fatal("Bad remote protocol version identification: '%.100s'", buf);
572 	debug("Remote protocol version %d.%d, remote software version %.100s",
573 	    remote_major, remote_minor, remote_version);
574 
575 	compat_datafellows(remote_version);
576 	mismatch = 0;
577 
578 	switch (remote_major) {
579 	case 1:
580 		if (remote_minor == 99 &&
581 		    (options.protocol & SSH_PROTO_2) &&
582 		    !(options.protocol & SSH_PROTO_1_PREFERRED)) {
583 			enable_compat20();
584 			break;
585 		}
586 		if (!(options.protocol & SSH_PROTO_1)) {
587 			mismatch = 1;
588 			break;
589 		}
590 		if (remote_minor < 3) {
591 			fatal("Remote machine has too old SSH software version.");
592 		} else if (remote_minor == 3 || remote_minor == 4) {
593 			/* We speak 1.3, too. */
594 			enable_compat13();
595 			minor1 = 3;
596 			if (options.forward_agent) {
597 				logit("Agent forwarding disabled for protocol 1.3");
598 				options.forward_agent = 0;
599 			}
600 		}
601 		break;
602 	case 2:
603 		if (options.protocol & SSH_PROTO_2) {
604 			enable_compat20();
605 			break;
606 		}
607 		/* FALLTHROUGH */
608 	default:
609 		mismatch = 1;
610 		break;
611 	}
612 	if (mismatch)
613 		fatal("Protocol major versions differ: %d vs. %d",
614 		    (options.protocol & SSH_PROTO_2) ? PROTOCOL_MAJOR_2 : PROTOCOL_MAJOR_1,
615 		    remote_major);
616 	if (!client_banner_sent)
617 		send_client_banner(connection_out, minor1);
618 	chop(server_version_string);
619 }
620 
621 /* defaults to 'no' */
622 static int
623 confirm(const char *prompt)
624 {
625 	const char *msg, *again = "Please type 'yes' or 'no': ";
626 	char *p;
627 	int ret = -1;
628 
629 	if (options.batch_mode)
630 		return 0;
631 	for (msg = prompt;;msg = again) {
632 		p = read_passphrase(msg, RP_ECHO);
633 		if (p == NULL ||
634 		    (p[0] == '\0') || (p[0] == '\n') ||
635 		    strncasecmp(p, "no", 2) == 0)
636 			ret = 0;
637 		if (p && strncasecmp(p, "yes", 3) == 0)
638 			ret = 1;
639 		if (p)
640 			xfree(p);
641 		if (ret != -1)
642 			return ret;
643 	}
644 }
645 
646 static int
647 check_host_cert(const char *host, const Key *host_key)
648 {
649 	const char *reason;
650 
651 	if (key_cert_check_authority(host_key, 1, 0, host, &reason) != 0) {
652 		error("%s", reason);
653 		return 0;
654 	}
655 	if (buffer_len(&host_key->cert->critical) != 0) {
656 		error("Certificate for %s contains unsupported "
657 		    "critical options(s)", host);
658 		return 0;
659 	}
660 	return 1;
661 }
662 
663 static int
664 sockaddr_is_local(struct sockaddr *hostaddr)
665 {
666 	switch (hostaddr->sa_family) {
667 	case AF_INET:
668 		return (ntohl(((struct sockaddr_in *)hostaddr)->
669 		    sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
670 	case AF_INET6:
671 		return IN6_IS_ADDR_LOOPBACK(
672 		    &(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
673 	default:
674 		return 0;
675 	}
676 }
677 
678 /*
679  * Prepare the hostname and ip address strings that are used to lookup
680  * host keys in known_hosts files. These may have a port number appended.
681  */
682 void
683 get_hostfile_hostname_ipaddr(char *hostname, struct sockaddr *hostaddr,
684     u_short port, char **hostfile_hostname, char **hostfile_ipaddr)
685 {
686 	char ntop[NI_MAXHOST];
687 
688 	/*
689 	 * We don't have the remote ip-address for connections
690 	 * using a proxy command
691 	 */
692 	if (hostfile_ipaddr != NULL) {
693 		if (options.proxy_command == NULL) {
694 			if (getnameinfo(hostaddr, hostaddr->sa_len,
695 			    ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST) != 0)
696 			fatal("check_host_key: getnameinfo failed");
697 			*hostfile_ipaddr = put_host_port(ntop, port);
698 		} else {
699 			*hostfile_ipaddr = xstrdup("<no hostip for proxy "
700 			    "command>");
701 		}
702 	}
703 
704 	/*
705 	 * Allow the user to record the key under a different name or
706 	 * differentiate a non-standard port.  This is useful for ssh
707 	 * tunneling over forwarded connections or if you run multiple
708 	 * sshd's on different ports on the same machine.
709 	 */
710 	if (hostfile_hostname != NULL) {
711 		if (options.host_key_alias != NULL) {
712 			*hostfile_hostname = xstrdup(options.host_key_alias);
713 			debug("using hostkeyalias: %s", *hostfile_hostname);
714 		} else {
715 			*hostfile_hostname = put_host_port(hostname, port);
716 		}
717 	}
718 }
719 
720 /*
721  * check whether the supplied host key is valid, return -1 if the key
722  * is not valid. user_hostfile[0] will not be updated if 'readonly' is true.
723  */
724 #define RDRW	0
725 #define RDONLY	1
726 #define ROQUIET	2
727 static int
728 check_host_key(char *hostname, struct sockaddr *hostaddr, u_short port,
729     Key *host_key, int readonly,
730     char **user_hostfiles, u_int num_user_hostfiles,
731     char **system_hostfiles, u_int num_system_hostfiles)
732 {
733 	HostStatus host_status;
734 	HostStatus ip_status;
735 	Key *raw_key = NULL;
736 	char *ip = NULL, *host = NULL;
737 	char hostline[1000], *hostp, *fp, *ra;
738 	char msg[1024];
739 	const char *type;
740 	const struct hostkey_entry *host_found, *ip_found;
741 	int len, cancelled_forwarding = 0;
742 	int local = sockaddr_is_local(hostaddr);
743 	int r, want_cert = key_is_cert(host_key), host_ip_differ = 0;
744 	struct hostkeys *host_hostkeys, *ip_hostkeys;
745 	u_int i;
746 
747 	/*
748 	 * Force accepting of the host key for loopback/localhost. The
749 	 * problem is that if the home directory is NFS-mounted to multiple
750 	 * machines, localhost will refer to a different machine in each of
751 	 * them, and the user will get bogus HOST_CHANGED warnings.  This
752 	 * essentially disables host authentication for localhost; however,
753 	 * this is probably not a real problem.
754 	 */
755 	if (options.no_host_authentication_for_localhost == 1 && local &&
756 	    options.host_key_alias == NULL) {
757 		debug("Forcing accepting of host key for "
758 		    "loopback/localhost.");
759 		return 0;
760 	}
761 
762 	/*
763 	 * Prepare the hostname and address strings used for hostkey lookup.
764 	 * In some cases, these will have a port number appended.
765 	 */
766 	get_hostfile_hostname_ipaddr(hostname, hostaddr, port, &host, &ip);
767 
768 	/*
769 	 * Turn off check_host_ip if the connection is to localhost, via proxy
770 	 * command or if we don't have a hostname to compare with
771 	 */
772 	if (options.check_host_ip && (local ||
773 	    strcmp(hostname, ip) == 0 || options.proxy_command != NULL))
774 		options.check_host_ip = 0;
775 
776 	host_hostkeys = init_hostkeys();
777 	for (i = 0; i < num_user_hostfiles; i++)
778 		load_hostkeys(host_hostkeys, host, user_hostfiles[i]);
779 	for (i = 0; i < num_system_hostfiles; i++)
780 		load_hostkeys(host_hostkeys, host, system_hostfiles[i]);
781 
782 	ip_hostkeys = NULL;
783 	if (!want_cert && options.check_host_ip) {
784 		ip_hostkeys = init_hostkeys();
785 		for (i = 0; i < num_user_hostfiles; i++)
786 			load_hostkeys(ip_hostkeys, ip, user_hostfiles[i]);
787 		for (i = 0; i < num_system_hostfiles; i++)
788 			load_hostkeys(ip_hostkeys, ip, system_hostfiles[i]);
789 	}
790 
791  retry:
792 	/* Reload these as they may have changed on cert->key downgrade */
793 	want_cert = key_is_cert(host_key);
794 	type = key_type(host_key);
795 
796 	/*
797 	 * Check if the host key is present in the user's list of known
798 	 * hosts or in the systemwide list.
799 	 */
800 	host_status = check_key_in_hostkeys(host_hostkeys, host_key,
801 	    &host_found);
802 
803 	/*
804 	 * Also perform check for the ip address, skip the check if we are
805 	 * localhost, looking for a certificate, or the hostname was an ip
806 	 * address to begin with.
807 	 */
808 	if (!want_cert && ip_hostkeys != NULL) {
809 		ip_status = check_key_in_hostkeys(ip_hostkeys, host_key,
810 		    &ip_found);
811 		if (host_status == HOST_CHANGED &&
812 		    (ip_status != HOST_CHANGED ||
813 		    (ip_found != NULL &&
814 		    !key_equal(ip_found->key, host_found->key))))
815 			host_ip_differ = 1;
816 	} else
817 		ip_status = host_status;
818 
819 	switch (host_status) {
820 	case HOST_OK:
821 		/* The host is known and the key matches. */
822 		debug("Host '%.200s' is known and matches the %s host %s.",
823 		    host, type, want_cert ? "certificate" : "key");
824 		debug("Found %s in %s:%lu", want_cert ? "CA key" : "key",
825 		    host_found->file, host_found->line);
826 		if (want_cert && !check_host_cert(hostname, host_key))
827 			goto fail;
828 		if (options.check_host_ip && ip_status == HOST_NEW) {
829 			if (readonly || want_cert)
830 				logit("%s host key for IP address "
831 				    "'%.128s' not in list of known hosts.",
832 				    type, ip);
833 			else if (!add_host_to_hostfile(user_hostfiles[0], ip,
834 			    host_key, options.hash_known_hosts))
835 				logit("Failed to add the %s host key for IP "
836 				    "address '%.128s' to the list of known "
837 				    "hosts (%.30s).", type, ip,
838 				    user_hostfiles[0]);
839 			else
840 				logit("Warning: Permanently added the %s host "
841 				    "key for IP address '%.128s' to the list "
842 				    "of known hosts.", type, ip);
843 		} else if (options.visual_host_key) {
844 			fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX);
845 			ra = key_fingerprint(host_key, SSH_FP_MD5,
846 			    SSH_FP_RANDOMART);
847 			logit("Host key fingerprint is %s\n%s\n", fp, ra);
848 			xfree(ra);
849 			xfree(fp);
850 		}
851 		break;
852 	case HOST_NEW:
853 		if (options.host_key_alias == NULL && port != 0 &&
854 		    port != SSH_DEFAULT_PORT) {
855 			debug("checking without port identifier");
856 			if (check_host_key(hostname, hostaddr, 0, host_key,
857 			    ROQUIET, user_hostfiles, num_user_hostfiles,
858 			    system_hostfiles, num_system_hostfiles) == 0) {
859 				debug("found matching key w/out port");
860 				break;
861 			}
862 		}
863 		if (readonly || want_cert)
864 			goto fail;
865 		/* The host is new. */
866 		if (options.strict_host_key_checking == 1) {
867 			/*
868 			 * User has requested strict host key checking.  We
869 			 * will not add the host key automatically.  The only
870 			 * alternative left is to abort.
871 			 */
872 			error("No %s host key is known for %.200s and you "
873 			    "have requested strict checking.", type, host);
874 			goto fail;
875 		} else if (options.strict_host_key_checking == 2) {
876 			char msg1[1024], msg2[1024];
877 
878 			if (show_other_keys(host_hostkeys, host_key))
879 				snprintf(msg1, sizeof(msg1),
880 				    "\nbut keys of different type are already"
881 				    " known for this host.");
882 			else
883 				snprintf(msg1, sizeof(msg1), ".");
884 			/* The default */
885 			fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX);
886 			ra = key_fingerprint(host_key, SSH_FP_MD5,
887 			    SSH_FP_RANDOMART);
888 			msg2[0] = '\0';
889 			if (options.verify_host_key_dns) {
890 				if (matching_host_key_dns)
891 					snprintf(msg2, sizeof(msg2),
892 					    "Matching host key fingerprint"
893 					    " found in DNS.\n");
894 				else
895 					snprintf(msg2, sizeof(msg2),
896 					    "No matching host key fingerprint"
897 					    " found in DNS.\n");
898 			}
899 			snprintf(msg, sizeof(msg),
900 			    "The authenticity of host '%.200s (%s)' can't be "
901 			    "established%s\n"
902 			    "%s key fingerprint is %s.%s%s\n%s"
903 			    "Are you sure you want to continue connecting "
904 			    "(yes/no)? ",
905 			    host, ip, msg1, type, fp,
906 			    options.visual_host_key ? "\n" : "",
907 			    options.visual_host_key ? ra : "",
908 			    msg2);
909 			xfree(ra);
910 			xfree(fp);
911 			if (!confirm(msg))
912 				goto fail;
913 		}
914 		/*
915 		 * If not in strict mode, add the key automatically to the
916 		 * local known_hosts file.
917 		 */
918 		if (options.check_host_ip && ip_status == HOST_NEW) {
919 			snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
920 			hostp = hostline;
921 			if (options.hash_known_hosts) {
922 				/* Add hash of host and IP separately */
923 				r = add_host_to_hostfile(user_hostfiles[0],
924 				    host, host_key, options.hash_known_hosts) &&
925 				    add_host_to_hostfile(user_hostfiles[0], ip,
926 				    host_key, options.hash_known_hosts);
927 			} else {
928 				/* Add unhashed "host,ip" */
929 				r = add_host_to_hostfile(user_hostfiles[0],
930 				    hostline, host_key,
931 				    options.hash_known_hosts);
932 			}
933 		} else {
934 			r = add_host_to_hostfile(user_hostfiles[0], host,
935 			    host_key, options.hash_known_hosts);
936 			hostp = host;
937 		}
938 
939 		if (!r)
940 			logit("Failed to add the host to the list of known "
941 			    "hosts (%.500s).", user_hostfiles[0]);
942 		else
943 			logit("Warning: Permanently added '%.200s' (%s) to the "
944 			    "list of known hosts.", hostp, type);
945 		break;
946 	case HOST_REVOKED:
947 		error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
948 		error("@       WARNING: REVOKED HOST KEY DETECTED!               @");
949 		error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
950 		error("The %s host key for %s is marked as revoked.", type, host);
951 		error("This could mean that a stolen key is being used to");
952 		error("impersonate this host.");
953 
954 		/*
955 		 * If strict host key checking is in use, the user will have
956 		 * to edit the key manually and we can only abort.
957 		 */
958 		if (options.strict_host_key_checking) {
959 			error("%s host key for %.200s was revoked and you have "
960 			    "requested strict checking.", type, host);
961 			goto fail;
962 		}
963 		goto continue_unsafe;
964 
965 	case HOST_CHANGED:
966 		if (want_cert) {
967 			/*
968 			 * This is only a debug() since it is valid to have
969 			 * CAs with wildcard DNS matches that don't match
970 			 * all hosts that one might visit.
971 			 */
972 			debug("Host certificate authority does not "
973 			    "match %s in %s:%lu", CA_MARKER,
974 			    host_found->file, host_found->line);
975 			goto fail;
976 		}
977 		if (readonly == ROQUIET)
978 			goto fail;
979 		if (options.check_host_ip && host_ip_differ) {
980 			const char *key_msg;
981 			if (ip_status == HOST_NEW)
982 				key_msg = "is unknown";
983 			else if (ip_status == HOST_OK)
984 				key_msg = "is unchanged";
985 			else
986 				key_msg = "has a different value";
987 			error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
988 			error("@       WARNING: POSSIBLE DNS SPOOFING DETECTED!          @");
989 			error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
990 			error("The %s host key for %s has changed,", type, host);
991 			error("and the key for the corresponding IP address %s", ip);
992 			error("%s. This could either mean that", key_msg);
993 			error("DNS SPOOFING is happening or the IP address for the host");
994 			error("and its host key have changed at the same time.");
995 			if (ip_status != HOST_NEW)
996 				error("Offending key for IP in %s:%lu",
997 				    ip_found->file, ip_found->line);
998 		}
999 		/* The host key has changed. */
1000 		warn_changed_key(host_key);
1001 		error("Add correct host key in %.100s to get rid of this message.",
1002 		    user_hostfiles[0]);
1003 		error("Offending %s key in %s:%lu", key_type(host_found->key),
1004 		    host_found->file, host_found->line);
1005 
1006 		/*
1007 		 * If strict host key checking is in use, the user will have
1008 		 * to edit the key manually and we can only abort.
1009 		 */
1010 		if (options.strict_host_key_checking) {
1011 			error("%s host key for %.200s has changed and you have "
1012 			    "requested strict checking.", type, host);
1013 			goto fail;
1014 		}
1015 
1016  continue_unsafe:
1017 		/*
1018 		 * If strict host key checking has not been requested, allow
1019 		 * the connection but without MITM-able authentication or
1020 		 * forwarding.
1021 		 */
1022 		if (options.password_authentication) {
1023 			error("Password authentication is disabled to avoid "
1024 			    "man-in-the-middle attacks.");
1025 			options.password_authentication = 0;
1026 			cancelled_forwarding = 1;
1027 		}
1028 		if (options.kbd_interactive_authentication) {
1029 			error("Keyboard-interactive authentication is disabled"
1030 			    " to avoid man-in-the-middle attacks.");
1031 			options.kbd_interactive_authentication = 0;
1032 			options.challenge_response_authentication = 0;
1033 			cancelled_forwarding = 1;
1034 		}
1035 		if (options.challenge_response_authentication) {
1036 			error("Challenge/response authentication is disabled"
1037 			    " to avoid man-in-the-middle attacks.");
1038 			options.challenge_response_authentication = 0;
1039 			cancelled_forwarding = 1;
1040 		}
1041 		if (options.forward_agent) {
1042 			error("Agent forwarding is disabled to avoid "
1043 			    "man-in-the-middle attacks.");
1044 			options.forward_agent = 0;
1045 			cancelled_forwarding = 1;
1046 		}
1047 		if (options.forward_x11) {
1048 			error("X11 forwarding is disabled to avoid "
1049 			    "man-in-the-middle attacks.");
1050 			options.forward_x11 = 0;
1051 			cancelled_forwarding = 1;
1052 		}
1053 		if (options.num_local_forwards > 0 ||
1054 		    options.num_remote_forwards > 0) {
1055 			error("Port forwarding is disabled to avoid "
1056 			    "man-in-the-middle attacks.");
1057 			options.num_local_forwards =
1058 			    options.num_remote_forwards = 0;
1059 			cancelled_forwarding = 1;
1060 		}
1061 		if (options.tun_open != SSH_TUNMODE_NO) {
1062 			error("Tunnel forwarding is disabled to avoid "
1063 			    "man-in-the-middle attacks.");
1064 			options.tun_open = SSH_TUNMODE_NO;
1065 			cancelled_forwarding = 1;
1066 		}
1067 		if (options.exit_on_forward_failure && cancelled_forwarding)
1068 			fatal("Error: forwarding disabled due to host key "
1069 			    "check failure");
1070 
1071 		/*
1072 		 * XXX Should permit the user to change to use the new id.
1073 		 * This could be done by converting the host key to an
1074 		 * identifying sentence, tell that the host identifies itself
1075 		 * by that sentence, and ask the user if he/she wishes to
1076 		 * accept the authentication.
1077 		 */
1078 		break;
1079 	case HOST_FOUND:
1080 		fatal("internal error");
1081 		break;
1082 	}
1083 
1084 	if (options.check_host_ip && host_status != HOST_CHANGED &&
1085 	    ip_status == HOST_CHANGED) {
1086 		snprintf(msg, sizeof(msg),
1087 		    "Warning: the %s host key for '%.200s' "
1088 		    "differs from the key for the IP address '%.128s'"
1089 		    "\nOffending key for IP in %s:%lu",
1090 		    type, host, ip, ip_found->file, ip_found->line);
1091 		if (host_status == HOST_OK) {
1092 			len = strlen(msg);
1093 			snprintf(msg + len, sizeof(msg) - len,
1094 			    "\nMatching host key in %s:%lu",
1095 			    host_found->file, host_found->line);
1096 		}
1097 		if (options.strict_host_key_checking == 1) {
1098 			logit("%s", msg);
1099 			error("Exiting, you have requested strict checking.");
1100 			goto fail;
1101 		} else if (options.strict_host_key_checking == 2) {
1102 			strlcat(msg, "\nAre you sure you want "
1103 			    "to continue connecting (yes/no)? ", sizeof(msg));
1104 			if (!confirm(msg))
1105 				goto fail;
1106 		} else {
1107 			logit("%s", msg);
1108 		}
1109 	}
1110 
1111 	xfree(ip);
1112 	xfree(host);
1113 	if (host_hostkeys != NULL)
1114 		free_hostkeys(host_hostkeys);
1115 	if (ip_hostkeys != NULL)
1116 		free_hostkeys(ip_hostkeys);
1117 	return 0;
1118 
1119 fail:
1120 	if (want_cert && host_status != HOST_REVOKED) {
1121 		/*
1122 		 * No matching certificate. Downgrade cert to raw key and
1123 		 * search normally.
1124 		 */
1125 		debug("No matching CA found. Retry with plain key");
1126 		raw_key = key_from_private(host_key);
1127 		if (key_drop_cert(raw_key) != 0)
1128 			fatal("Couldn't drop certificate");
1129 		host_key = raw_key;
1130 		goto retry;
1131 	}
1132 	if (raw_key != NULL)
1133 		key_free(raw_key);
1134 	xfree(ip);
1135 	xfree(host);
1136 	if (host_hostkeys != NULL)
1137 		free_hostkeys(host_hostkeys);
1138 	if (ip_hostkeys != NULL)
1139 		free_hostkeys(ip_hostkeys);
1140 	return -1;
1141 }
1142 
1143 /* returns 0 if key verifies or -1 if key does NOT verify */
1144 int
1145 verify_host_key(char *host, struct sockaddr *hostaddr, Key *host_key)
1146 {
1147 	int flags = 0;
1148 	char *fp;
1149 
1150 	fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX);
1151 	debug("Server host key: %s %s", key_type(host_key), fp);
1152 	xfree(fp);
1153 
1154 	/* XXX certs are not yet supported for DNS */
1155 	if (!key_is_cert(host_key) && options.verify_host_key_dns &&
1156 	    verify_host_key_dns(host, hostaddr, host_key, &flags) == 0) {
1157 		if (flags & DNS_VERIFY_FOUND) {
1158 
1159 			if (options.verify_host_key_dns == 1 &&
1160 			    flags & DNS_VERIFY_MATCH &&
1161 			    flags & DNS_VERIFY_SECURE)
1162 				return 0;
1163 
1164 			if (flags & DNS_VERIFY_MATCH) {
1165 				matching_host_key_dns = 1;
1166 			} else {
1167 				warn_changed_key(host_key);
1168 				error("Update the SSHFP RR in DNS with the new "
1169 				    "host key to get rid of this message.");
1170 			}
1171 		}
1172 	}
1173 
1174 	return check_host_key(host, hostaddr, options.port, host_key, RDRW,
1175 	    options.user_hostfiles, options.num_user_hostfiles,
1176 	    options.system_hostfiles, options.num_system_hostfiles);
1177 }
1178 
1179 /*
1180  * Starts a dialog with the server, and authenticates the current user on the
1181  * server.  This does not need any extra privileges.  The basic connection
1182  * to the server must already have been established before this is called.
1183  * If login fails, this function prints an error and never returns.
1184  * This function does not require super-user privileges.
1185  */
1186 void
1187 ssh_login(Sensitive *sensitive, const char *orighost,
1188     struct sockaddr *hostaddr, u_short port, struct passwd *pw, int timeout_ms)
1189 {
1190 	char *host, *cp;
1191 	char *server_user, *local_user;
1192 
1193 	local_user = xstrdup(pw->pw_name);
1194 	server_user = options.user ? options.user : local_user;
1195 
1196 	/* Convert the user-supplied hostname into all lowercase. */
1197 	host = xstrdup(orighost);
1198 	for (cp = host; *cp; cp++)
1199 		if (isupper((unsigned char)*cp))
1200 			*cp = (char)tolower((unsigned char)*cp);
1201 
1202 	/* Exchange protocol version identification strings with the server. */
1203 	ssh_exchange_identification(timeout_ms);
1204 
1205 	/* Put the connection into non-blocking mode. */
1206 	packet_set_nonblocking();
1207 
1208 	/* key exchange */
1209 	/* authenticate user */
1210 	if (compat20) {
1211 		ssh_kex2(host, hostaddr, port);
1212 		ssh_userauth2(local_user, server_user, host, sensitive);
1213 	} else {
1214 		ssh_kex(host, hostaddr);
1215 		ssh_userauth1(local_user, server_user, host, sensitive);
1216 	}
1217 	xfree(local_user);
1218 }
1219 
1220 void
1221 ssh_put_password(char *password)
1222 {
1223 	int size;
1224 	char *padded;
1225 
1226 	if (datafellows & SSH_BUG_PASSWORDPAD) {
1227 		packet_put_cstring(password);
1228 		return;
1229 	}
1230 	size = roundup(strlen(password) + 1, 32);
1231 	padded = xcalloc(1, size);
1232 	strlcpy(padded, password, size);
1233 	packet_put_string(padded, size);
1234 	memset(padded, 0, size);
1235 	xfree(padded);
1236 }
1237 
1238 /* print all known host keys for a given host, but skip keys of given type */
1239 static int
1240 show_other_keys(struct hostkeys *hostkeys, Key *key)
1241 {
1242 	int type[] = { KEY_RSA1, KEY_RSA, KEY_DSA, KEY_ECDSA, -1};
1243 	int i, ret = 0;
1244 	char *fp, *ra;
1245 	const struct hostkey_entry *found;
1246 
1247 	for (i = 0; type[i] != -1; i++) {
1248 		if (type[i] == key->type)
1249 			continue;
1250 		if (!lookup_key_in_hostkeys_by_type(hostkeys, type[i], &found))
1251 			continue;
1252 		fp = key_fingerprint(found->key, SSH_FP_MD5, SSH_FP_HEX);
1253 		ra = key_fingerprint(found->key, SSH_FP_MD5, SSH_FP_RANDOMART);
1254 		logit("WARNING: %s key found for host %s\n"
1255 		    "in %s:%lu\n"
1256 		    "%s key fingerprint %s.",
1257 		    key_type(found->key),
1258 		    found->host, found->file, found->line,
1259 		    key_type(found->key), fp);
1260 		if (options.visual_host_key)
1261 			logit("%s", ra);
1262 		xfree(ra);
1263 		xfree(fp);
1264 		ret = 1;
1265 	}
1266 	return ret;
1267 }
1268 
1269 static void
1270 warn_changed_key(Key *host_key)
1271 {
1272 	char *fp;
1273 
1274 	fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX);
1275 
1276 	error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1277 	error("@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @");
1278 	error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1279 	error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1280 	error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1281 	error("It is also possible that a host key has just been changed.");
1282 	error("The fingerprint for the %s key sent by the remote host is\n%s.",
1283 	    key_type(host_key), fp);
1284 	error("Please contact your system administrator.");
1285 
1286 	xfree(fp);
1287 }
1288 
1289 /*
1290  * Execute a local command
1291  */
1292 int
1293 ssh_local_cmd(const char *args)
1294 {
1295 	const char *shell;
1296 	pid_t pid;
1297 	int status;
1298 	void (*osighand)(int);
1299 
1300 	if (!options.permit_local_command ||
1301 	    args == NULL || !*args)
1302 		return (1);
1303 
1304 	if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
1305 		shell = _PATH_BSHELL;
1306 
1307 	osighand = signal(SIGCHLD, SIG_DFL);
1308 	pid = fork();
1309 	if (pid == 0) {
1310 		signal(SIGPIPE, SIG_DFL);
1311 		debug3("Executing %s -c \"%s\"", shell, args);
1312 		execl(shell, shell, "-c", args, (char *)NULL);
1313 		error("Couldn't execute %s -c \"%s\": %s",
1314 		    shell, args, strerror(errno));
1315 		_exit(1);
1316 	} else if (pid == -1)
1317 		fatal("fork failed: %.100s", strerror(errno));
1318 	while (waitpid(pid, &status, 0) == -1)
1319 		if (errno != EINTR)
1320 			fatal("Couldn't wait for child: %s", strerror(errno));
1321 	signal(SIGCHLD, osighand);
1322 
1323 	if (!WIFEXITED(status))
1324 		return (1);
1325 
1326 	return (WEXITSTATUS(status));
1327 }
1328