1 /* $OpenBSD: sshconnect.c,v 1.297 2018/02/23 15:58:38 markus Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
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".
18 #include <sys/types.h>
21 #include <sys/socket.h>
22 #ifdef HAVE_SYS_TIME_H
23 # include <sys/time.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
60 #include "sshconnect.h"
67 #include "monitor_fdpass.h"
74 char *client_version_string = NULL;
75 char *server_version_string = NULL;
76 struct sshkey *previous_host_key = NULL;
78 static int matching_host_key_dns = 0;
80 static pid_t proxy_command_pid = 0;
83 extern Options options;
84 extern char *__progname;
85 extern uid_t original_real_uid;
86 extern uid_t original_effective_uid;
88 static int show_other_keys(struct hostkeys *, struct sshkey *);
89 static void warn_changed_key(struct sshkey *);
91 /* Expand a proxy command */
93 expand_proxy_command(const char *proxy_command, const char *user,
94 const char *host, int port)
96 char *tmp, *ret, strport[NI_MAXSERV];
98 snprintf(strport, sizeof strport, "%d", port);
99 xasprintf(&tmp, "exec %s", proxy_command);
100 ret = percent_expand(tmp, "h", host, "p", strport,
101 "r", options.user, (char *)NULL);
107 * Connect to the given ssh server using a proxy command that passes a
108 * a connected fd back to us.
111 ssh_proxy_fdpass_connect(struct ssh *ssh, const char *host, u_short port,
112 const char *proxy_command)
114 char *command_string;
119 if ((shell = getenv("SHELL")) == NULL)
120 shell = _PATH_BSHELL;
122 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sp) < 0)
123 fatal("Could not create socketpair to communicate with "
124 "proxy dialer: %.100s", strerror(errno));
126 command_string = expand_proxy_command(proxy_command, options.user,
128 debug("Executing proxy dialer command: %.500s", command_string);
130 /* Fork and execute the proxy command. */
131 if ((pid = fork()) == 0) {
134 /* Child. Permanently give up superuser privileges. */
135 permanently_drop_suid(original_real_uid);
138 /* Redirect stdin and stdout. */
140 if (dup2(sp[0], 0) < 0)
141 perror("dup2 stdin");
144 if (dup2(sp[0], 1) < 0)
145 perror("dup2 stdout");
151 * Stderr is left as it is so that error messages get
152 * printed on the user's terminal.
156 argv[2] = command_string;
160 * Execute the proxy command.
161 * Note that we gave up any extra privileges above.
163 execv(argv[0], argv);
169 fatal("fork failed: %.100s", strerror(errno));
171 free(command_string);
173 if ((sock = mm_receive_fd(sp[1])) == -1)
174 fatal("proxy dialer did not pass back a connection");
177 while (waitpid(pid, NULL, 0) == -1)
179 fatal("Couldn't wait for child: %s", strerror(errno));
181 /* Set the connection file descriptors. */
182 if (ssh_packet_set_connection(ssh, sock, sock) == NULL)
183 return -1; /* ssh_packet_set_connection logs error */
189 * Connect to the given ssh server using a proxy command.
192 ssh_proxy_connect(struct ssh *ssh, const char *host, u_short port,
193 const char *proxy_command)
195 char *command_string;
200 if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
201 shell = _PATH_BSHELL;
203 /* Create pipes for communicating with the proxy. */
204 if (pipe(pin) < 0 || pipe(pout) < 0)
205 fatal("Could not create pipes to communicate with the proxy: %.100s",
208 command_string = expand_proxy_command(proxy_command, options.user,
210 debug("Executing proxy command: %.500s", command_string);
212 /* Fork and execute the proxy command. */
213 if ((pid = fork()) == 0) {
216 /* Child. Permanently give up superuser privileges. */
217 permanently_drop_suid(original_real_uid);
219 /* Redirect stdin and stdout. */
222 if (dup2(pin[0], 0) < 0)
223 perror("dup2 stdin");
227 if (dup2(pout[1], 1) < 0)
228 perror("dup2 stdout");
229 /* Cannot be 1 because pin allocated two descriptors. */
232 /* Stderr is left as it is so that error messages get
233 printed on the user's terminal. */
236 argv[2] = command_string;
239 /* Execute the proxy command. Note that we gave up any
240 extra privileges above. */
241 signal(SIGPIPE, SIG_DFL);
242 execv(argv[0], argv);
248 fatal("fork failed: %.100s", strerror(errno));
250 proxy_command_pid = pid; /* save pid to clean up later */
252 /* Close child side of the descriptors. */
256 /* Free the command name. */
257 free(command_string);
259 /* Set the connection file descriptors. */
260 if (ssh_packet_set_connection(ssh, pout[0], pin[1]) == NULL)
261 return -1; /* ssh_packet_set_connection logs error */
267 ssh_kill_proxy_command(void)
270 * Send SIGHUP to proxy command if used. We don't wait() in
271 * case it hangs and instead rely on init to reap the child
273 if (proxy_command_pid > 1)
274 kill(proxy_command_pid, SIGHUP);
277 #ifdef HAVE_IFADDRS_H
279 * Search a interface address list (returned from getifaddrs(3)) for an
280 * address that matches the desired address family on the specifed interface.
281 * Returns 0 and fills in *resultp and *rlenp on success. Returns -1 on failure.
284 check_ifaddrs(const char *ifname, int af, const struct ifaddrs *ifaddrs,
285 struct sockaddr_storage *resultp, socklen_t *rlenp)
287 struct sockaddr_in6 *sa6;
288 struct sockaddr_in *sa;
289 struct in6_addr *v6addr;
290 const struct ifaddrs *ifa;
294 * Prefer addresses that are not loopback or linklocal, but use them
295 * if nothing else matches.
297 for (allow_local = 0; allow_local < 2; allow_local++) {
298 for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
299 if (ifa->ifa_addr == NULL || ifa->ifa_name == NULL ||
300 (ifa->ifa_flags & IFF_UP) == 0 ||
301 ifa->ifa_addr->sa_family != af ||
302 strcmp(ifa->ifa_name, options.bind_interface) != 0)
304 switch (ifa->ifa_addr->sa_family) {
306 sa = (struct sockaddr_in *)ifa->ifa_addr;
307 if (!allow_local && sa->sin_addr.s_addr ==
308 htonl(INADDR_LOOPBACK))
310 if (*rlenp < sizeof(struct sockaddr_in)) {
311 error("%s: v4 addr doesn't fit",
315 *rlenp = sizeof(struct sockaddr_in);
316 memcpy(resultp, sa, *rlenp);
319 sa6 = (struct sockaddr_in6 *)ifa->ifa_addr;
320 v6addr = &sa6->sin6_addr;
322 (IN6_IS_ADDR_LINKLOCAL(v6addr) ||
323 IN6_IS_ADDR_LOOPBACK(v6addr)))
325 if (*rlenp < sizeof(struct sockaddr_in6)) {
326 error("%s: v6 addr doesn't fit",
330 *rlenp = sizeof(struct sockaddr_in6);
331 memcpy(resultp, sa6, *rlenp);
341 * Creates a (possibly privileged) socket for use as the ssh connection.
344 ssh_create_socket(int privileged, struct addrinfo *ai)
347 struct sockaddr_storage bindaddr;
348 socklen_t bindaddrlen = 0;
349 struct addrinfo hints, *res = NULL;
350 #ifdef HAVE_IFADDRS_H
351 struct ifaddrs *ifaddrs = NULL;
353 char ntop[NI_MAXHOST];
355 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
357 error("socket: %s", strerror(errno));
360 fcntl(sock, F_SETFD, FD_CLOEXEC);
362 /* Bind the socket to an alternative local IP address */
363 if (options.bind_address == NULL && options.bind_interface == NULL &&
367 if (options.bind_address != NULL) {
368 memset(&hints, 0, sizeof(hints));
369 hints.ai_family = ai->ai_family;
370 hints.ai_socktype = ai->ai_socktype;
371 hints.ai_protocol = ai->ai_protocol;
372 hints.ai_flags = AI_PASSIVE;
373 if ((r = getaddrinfo(options.bind_address, NULL,
374 &hints, &res)) != 0) {
375 error("getaddrinfo: %s: %s", options.bind_address,
376 ssh_gai_strerror(r));
380 error("getaddrinfo: no addrs");
383 if (res->ai_addrlen > sizeof(bindaddr)) {
384 error("%s: addr doesn't fit", __func__);
387 memcpy(&bindaddr, res->ai_addr, res->ai_addrlen);
388 bindaddrlen = res->ai_addrlen;
389 } else if (options.bind_interface != NULL) {
390 #ifdef HAVE_IFADDRS_H
391 if ((r = getifaddrs(&ifaddrs)) != 0) {
392 error("getifaddrs: %s: %s", options.bind_interface,
396 bindaddrlen = sizeof(bindaddr);
397 if (check_ifaddrs(options.bind_interface, ai->ai_family,
398 ifaddrs, &bindaddr, &bindaddrlen) != 0) {
399 logit("getifaddrs: %s: no suitable addresses",
400 options.bind_interface);
404 error("BindInterface not supported on this platform.");
407 if ((r = getnameinfo((struct sockaddr *)&bindaddr, bindaddrlen,
408 ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST)) != 0) {
409 error("%s: getnameinfo failed: %s", __func__,
410 ssh_gai_strerror(r));
414 * If we are running as root and want to connect to a privileged
415 * port, bind our own socket to a privileged port.
419 r = bindresvport_sa(sock,
420 bindaddrlen == 0 ? NULL : (struct sockaddr *)&bindaddr);
424 error("bindresvport_sa %s: %s", ntop,
428 } else if (bind(sock, (struct sockaddr *)&bindaddr, bindaddrlen) != 0) {
429 error("bind %s: %s", ntop, strerror(errno));
432 debug("%s: bound to %s", __func__, ntop);
441 #ifdef HAVE_IFADDRS_H
443 freeifaddrs(ifaddrs);
449 * Wait up to *timeoutp milliseconds for fd to be readable. Updates
450 * *timeoutp with time remaining.
451 * Returns 0 if fd ready or -1 on timeout or error (see errno).
454 waitrfd(int fd, int *timeoutp)
457 struct timeval t_start;
460 monotime_tv(&t_start);
463 for (; *timeoutp >= 0;) {
464 r = poll(&pfd, 1, *timeoutp);
466 ms_subtract_diff(&t_start, timeoutp);
470 else if (r == -1 && errno != EAGAIN)
481 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
482 socklen_t addrlen, int *timeoutp)
485 socklen_t optlen = sizeof(optval);
487 /* No timeout: just do a blocking connect() */
489 return connect(sockfd, serv_addr, addrlen);
491 set_nonblock(sockfd);
492 if (connect(sockfd, serv_addr, addrlen) == 0) {
493 /* Succeeded already? */
494 unset_nonblock(sockfd);
496 } else if (errno != EINPROGRESS)
499 if (waitrfd(sockfd, timeoutp) == -1)
502 /* Completed or failed */
503 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
504 debug("getsockopt: %s", strerror(errno));
511 unset_nonblock(sockfd);
516 * Opens a TCP/IP connection to the remote server on the given host.
517 * The address of the remote host will be returned in hostaddr.
518 * If port is 0, the default port will be used. If needpriv is true,
519 * a privileged port will be allocated to make the connection.
520 * This requires super-user privileges if needpriv is true.
521 * Connection_attempts specifies the maximum number of tries (one per
522 * second). If proxy_command is non-NULL, it specifies the command (with %h
523 * and %p substituted for host and port, respectively) to use to contact
527 ssh_connect_direct(struct ssh *ssh, const char *host, struct addrinfo *aitop,
528 struct sockaddr_storage *hostaddr, u_short port, int family,
529 int connection_attempts, int *timeout_ms, int want_keepalive, int needpriv)
532 int oerrno, sock = -1, attempt;
533 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
536 debug2("%s: needpriv %d", __func__, needpriv);
537 memset(ntop, 0, sizeof(ntop));
538 memset(strport, 0, sizeof(strport));
540 for (attempt = 0; attempt < connection_attempts; attempt++) {
542 /* Sleep a moment before retrying. */
544 debug("Trying again...");
547 * Loop through addresses for this host, and try each one in
548 * sequence until the connection succeeds.
550 for (ai = aitop; ai; ai = ai->ai_next) {
551 if (ai->ai_family != AF_INET &&
552 ai->ai_family != AF_INET6) {
553 errno = EAFNOSUPPORT;
556 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
557 ntop, sizeof(ntop), strport, sizeof(strport),
558 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
560 error("%s: getnameinfo failed", __func__);
564 debug("Connecting to %.200s [%.100s] port %s.",
565 host, ntop, strport);
567 /* Create a socket for connecting. */
568 sock = ssh_create_socket(needpriv, ai);
570 /* Any error is already output */
575 if (timeout_connect(sock, ai->ai_addr, ai->ai_addrlen,
577 /* Successful connection. */
578 memcpy(hostaddr, ai->ai_addr, ai->ai_addrlen);
582 debug("connect to address %s port %s: %s",
583 ntop, strport, strerror(errno));
590 break; /* Successful connection. */
593 /* Return failure if we didn't get a successful connection. */
595 error("ssh: connect to host %s port %s: %s",
596 host, strport, errno == 0 ? "failure" : strerror(errno));
600 debug("Connection established.");
602 /* Set SO_KEEPALIVE if requested. */
603 if (want_keepalive &&
604 setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
606 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
608 /* Set the connection. */
609 if (ssh_packet_set_connection(ssh, sock, sock) == NULL)
610 return -1; /* ssh_packet_set_connection logs error */
616 ssh_connect(struct ssh *ssh, const char *host, struct addrinfo *addrs,
617 struct sockaddr_storage *hostaddr, u_short port, int family,
618 int connection_attempts, int *timeout_ms, int want_keepalive, int needpriv)
620 if (options.proxy_command == NULL) {
621 return ssh_connect_direct(ssh, host, addrs, hostaddr, port,
622 family, connection_attempts, timeout_ms, want_keepalive,
624 } else if (strcmp(options.proxy_command, "-") == 0) {
625 if ((ssh_packet_set_connection(ssh,
626 STDIN_FILENO, STDOUT_FILENO)) == NULL)
627 return -1; /* ssh_packet_set_connection logs error */
629 } else if (options.proxy_use_fdpass) {
630 return ssh_proxy_fdpass_connect(ssh, host, port,
631 options.proxy_command);
633 return ssh_proxy_connect(ssh, host, port, options.proxy_command);
637 send_client_banner(int connection_out, int minor1)
639 /* Send our own protocol version identification. */
640 xasprintf(&client_version_string, "SSH-%d.%d-%.100s\r\n",
641 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION);
642 if (atomicio(vwrite, connection_out, client_version_string,
643 strlen(client_version_string)) != strlen(client_version_string))
644 fatal("write: %.100s", strerror(errno));
645 chop(client_version_string);
646 debug("Local version string %.100s", client_version_string);
650 * Waits for the server identification string, and sends our own
651 * identification string.
654 ssh_exchange_identification(int timeout_ms)
656 char buf[256], remote_version[256]; /* must be same size! */
657 int remote_major, remote_minor, mismatch;
658 int connection_in = packet_get_connection_in();
659 int connection_out = packet_get_connection_out();
664 send_client_banner(connection_out, 0);
666 /* Read other side's version identification. */
668 for (i = 0; i < sizeof(buf) - 1; i++) {
669 if (timeout_ms > 0) {
670 rc = waitrfd(connection_in, &timeout_ms);
671 if (rc == -1 && errno == ETIMEDOUT) {
672 fatal("Connection timed out during "
674 } else if (rc == -1) {
676 __func__, strerror(errno));
680 len = atomicio(read, connection_in, &buf[i], 1);
681 if (len != 1 && errno == EPIPE)
682 fatal("ssh_exchange_identification: "
683 "Connection closed by remote host");
685 fatal("ssh_exchange_identification: "
686 "read: %.100s", strerror(errno));
687 if (buf[i] == '\r') {
690 continue; /**XXX wait for \n */
692 if (buf[i] == '\n') {
697 fatal("ssh_exchange_identification: "
698 "No banner received");
700 buf[sizeof(buf) - 1] = 0;
701 if (strncmp(buf, "SSH-", 4) == 0)
703 debug("ssh_exchange_identification: %s", buf);
705 server_version_string = xstrdup(buf);
708 * Check that the versions match. In future this might accept
709 * several versions and set appropriate flags to handle them.
711 if (sscanf(server_version_string, "SSH-%d.%d-%[^\n]\n",
712 &remote_major, &remote_minor, remote_version) != 3)
713 fatal("Bad remote protocol version identification: '%.100s'", buf);
714 debug("Remote protocol version %d.%d, remote software version %.100s",
715 remote_major, remote_minor, remote_version);
717 active_state->compat = compat_datafellows(remote_version);
720 switch (remote_major) {
724 if (remote_minor != 99)
732 fatal("Protocol major versions differ: %d vs. %d",
733 PROTOCOL_MAJOR_2, remote_major);
734 if ((datafellows & SSH_BUG_RSASIGMD5) != 0)
735 logit("Server version \"%.100s\" uses unsafe RSA signature "
736 "scheme; disabling use of RSA keys", remote_version);
737 chop(server_version_string);
740 /* defaults to 'no' */
742 confirm(const char *prompt)
744 const char *msg, *again = "Please type 'yes' or 'no': ";
748 if (options.batch_mode)
750 for (msg = prompt;;msg = again) {
751 p = read_passphrase(msg, RP_ECHO);
754 p[strcspn(p, "\n")] = '\0';
755 if (p[0] == '\0' || strcasecmp(p, "no") == 0)
757 else if (strcasecmp(p, "yes") == 0)
766 check_host_cert(const char *host, const struct sshkey *host_key)
770 if (key_cert_check_authority(host_key, 1, 0, host, &reason) != 0) {
774 if (buffer_len(host_key->cert->critical) != 0) {
775 error("Certificate for %s contains unsupported "
776 "critical options(s)", host);
783 sockaddr_is_local(struct sockaddr *hostaddr)
785 switch (hostaddr->sa_family) {
787 return (ntohl(((struct sockaddr_in *)hostaddr)->
788 sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
790 return IN6_IS_ADDR_LOOPBACK(
791 &(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
798 * Prepare the hostname and ip address strings that are used to lookup
799 * host keys in known_hosts files. These may have a port number appended.
802 get_hostfile_hostname_ipaddr(char *hostname, struct sockaddr *hostaddr,
803 u_short port, char **hostfile_hostname, char **hostfile_ipaddr)
805 char ntop[NI_MAXHOST];
808 switch (hostaddr == NULL ? -1 : hostaddr->sa_family) {
813 addrlen = sizeof(struct sockaddr_in);
816 addrlen = sizeof(struct sockaddr_in6);
819 addrlen = sizeof(struct sockaddr);
824 * We don't have the remote ip-address for connections
825 * using a proxy command
827 if (hostfile_ipaddr != NULL) {
828 if (options.proxy_command == NULL) {
829 if (getnameinfo(hostaddr, addrlen,
830 ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST) != 0)
831 fatal("%s: getnameinfo failed", __func__);
832 *hostfile_ipaddr = put_host_port(ntop, port);
834 *hostfile_ipaddr = xstrdup("<no hostip for proxy "
840 * Allow the user to record the key under a different name or
841 * differentiate a non-standard port. This is useful for ssh
842 * tunneling over forwarded connections or if you run multiple
843 * sshd's on different ports on the same machine.
845 if (hostfile_hostname != NULL) {
846 if (options.host_key_alias != NULL) {
847 *hostfile_hostname = xstrdup(options.host_key_alias);
848 debug("using hostkeyalias: %s", *hostfile_hostname);
850 *hostfile_hostname = put_host_port(hostname, port);
856 * check whether the supplied host key is valid, return -1 if the key
857 * is not valid. user_hostfile[0] will not be updated if 'readonly' is true.
863 check_host_key(char *hostname, struct sockaddr *hostaddr, u_short port,
864 struct sshkey *host_key, int readonly,
865 char **user_hostfiles, u_int num_user_hostfiles,
866 char **system_hostfiles, u_int num_system_hostfiles)
868 HostStatus host_status;
869 HostStatus ip_status;
870 struct sshkey *raw_key = NULL;
871 char *ip = NULL, *host = NULL;
872 char hostline[1000], *hostp, *fp, *ra;
875 const struct hostkey_entry *host_found, *ip_found;
876 int len, cancelled_forwarding = 0;
877 int local = sockaddr_is_local(hostaddr);
878 int r, want_cert = sshkey_is_cert(host_key), host_ip_differ = 0;
879 int hostkey_trusted = 0; /* Known or explicitly accepted by user */
880 struct hostkeys *host_hostkeys, *ip_hostkeys;
884 * Force accepting of the host key for loopback/localhost. The
885 * problem is that if the home directory is NFS-mounted to multiple
886 * machines, localhost will refer to a different machine in each of
887 * them, and the user will get bogus HOST_CHANGED warnings. This
888 * essentially disables host authentication for localhost; however,
889 * this is probably not a real problem.
891 if (options.no_host_authentication_for_localhost == 1 && local &&
892 options.host_key_alias == NULL) {
893 debug("Forcing accepting of host key for "
894 "loopback/localhost.");
899 * Prepare the hostname and address strings used for hostkey lookup.
900 * In some cases, these will have a port number appended.
902 get_hostfile_hostname_ipaddr(hostname, hostaddr, port, &host, &ip);
905 * Turn off check_host_ip if the connection is to localhost, via proxy
906 * command or if we don't have a hostname to compare with
908 if (options.check_host_ip && (local ||
909 strcmp(hostname, ip) == 0 || options.proxy_command != NULL))
910 options.check_host_ip = 0;
912 host_hostkeys = init_hostkeys();
913 for (i = 0; i < num_user_hostfiles; i++)
914 load_hostkeys(host_hostkeys, host, user_hostfiles[i]);
915 for (i = 0; i < num_system_hostfiles; i++)
916 load_hostkeys(host_hostkeys, host, system_hostfiles[i]);
919 if (!want_cert && options.check_host_ip) {
920 ip_hostkeys = init_hostkeys();
921 for (i = 0; i < num_user_hostfiles; i++)
922 load_hostkeys(ip_hostkeys, ip, user_hostfiles[i]);
923 for (i = 0; i < num_system_hostfiles; i++)
924 load_hostkeys(ip_hostkeys, ip, system_hostfiles[i]);
928 /* Reload these as they may have changed on cert->key downgrade */
929 want_cert = sshkey_is_cert(host_key);
930 type = sshkey_type(host_key);
933 * Check if the host key is present in the user's list of known
934 * hosts or in the systemwide list.
936 host_status = check_key_in_hostkeys(host_hostkeys, host_key,
940 * Also perform check for the ip address, skip the check if we are
941 * localhost, looking for a certificate, or the hostname was an ip
942 * address to begin with.
944 if (!want_cert && ip_hostkeys != NULL) {
945 ip_status = check_key_in_hostkeys(ip_hostkeys, host_key,
947 if (host_status == HOST_CHANGED &&
948 (ip_status != HOST_CHANGED ||
950 !sshkey_equal(ip_found->key, host_found->key))))
953 ip_status = host_status;
955 switch (host_status) {
957 /* The host is known and the key matches. */
958 debug("Host '%.200s' is known and matches the %s host %s.",
959 host, type, want_cert ? "certificate" : "key");
960 debug("Found %s in %s:%lu", want_cert ? "CA key" : "key",
961 host_found->file, host_found->line);
963 !check_host_cert(options.host_key_alias == NULL ?
964 hostname : options.host_key_alias, host_key))
966 if (options.check_host_ip && ip_status == HOST_NEW) {
967 if (readonly || want_cert)
968 logit("%s host key for IP address "
969 "'%.128s' not in list of known hosts.",
971 else if (!add_host_to_hostfile(user_hostfiles[0], ip,
972 host_key, options.hash_known_hosts))
973 logit("Failed to add the %s host key for IP "
974 "address '%.128s' to the list of known "
975 "hosts (%.500s).", type, ip,
978 logit("Warning: Permanently added the %s host "
979 "key for IP address '%.128s' to the list "
980 "of known hosts.", type, ip);
981 } else if (options.visual_host_key) {
982 fp = sshkey_fingerprint(host_key,
983 options.fingerprint_hash, SSH_FP_DEFAULT);
984 ra = sshkey_fingerprint(host_key,
985 options.fingerprint_hash, SSH_FP_RANDOMART);
986 if (fp == NULL || ra == NULL)
987 fatal("%s: sshkey_fingerprint fail", __func__);
988 logit("Host key fingerprint is %s\n%s", fp, ra);
995 if (options.host_key_alias == NULL && port != 0 &&
996 port != SSH_DEFAULT_PORT) {
997 debug("checking without port identifier");
998 if (check_host_key(hostname, hostaddr, 0, host_key,
999 ROQUIET, user_hostfiles, num_user_hostfiles,
1000 system_hostfiles, num_system_hostfiles) == 0) {
1001 debug("found matching key w/out port");
1005 if (readonly || want_cert)
1007 /* The host is new. */
1008 if (options.strict_host_key_checking ==
1009 SSH_STRICT_HOSTKEY_YES) {
1011 * User has requested strict host key checking. We
1012 * will not add the host key automatically. The only
1013 * alternative left is to abort.
1015 error("No %s host key is known for %.200s and you "
1016 "have requested strict checking.", type, host);
1018 } else if (options.strict_host_key_checking ==
1019 SSH_STRICT_HOSTKEY_ASK) {
1020 char msg1[1024], msg2[1024];
1022 if (show_other_keys(host_hostkeys, host_key))
1023 snprintf(msg1, sizeof(msg1),
1024 "\nbut keys of different type are already"
1025 " known for this host.");
1027 snprintf(msg1, sizeof(msg1), ".");
1029 fp = sshkey_fingerprint(host_key,
1030 options.fingerprint_hash, SSH_FP_DEFAULT);
1031 ra = sshkey_fingerprint(host_key,
1032 options.fingerprint_hash, SSH_FP_RANDOMART);
1033 if (fp == NULL || ra == NULL)
1034 fatal("%s: sshkey_fingerprint fail", __func__);
1036 if (options.verify_host_key_dns) {
1037 if (matching_host_key_dns)
1038 snprintf(msg2, sizeof(msg2),
1039 "Matching host key fingerprint"
1040 " found in DNS.\n");
1042 snprintf(msg2, sizeof(msg2),
1043 "No matching host key fingerprint"
1044 " found in DNS.\n");
1046 snprintf(msg, sizeof(msg),
1047 "The authenticity of host '%.200s (%s)' can't be "
1049 "%s key fingerprint is %s.%s%s\n%s"
1050 "Are you sure you want to continue connecting "
1052 host, ip, msg1, type, fp,
1053 options.visual_host_key ? "\n" : "",
1054 options.visual_host_key ? ra : "",
1060 hostkey_trusted = 1; /* user explicitly confirmed */
1063 * If in "new" or "off" strict mode, add the key automatically
1064 * to the local known_hosts file.
1066 if (options.check_host_ip && ip_status == HOST_NEW) {
1067 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1069 if (options.hash_known_hosts) {
1070 /* Add hash of host and IP separately */
1071 r = add_host_to_hostfile(user_hostfiles[0],
1072 host, host_key, options.hash_known_hosts) &&
1073 add_host_to_hostfile(user_hostfiles[0], ip,
1074 host_key, options.hash_known_hosts);
1076 /* Add unhashed "host,ip" */
1077 r = add_host_to_hostfile(user_hostfiles[0],
1079 options.hash_known_hosts);
1082 r = add_host_to_hostfile(user_hostfiles[0], host,
1083 host_key, options.hash_known_hosts);
1088 logit("Failed to add the host to the list of known "
1089 "hosts (%.500s).", user_hostfiles[0]);
1091 logit("Warning: Permanently added '%.200s' (%s) to the "
1092 "list of known hosts.", hostp, type);
1095 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1096 error("@ WARNING: REVOKED HOST KEY DETECTED! @");
1097 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1098 error("The %s host key for %s is marked as revoked.", type, host);
1099 error("This could mean that a stolen key is being used to");
1100 error("impersonate this host.");
1103 * If strict host key checking is in use, the user will have
1104 * to edit the key manually and we can only abort.
1106 if (options.strict_host_key_checking !=
1107 SSH_STRICT_HOSTKEY_OFF) {
1108 error("%s host key for %.200s was revoked and you have "
1109 "requested strict checking.", type, host);
1112 goto continue_unsafe;
1117 * This is only a debug() since it is valid to have
1118 * CAs with wildcard DNS matches that don't match
1119 * all hosts that one might visit.
1121 debug("Host certificate authority does not "
1122 "match %s in %s:%lu", CA_MARKER,
1123 host_found->file, host_found->line);
1126 if (readonly == ROQUIET)
1128 if (options.check_host_ip && host_ip_differ) {
1130 if (ip_status == HOST_NEW)
1131 key_msg = "is unknown";
1132 else if (ip_status == HOST_OK)
1133 key_msg = "is unchanged";
1135 key_msg = "has a different value";
1136 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1137 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1138 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1139 error("The %s host key for %s has changed,", type, host);
1140 error("and the key for the corresponding IP address %s", ip);
1141 error("%s. This could either mean that", key_msg);
1142 error("DNS SPOOFING is happening or the IP address for the host");
1143 error("and its host key have changed at the same time.");
1144 if (ip_status != HOST_NEW)
1145 error("Offending key for IP in %s:%lu",
1146 ip_found->file, ip_found->line);
1148 /* The host key has changed. */
1149 warn_changed_key(host_key);
1150 error("Add correct host key in %.100s to get rid of this message.",
1152 error("Offending %s key in %s:%lu",
1153 sshkey_type(host_found->key),
1154 host_found->file, host_found->line);
1157 * If strict host key checking is in use, the user will have
1158 * to edit the key manually and we can only abort.
1160 if (options.strict_host_key_checking !=
1161 SSH_STRICT_HOSTKEY_OFF) {
1162 error("%s host key for %.200s has changed and you have "
1163 "requested strict checking.", type, host);
1169 * If strict host key checking has not been requested, allow
1170 * the connection but without MITM-able authentication or
1173 if (options.password_authentication) {
1174 error("Password authentication is disabled to avoid "
1175 "man-in-the-middle attacks.");
1176 options.password_authentication = 0;
1177 cancelled_forwarding = 1;
1179 if (options.kbd_interactive_authentication) {
1180 error("Keyboard-interactive authentication is disabled"
1181 " to avoid man-in-the-middle attacks.");
1182 options.kbd_interactive_authentication = 0;
1183 options.challenge_response_authentication = 0;
1184 cancelled_forwarding = 1;
1186 if (options.challenge_response_authentication) {
1187 error("Challenge/response authentication is disabled"
1188 " to avoid man-in-the-middle attacks.");
1189 options.challenge_response_authentication = 0;
1190 cancelled_forwarding = 1;
1192 if (options.forward_agent) {
1193 error("Agent forwarding is disabled to avoid "
1194 "man-in-the-middle attacks.");
1195 options.forward_agent = 0;
1196 cancelled_forwarding = 1;
1198 if (options.forward_x11) {
1199 error("X11 forwarding is disabled to avoid "
1200 "man-in-the-middle attacks.");
1201 options.forward_x11 = 0;
1202 cancelled_forwarding = 1;
1204 if (options.num_local_forwards > 0 ||
1205 options.num_remote_forwards > 0) {
1206 error("Port forwarding is disabled to avoid "
1207 "man-in-the-middle attacks.");
1208 options.num_local_forwards =
1209 options.num_remote_forwards = 0;
1210 cancelled_forwarding = 1;
1212 if (options.tun_open != SSH_TUNMODE_NO) {
1213 error("Tunnel forwarding is disabled to avoid "
1214 "man-in-the-middle attacks.");
1215 options.tun_open = SSH_TUNMODE_NO;
1216 cancelled_forwarding = 1;
1218 if (options.exit_on_forward_failure && cancelled_forwarding)
1219 fatal("Error: forwarding disabled due to host key "
1223 * XXX Should permit the user to change to use the new id.
1224 * This could be done by converting the host key to an
1225 * identifying sentence, tell that the host identifies itself
1226 * by that sentence, and ask the user if he/she wishes to
1227 * accept the authentication.
1231 fatal("internal error");
1235 if (options.check_host_ip && host_status != HOST_CHANGED &&
1236 ip_status == HOST_CHANGED) {
1237 snprintf(msg, sizeof(msg),
1238 "Warning: the %s host key for '%.200s' "
1239 "differs from the key for the IP address '%.128s'"
1240 "\nOffending key for IP in %s:%lu",
1241 type, host, ip, ip_found->file, ip_found->line);
1242 if (host_status == HOST_OK) {
1244 snprintf(msg + len, sizeof(msg) - len,
1245 "\nMatching host key in %s:%lu",
1246 host_found->file, host_found->line);
1248 if (options.strict_host_key_checking ==
1249 SSH_STRICT_HOSTKEY_ASK) {
1250 strlcat(msg, "\nAre you sure you want "
1251 "to continue connecting (yes/no)? ", sizeof(msg));
1254 } else if (options.strict_host_key_checking !=
1255 SSH_STRICT_HOSTKEY_OFF) {
1257 error("Exiting, you have requested strict checking.");
1264 if (!hostkey_trusted && options.update_hostkeys) {
1265 debug("%s: hostkey not known or explicitly trusted: "
1266 "disabling UpdateHostkeys", __func__);
1267 options.update_hostkeys = 0;
1272 if (host_hostkeys != NULL)
1273 free_hostkeys(host_hostkeys);
1274 if (ip_hostkeys != NULL)
1275 free_hostkeys(ip_hostkeys);
1279 if (want_cert && host_status != HOST_REVOKED) {
1281 * No matching certificate. Downgrade cert to raw key and
1284 debug("No matching CA found. Retry with plain key");
1285 if ((r = sshkey_from_private(host_key, &raw_key)) != 0)
1286 fatal("%s: sshkey_from_private: %s",
1287 __func__, ssh_err(r));
1288 if ((r = sshkey_drop_cert(raw_key)) != 0)
1289 fatal("Couldn't drop certificate: %s", ssh_err(r));
1293 sshkey_free(raw_key);
1296 if (host_hostkeys != NULL)
1297 free_hostkeys(host_hostkeys);
1298 if (ip_hostkeys != NULL)
1299 free_hostkeys(ip_hostkeys);
1303 /* returns 0 if key verifies or -1 if key does NOT verify */
1305 verify_host_key(char *host, struct sockaddr *hostaddr, struct sshkey *host_key)
1308 int r = -1, flags = 0;
1309 char valid[64], *fp = NULL, *cafp = NULL;
1310 struct sshkey *plain = NULL;
1312 if ((fp = sshkey_fingerprint(host_key,
1313 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
1314 error("%s: fingerprint host key: %s", __func__, ssh_err(r));
1319 if (sshkey_is_cert(host_key)) {
1320 if ((cafp = sshkey_fingerprint(host_key->cert->signature_key,
1321 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
1322 error("%s: fingerprint CA key: %s",
1323 __func__, ssh_err(r));
1327 sshkey_format_cert_validity(host_key->cert,
1328 valid, sizeof(valid));
1329 debug("Server host certificate: %s %s, serial %llu "
1330 "ID \"%s\" CA %s %s valid %s",
1331 sshkey_ssh_name(host_key), fp,
1332 (unsigned long long)host_key->cert->serial,
1333 host_key->cert->key_id,
1334 sshkey_ssh_name(host_key->cert->signature_key), cafp,
1336 for (i = 0; i < host_key->cert->nprincipals; i++) {
1337 debug2("Server host certificate hostname: %s",
1338 host_key->cert->principals[i]);
1341 debug("Server host key: %s %s", sshkey_ssh_name(host_key), fp);
1344 if (sshkey_equal(previous_host_key, host_key)) {
1345 debug2("%s: server host key %s %s matches cached key",
1346 __func__, sshkey_type(host_key), fp);
1351 /* Check in RevokedHostKeys file if specified */
1352 if (options.revoked_host_keys != NULL) {
1353 r = sshkey_check_revoked(host_key, options.revoked_host_keys);
1356 break; /* not revoked */
1357 case SSH_ERR_KEY_REVOKED:
1358 error("Host key %s %s revoked by file %s",
1359 sshkey_type(host_key), fp,
1360 options.revoked_host_keys);
1364 error("Error checking host key %s %s in "
1365 "revoked keys file %s: %s", sshkey_type(host_key),
1366 fp, options.revoked_host_keys, ssh_err(r));
1372 if (options.verify_host_key_dns) {
1374 * XXX certs are not yet supported for DNS, so downgrade
1375 * them and try the plain key.
1377 if ((r = sshkey_from_private(host_key, &plain)) != 0)
1379 if (sshkey_is_cert(plain))
1380 sshkey_drop_cert(plain);
1381 if (verify_host_key_dns(host, hostaddr, plain, &flags) == 0) {
1382 if (flags & DNS_VERIFY_FOUND) {
1383 if (options.verify_host_key_dns == 1 &&
1384 flags & DNS_VERIFY_MATCH &&
1385 flags & DNS_VERIFY_SECURE) {
1389 if (flags & DNS_VERIFY_MATCH) {
1390 matching_host_key_dns = 1;
1392 warn_changed_key(plain);
1393 error("Update the SSHFP RR in DNS "
1394 "with the new host key to get rid "
1395 "of this message.");
1400 r = check_host_key(host, hostaddr, options.port, host_key, RDRW,
1401 options.user_hostfiles, options.num_user_hostfiles,
1402 options.system_hostfiles, options.num_system_hostfiles);
1408 if (r == 0 && host_key != NULL) {
1409 sshkey_free(previous_host_key);
1410 r = sshkey_from_private(host_key, &previous_host_key);
1417 * Starts a dialog with the server, and authenticates the current user on the
1418 * server. This does not need any extra privileges. The basic connection
1419 * to the server must already have been established before this is called.
1420 * If login fails, this function prints an error and never returns.
1421 * This function does not require super-user privileges.
1424 ssh_login(Sensitive *sensitive, const char *orighost,
1425 struct sockaddr *hostaddr, u_short port, struct passwd *pw, int timeout_ms)
1428 char *server_user, *local_user;
1430 local_user = xstrdup(pw->pw_name);
1431 server_user = options.user ? options.user : local_user;
1433 /* Convert the user-supplied hostname into all lowercase. */
1434 host = xstrdup(orighost);
1437 /* Exchange protocol version identification strings with the server. */
1438 ssh_exchange_identification(timeout_ms);
1440 /* Put the connection into non-blocking mode. */
1441 packet_set_nonblocking();
1444 /* authenticate user */
1445 debug("Authenticating to %s:%d as '%s'", host, port, server_user);
1446 ssh_kex2(host, hostaddr, port);
1447 ssh_userauth2(local_user, server_user, host, sensitive);
1452 ssh_put_password(char *password)
1457 if (datafellows & SSH_BUG_PASSWORDPAD) {
1458 packet_put_cstring(password);
1461 size = ROUNDUP(strlen(password) + 1, 32);
1462 padded = xcalloc(1, size);
1463 strlcpy(padded, password, size);
1464 packet_put_string(padded, size);
1465 explicit_bzero(padded, size);
1469 /* print all known host keys for a given host, but skip keys of given type */
1471 show_other_keys(struct hostkeys *hostkeys, struct sshkey *key)
1483 const struct hostkey_entry *found;
1485 for (i = 0; type[i] != -1; i++) {
1486 if (type[i] == key->type)
1488 if (!lookup_key_in_hostkeys_by_type(hostkeys, type[i], &found))
1490 fp = sshkey_fingerprint(found->key,
1491 options.fingerprint_hash, SSH_FP_DEFAULT);
1492 ra = sshkey_fingerprint(found->key,
1493 options.fingerprint_hash, SSH_FP_RANDOMART);
1494 if (fp == NULL || ra == NULL)
1495 fatal("%s: sshkey_fingerprint fail", __func__);
1496 logit("WARNING: %s key found for host %s\n"
1498 "%s key fingerprint %s.",
1499 key_type(found->key),
1500 found->host, found->file, found->line,
1501 key_type(found->key), fp);
1502 if (options.visual_host_key)
1512 warn_changed_key(struct sshkey *host_key)
1516 fp = sshkey_fingerprint(host_key, options.fingerprint_hash,
1519 fatal("%s: sshkey_fingerprint fail", __func__);
1521 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1522 error("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @");
1523 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1524 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1525 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1526 error("It is also possible that a host key has just been changed.");
1527 error("The fingerprint for the %s key sent by the remote host is\n%s.",
1528 key_type(host_key), fp);
1529 error("Please contact your system administrator.");
1535 * Execute a local command
1538 ssh_local_cmd(const char *args)
1543 void (*osighand)(int);
1545 if (!options.permit_local_command ||
1546 args == NULL || !*args)
1549 if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
1550 shell = _PATH_BSHELL;
1552 osighand = signal(SIGCHLD, SIG_DFL);
1555 signal(SIGPIPE, SIG_DFL);
1556 debug3("Executing %s -c \"%s\"", shell, args);
1557 execl(shell, shell, "-c", args, (char *)NULL);
1558 error("Couldn't execute %s -c \"%s\": %s",
1559 shell, args, strerror(errno));
1561 } else if (pid == -1)
1562 fatal("fork failed: %.100s", strerror(errno));
1563 while (waitpid(pid, &status, 0) == -1)
1565 fatal("Couldn't wait for child: %s", strerror(errno));
1566 signal(SIGCHLD, osighand);
1568 if (!WIFEXITED(status))
1571 return (WEXITSTATUS(status));
1575 maybe_add_key_to_agent(char *authfile, const struct sshkey *private,
1576 char *comment, char *passphrase)
1578 int auth_sock = -1, r;
1580 if (options.add_keys_to_agent == 0)
1583 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
1584 debug3("no authentication agent, not adding key");
1588 if (options.add_keys_to_agent == 2 &&
1589 !ask_permission("Add key %s (%s) to agent?", authfile, comment)) {
1590 debug3("user denied adding this key");
1595 if ((r = ssh_add_identity_constrained(auth_sock, private, comment, 0,
1596 (options.add_keys_to_agent == 3), 0)) == 0)
1597 debug("identity added to agent: %s", authfile);
1599 debug("could not add identity to agent: %s (%d)", authfile, r);