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