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