1 /* $OpenBSD: sshconnect.c,v 1.305 2018/09/20 03:30:44 djm 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".
19 #include <sys/types.h>
22 #include <sys/socket.h>
23 #ifdef HAVE_SYS_TIME_H
24 # include <sys/time.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
59 #include "sshconnect.h"
66 #include "monitor_fdpass.h"
73 char *client_version_string = NULL;
74 char *server_version_string = NULL;
75 struct sshkey *previous_host_key = NULL;
77 static int matching_host_key_dns = 0;
79 static pid_t proxy_command_pid = 0;
82 extern Options options;
83 extern char *__progname;
85 static int show_other_keys(struct hostkeys *, struct sshkey *);
86 static void warn_changed_key(struct sshkey *);
88 /* Expand a proxy command */
90 expand_proxy_command(const char *proxy_command, const char *user,
91 const char *host, int port)
93 char *tmp, *ret, strport[NI_MAXSERV];
95 snprintf(strport, sizeof strport, "%d", port);
96 xasprintf(&tmp, "exec %s", proxy_command);
97 ret = percent_expand(tmp, "h", host, "p", strport,
98 "r", options.user, (char *)NULL);
104 * Connect to the given ssh server using a proxy command that passes a
105 * a connected fd back to us.
108 ssh_proxy_fdpass_connect(struct ssh *ssh, const char *host, u_short port,
109 const char *proxy_command)
111 char *command_string;
116 if ((shell = getenv("SHELL")) == NULL)
117 shell = _PATH_BSHELL;
119 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sp) < 0)
120 fatal("Could not create socketpair to communicate with "
121 "proxy dialer: %.100s", strerror(errno));
123 command_string = expand_proxy_command(proxy_command, options.user,
125 debug("Executing proxy dialer command: %.500s", command_string);
127 /* Fork and execute the proxy command. */
128 if ((pid = fork()) == 0) {
132 /* Redirect stdin and stdout. */
134 if (dup2(sp[0], 0) < 0)
135 perror("dup2 stdin");
138 if (dup2(sp[0], 1) < 0)
139 perror("dup2 stdout");
145 * Stderr is left as it is so that error messages get
146 * printed on the user's terminal.
150 argv[2] = command_string;
154 * Execute the proxy command.
155 * Note that we gave up any extra privileges above.
157 execv(argv[0], argv);
163 fatal("fork failed: %.100s", strerror(errno));
165 free(command_string);
167 if ((sock = mm_receive_fd(sp[1])) == -1)
168 fatal("proxy dialer did not pass back a connection");
171 while (waitpid(pid, NULL, 0) == -1)
173 fatal("Couldn't wait for child: %s", strerror(errno));
175 /* Set the connection file descriptors. */
176 if (ssh_packet_set_connection(ssh, sock, sock) == NULL)
177 return -1; /* ssh_packet_set_connection logs error */
183 * Connect to the given ssh server using a proxy command.
186 ssh_proxy_connect(struct ssh *ssh, const char *host, u_short port,
187 const char *proxy_command)
189 char *command_string;
194 if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
195 shell = _PATH_BSHELL;
197 /* Create pipes for communicating with the proxy. */
198 if (pipe(pin) < 0 || pipe(pout) < 0)
199 fatal("Could not create pipes to communicate with the proxy: %.100s",
202 command_string = expand_proxy_command(proxy_command, options.user,
204 debug("Executing proxy command: %.500s", command_string);
206 /* Fork and execute the proxy command. */
207 if ((pid = fork()) == 0) {
210 /* Redirect stdin and stdout. */
213 if (dup2(pin[0], 0) < 0)
214 perror("dup2 stdin");
218 if (dup2(pout[1], 1) < 0)
219 perror("dup2 stdout");
220 /* Cannot be 1 because pin allocated two descriptors. */
223 /* Stderr is left as it is so that error messages get
224 printed on the user's terminal. */
227 argv[2] = command_string;
230 /* Execute the proxy command. Note that we gave up any
231 extra privileges above. */
232 signal(SIGPIPE, SIG_DFL);
233 execv(argv[0], argv);
239 fatal("fork failed: %.100s", strerror(errno));
241 proxy_command_pid = pid; /* save pid to clean up later */
243 /* Close child side of the descriptors. */
247 /* Free the command name. */
248 free(command_string);
250 /* Set the connection file descriptors. */
251 if (ssh_packet_set_connection(ssh, pout[0], pin[1]) == NULL)
252 return -1; /* ssh_packet_set_connection logs error */
258 ssh_kill_proxy_command(void)
261 * Send SIGHUP to proxy command if used. We don't wait() in
262 * case it hangs and instead rely on init to reap the child
264 if (proxy_command_pid > 1)
265 kill(proxy_command_pid, SIGHUP);
268 #ifdef HAVE_IFADDRS_H
270 * Search a interface address list (returned from getifaddrs(3)) for an
271 * address that matches the desired address family on the specified interface.
272 * Returns 0 and fills in *resultp and *rlenp on success. Returns -1 on failure.
275 check_ifaddrs(const char *ifname, int af, const struct ifaddrs *ifaddrs,
276 struct sockaddr_storage *resultp, socklen_t *rlenp)
278 struct sockaddr_in6 *sa6;
279 struct sockaddr_in *sa;
280 struct in6_addr *v6addr;
281 const struct ifaddrs *ifa;
285 * Prefer addresses that are not loopback or linklocal, but use them
286 * if nothing else matches.
288 for (allow_local = 0; allow_local < 2; allow_local++) {
289 for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
290 if (ifa->ifa_addr == NULL || ifa->ifa_name == NULL ||
291 (ifa->ifa_flags & IFF_UP) == 0 ||
292 ifa->ifa_addr->sa_family != af ||
293 strcmp(ifa->ifa_name, options.bind_interface) != 0)
295 switch (ifa->ifa_addr->sa_family) {
297 sa = (struct sockaddr_in *)ifa->ifa_addr;
298 if (!allow_local && sa->sin_addr.s_addr ==
299 htonl(INADDR_LOOPBACK))
301 if (*rlenp < sizeof(struct sockaddr_in)) {
302 error("%s: v4 addr doesn't fit",
306 *rlenp = sizeof(struct sockaddr_in);
307 memcpy(resultp, sa, *rlenp);
310 sa6 = (struct sockaddr_in6 *)ifa->ifa_addr;
311 v6addr = &sa6->sin6_addr;
313 (IN6_IS_ADDR_LINKLOCAL(v6addr) ||
314 IN6_IS_ADDR_LOOPBACK(v6addr)))
316 if (*rlenp < sizeof(struct sockaddr_in6)) {
317 error("%s: v6 addr doesn't fit",
321 *rlenp = sizeof(struct sockaddr_in6);
322 memcpy(resultp, sa6, *rlenp);
332 * Creates a socket for use as the ssh connection.
335 ssh_create_socket(struct addrinfo *ai)
338 struct sockaddr_storage bindaddr;
339 socklen_t bindaddrlen = 0;
340 struct addrinfo hints, *res = NULL;
341 #ifdef HAVE_IFADDRS_H
342 struct ifaddrs *ifaddrs = NULL;
344 char ntop[NI_MAXHOST];
346 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
348 error("socket: %s", strerror(errno));
351 fcntl(sock, F_SETFD, FD_CLOEXEC);
353 /* Bind the socket to an alternative local IP address */
354 if (options.bind_address == NULL && options.bind_interface == NULL)
357 if (options.bind_address != NULL) {
358 memset(&hints, 0, sizeof(hints));
359 hints.ai_family = ai->ai_family;
360 hints.ai_socktype = ai->ai_socktype;
361 hints.ai_protocol = ai->ai_protocol;
362 hints.ai_flags = AI_PASSIVE;
363 if ((r = getaddrinfo(options.bind_address, NULL,
364 &hints, &res)) != 0) {
365 error("getaddrinfo: %s: %s", options.bind_address,
366 ssh_gai_strerror(r));
370 error("getaddrinfo: no addrs");
373 if (res->ai_addrlen > sizeof(bindaddr)) {
374 error("%s: addr doesn't fit", __func__);
377 memcpy(&bindaddr, res->ai_addr, res->ai_addrlen);
378 bindaddrlen = res->ai_addrlen;
379 } else if (options.bind_interface != NULL) {
380 #ifdef HAVE_IFADDRS_H
381 if ((r = getifaddrs(&ifaddrs)) != 0) {
382 error("getifaddrs: %s: %s", options.bind_interface,
386 bindaddrlen = sizeof(bindaddr);
387 if (check_ifaddrs(options.bind_interface, ai->ai_family,
388 ifaddrs, &bindaddr, &bindaddrlen) != 0) {
389 logit("getifaddrs: %s: no suitable addresses",
390 options.bind_interface);
394 error("BindInterface not supported on this platform.");
397 if ((r = getnameinfo((struct sockaddr *)&bindaddr, bindaddrlen,
398 ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST)) != 0) {
399 error("%s: getnameinfo failed: %s", __func__,
400 ssh_gai_strerror(r));
403 if (bind(sock, (struct sockaddr *)&bindaddr, bindaddrlen) != 0) {
404 error("bind %s: %s", ntop, strerror(errno));
407 debug("%s: bound to %s", __func__, ntop);
416 #ifdef HAVE_IFADDRS_H
418 freeifaddrs(ifaddrs);
424 * Wait up to *timeoutp milliseconds for fd to be readable. Updates
425 * *timeoutp with time remaining.
426 * Returns 0 if fd ready or -1 on timeout or error (see errno).
429 waitrfd(int fd, int *timeoutp)
432 struct timeval t_start;
435 monotime_tv(&t_start);
438 for (; *timeoutp >= 0;) {
439 r = poll(&pfd, 1, *timeoutp);
441 ms_subtract_diff(&t_start, timeoutp);
445 else if (r == -1 && errno != EAGAIN)
456 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
457 socklen_t addrlen, int *timeoutp)
460 socklen_t optlen = sizeof(optval);
462 /* No timeout: just do a blocking connect() */
464 return connect(sockfd, serv_addr, addrlen);
466 set_nonblock(sockfd);
467 if (connect(sockfd, serv_addr, addrlen) == 0) {
468 /* Succeeded already? */
469 unset_nonblock(sockfd);
471 } else if (errno != EINPROGRESS)
474 if (waitrfd(sockfd, timeoutp) == -1)
477 /* Completed or failed */
478 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
479 debug("getsockopt: %s", strerror(errno));
486 unset_nonblock(sockfd);
491 * Opens a TCP/IP connection to the remote server on the given host.
492 * The address of the remote host will be returned in hostaddr.
493 * If port is 0, the default port will be used.
494 * Connection_attempts specifies the maximum number of tries (one per
495 * second). If proxy_command is non-NULL, it specifies the command (with %h
496 * and %p substituted for host and port, respectively) to use to contact
500 ssh_connect_direct(struct ssh *ssh, const char *host, struct addrinfo *aitop,
501 struct sockaddr_storage *hostaddr, u_short port, int family,
502 int connection_attempts, int *timeout_ms, int want_keepalive)
505 int oerrno, sock = -1, attempt;
506 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
509 debug2("%s", __func__);
510 memset(ntop, 0, sizeof(ntop));
511 memset(strport, 0, sizeof(strport));
513 for (attempt = 0; attempt < connection_attempts; attempt++) {
515 /* Sleep a moment before retrying. */
517 debug("Trying again...");
520 * Loop through addresses for this host, and try each one in
521 * sequence until the connection succeeds.
523 for (ai = aitop; ai; ai = ai->ai_next) {
524 if (ai->ai_family != AF_INET &&
525 ai->ai_family != AF_INET6) {
526 errno = EAFNOSUPPORT;
529 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
530 ntop, sizeof(ntop), strport, sizeof(strport),
531 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
533 error("%s: getnameinfo failed", __func__);
537 debug("Connecting to %.200s [%.100s] port %s.",
538 host, ntop, strport);
540 /* Create a socket for connecting. */
541 sock = ssh_create_socket(ai);
543 /* Any error is already output */
548 if (timeout_connect(sock, ai->ai_addr, ai->ai_addrlen,
550 /* Successful connection. */
551 memcpy(hostaddr, ai->ai_addr, ai->ai_addrlen);
555 debug("connect to address %s port %s: %s",
556 ntop, strport, strerror(errno));
563 break; /* Successful connection. */
566 /* Return failure if we didn't get a successful connection. */
568 error("ssh: connect to host %s port %s: %s",
569 host, strport, errno == 0 ? "failure" : strerror(errno));
573 debug("Connection established.");
575 /* Set SO_KEEPALIVE if requested. */
576 if (want_keepalive &&
577 setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
579 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
581 /* Set the connection. */
582 if (ssh_packet_set_connection(ssh, sock, sock) == NULL)
583 return -1; /* ssh_packet_set_connection logs error */
589 ssh_connect(struct ssh *ssh, const char *host, struct addrinfo *addrs,
590 struct sockaddr_storage *hostaddr, u_short port, int family,
591 int connection_attempts, int *timeout_ms, int want_keepalive)
593 if (options.proxy_command == NULL) {
594 return ssh_connect_direct(ssh, host, addrs, hostaddr, port,
595 family, connection_attempts, timeout_ms, want_keepalive);
596 } else if (strcmp(options.proxy_command, "-") == 0) {
597 if ((ssh_packet_set_connection(ssh,
598 STDIN_FILENO, STDOUT_FILENO)) == NULL)
599 return -1; /* ssh_packet_set_connection logs error */
601 } else if (options.proxy_use_fdpass) {
602 return ssh_proxy_fdpass_connect(ssh, host, port,
603 options.proxy_command);
605 return ssh_proxy_connect(ssh, host, port, options.proxy_command);
609 send_client_banner(int connection_out, int minor1)
611 /* Send our own protocol version identification. */
612 xasprintf(&client_version_string, "SSH-%d.%d-%.100s%s%s\n",
613 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
614 *options.version_addendum == '\0' ? "" : " ",
615 options.version_addendum);
616 if (atomicio(vwrite, connection_out, client_version_string,
617 strlen(client_version_string)) != strlen(client_version_string))
618 fatal("write: %.100s", strerror(errno));
619 chop(client_version_string);
620 debug("Local version string %.100s", client_version_string);
624 * Waits for the server identification string, and sends our own
625 * identification string.
628 ssh_exchange_identification(int timeout_ms)
630 char buf[256], remote_version[256]; /* must be same size! */
631 int remote_major, remote_minor, mismatch;
632 int connection_in = packet_get_connection_in();
633 int connection_out = packet_get_connection_out();
638 send_client_banner(connection_out, 0);
640 /* Read other side's version identification. */
642 for (i = 0; i < sizeof(buf) - 1; i++) {
643 if (timeout_ms > 0) {
644 rc = waitrfd(connection_in, &timeout_ms);
645 if (rc == -1 && errno == ETIMEDOUT) {
646 fatal("Connection timed out during "
648 } else if (rc == -1) {
650 __func__, strerror(errno));
654 len = atomicio(read, connection_in, &buf[i], 1);
655 if (len != 1 && errno == EPIPE)
656 fatal("ssh_exchange_identification: "
657 "Connection closed by remote host");
659 fatal("ssh_exchange_identification: "
660 "read: %.100s", strerror(errno));
661 if (buf[i] == '\r') {
664 continue; /**XXX wait for \n */
666 if (buf[i] == '\n') {
671 fatal("ssh_exchange_identification: "
672 "No banner received");
674 buf[sizeof(buf) - 1] = 0;
675 if (strncmp(buf, "SSH-", 4) == 0)
677 debug("ssh_exchange_identification: %s", buf);
679 server_version_string = xstrdup(buf);
682 * Check that the versions match. In future this might accept
683 * several versions and set appropriate flags to handle them.
685 if (sscanf(server_version_string, "SSH-%d.%d-%[^\n]\n",
686 &remote_major, &remote_minor, remote_version) != 3)
687 fatal("Bad remote protocol version identification: '%.100s'", buf);
688 debug("Remote protocol version %d.%d, remote software version %.100s",
689 remote_major, remote_minor, remote_version);
691 active_state->compat = compat_datafellows(remote_version);
694 switch (remote_major) {
698 if (remote_minor != 99)
706 fatal("Protocol major versions differ: %d vs. %d",
707 PROTOCOL_MAJOR_2, remote_major);
708 if ((datafellows & SSH_BUG_RSASIGMD5) != 0)
709 logit("Server version \"%.100s\" uses unsafe RSA signature "
710 "scheme; disabling use of RSA keys", remote_version);
711 chop(server_version_string);
714 /* defaults to 'no' */
716 confirm(const char *prompt)
718 const char *msg, *again = "Please type 'yes' or 'no': ";
722 if (options.batch_mode)
724 for (msg = prompt;;msg = again) {
725 p = read_passphrase(msg, RP_ECHO);
728 p[strcspn(p, "\n")] = '\0';
729 if (p[0] == '\0' || strcasecmp(p, "no") == 0)
731 else if (strcasecmp(p, "yes") == 0)
740 check_host_cert(const char *host, const struct sshkey *key)
745 if (sshkey_cert_check_authority(key, 1, 0, host, &reason) != 0) {
749 if (sshbuf_len(key->cert->critical) != 0) {
750 error("Certificate for %s contains unsupported "
751 "critical options(s)", host);
754 if ((r = sshkey_check_cert_sigtype(key,
755 options.ca_sign_algorithms)) != 0) {
756 logit("%s: certificate signature algorithm %s: %s", __func__,
757 (key->cert == NULL || key->cert->signature_type == NULL) ?
758 "(null)" : key->cert->signature_type, ssh_err(r));
766 sockaddr_is_local(struct sockaddr *hostaddr)
768 switch (hostaddr->sa_family) {
770 return (ntohl(((struct sockaddr_in *)hostaddr)->
771 sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
773 return IN6_IS_ADDR_LOOPBACK(
774 &(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
781 * Prepare the hostname and ip address strings that are used to lookup
782 * host keys in known_hosts files. These may have a port number appended.
785 get_hostfile_hostname_ipaddr(char *hostname, struct sockaddr *hostaddr,
786 u_short port, char **hostfile_hostname, char **hostfile_ipaddr)
788 char ntop[NI_MAXHOST];
791 switch (hostaddr == NULL ? -1 : hostaddr->sa_family) {
796 addrlen = sizeof(struct sockaddr_in);
799 addrlen = sizeof(struct sockaddr_in6);
802 addrlen = sizeof(struct sockaddr);
807 * We don't have the remote ip-address for connections
808 * using a proxy command
810 if (hostfile_ipaddr != NULL) {
811 if (options.proxy_command == NULL) {
812 if (getnameinfo(hostaddr, addrlen,
813 ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST) != 0)
814 fatal("%s: getnameinfo failed", __func__);
815 *hostfile_ipaddr = put_host_port(ntop, port);
817 *hostfile_ipaddr = xstrdup("<no hostip for proxy "
823 * Allow the user to record the key under a different name or
824 * differentiate a non-standard port. This is useful for ssh
825 * tunneling over forwarded connections or if you run multiple
826 * sshd's on different ports on the same machine.
828 if (hostfile_hostname != NULL) {
829 if (options.host_key_alias != NULL) {
830 *hostfile_hostname = xstrdup(options.host_key_alias);
831 debug("using hostkeyalias: %s", *hostfile_hostname);
833 *hostfile_hostname = put_host_port(hostname, port);
839 * check whether the supplied host key is valid, return -1 if the key
840 * is not valid. user_hostfile[0] will not be updated if 'readonly' is true.
846 check_host_key(char *hostname, struct sockaddr *hostaddr, u_short port,
847 struct sshkey *host_key, int readonly,
848 char **user_hostfiles, u_int num_user_hostfiles,
849 char **system_hostfiles, u_int num_system_hostfiles)
851 HostStatus host_status;
852 HostStatus ip_status;
853 struct sshkey *raw_key = NULL;
854 char *ip = NULL, *host = NULL;
855 char hostline[1000], *hostp, *fp, *ra;
858 const struct hostkey_entry *host_found, *ip_found;
859 int len, cancelled_forwarding = 0;
860 int local = sockaddr_is_local(hostaddr);
861 int r, want_cert = sshkey_is_cert(host_key), host_ip_differ = 0;
862 int hostkey_trusted = 0; /* Known or explicitly accepted by user */
863 struct hostkeys *host_hostkeys, *ip_hostkeys;
867 * Force accepting of the host key for loopback/localhost. The
868 * problem is that if the home directory is NFS-mounted to multiple
869 * machines, localhost will refer to a different machine in each of
870 * them, and the user will get bogus HOST_CHANGED warnings. This
871 * essentially disables host authentication for localhost; however,
872 * this is probably not a real problem.
874 if (options.no_host_authentication_for_localhost == 1 && local &&
875 options.host_key_alias == NULL) {
876 debug("Forcing accepting of host key for "
877 "loopback/localhost.");
882 * Prepare the hostname and address strings used for hostkey lookup.
883 * In some cases, these will have a port number appended.
885 get_hostfile_hostname_ipaddr(hostname, hostaddr, port, &host, &ip);
888 * Turn off check_host_ip if the connection is to localhost, via proxy
889 * command or if we don't have a hostname to compare with
891 if (options.check_host_ip && (local ||
892 strcmp(hostname, ip) == 0 || options.proxy_command != NULL))
893 options.check_host_ip = 0;
895 host_hostkeys = init_hostkeys();
896 for (i = 0; i < num_user_hostfiles; i++)
897 load_hostkeys(host_hostkeys, host, user_hostfiles[i]);
898 for (i = 0; i < num_system_hostfiles; i++)
899 load_hostkeys(host_hostkeys, host, system_hostfiles[i]);
902 if (!want_cert && options.check_host_ip) {
903 ip_hostkeys = init_hostkeys();
904 for (i = 0; i < num_user_hostfiles; i++)
905 load_hostkeys(ip_hostkeys, ip, user_hostfiles[i]);
906 for (i = 0; i < num_system_hostfiles; i++)
907 load_hostkeys(ip_hostkeys, ip, system_hostfiles[i]);
911 /* Reload these as they may have changed on cert->key downgrade */
912 want_cert = sshkey_is_cert(host_key);
913 type = sshkey_type(host_key);
916 * Check if the host key is present in the user's list of known
917 * hosts or in the systemwide list.
919 host_status = check_key_in_hostkeys(host_hostkeys, host_key,
923 * Also perform check for the ip address, skip the check if we are
924 * localhost, looking for a certificate, or the hostname was an ip
925 * address to begin with.
927 if (!want_cert && ip_hostkeys != NULL) {
928 ip_status = check_key_in_hostkeys(ip_hostkeys, host_key,
930 if (host_status == HOST_CHANGED &&
931 (ip_status != HOST_CHANGED ||
933 !sshkey_equal(ip_found->key, host_found->key))))
936 ip_status = host_status;
938 switch (host_status) {
940 /* The host is known and the key matches. */
941 debug("Host '%.200s' is known and matches the %s host %s.",
942 host, type, want_cert ? "certificate" : "key");
943 debug("Found %s in %s:%lu", want_cert ? "CA key" : "key",
944 host_found->file, host_found->line);
946 !check_host_cert(options.host_key_alias == NULL ?
947 hostname : options.host_key_alias, host_key))
949 if (options.check_host_ip && ip_status == HOST_NEW) {
950 if (readonly || want_cert)
951 logit("%s host key for IP address "
952 "'%.128s' not in list of known hosts.",
954 else if (!add_host_to_hostfile(user_hostfiles[0], ip,
955 host_key, options.hash_known_hosts))
956 logit("Failed to add the %s host key for IP "
957 "address '%.128s' to the list of known "
958 "hosts (%.500s).", type, ip,
961 logit("Warning: Permanently added the %s host "
962 "key for IP address '%.128s' to the list "
963 "of known hosts.", type, ip);
964 } else if (options.visual_host_key) {
965 fp = sshkey_fingerprint(host_key,
966 options.fingerprint_hash, SSH_FP_DEFAULT);
967 ra = sshkey_fingerprint(host_key,
968 options.fingerprint_hash, SSH_FP_RANDOMART);
969 if (fp == NULL || ra == NULL)
970 fatal("%s: sshkey_fingerprint fail", __func__);
971 logit("Host key fingerprint is %s\n%s", fp, ra);
978 if (options.host_key_alias == NULL && port != 0 &&
979 port != SSH_DEFAULT_PORT) {
980 debug("checking without port identifier");
981 if (check_host_key(hostname, hostaddr, 0, host_key,
982 ROQUIET, user_hostfiles, num_user_hostfiles,
983 system_hostfiles, num_system_hostfiles) == 0) {
984 debug("found matching key w/out port");
988 if (readonly || want_cert)
990 /* The host is new. */
991 if (options.strict_host_key_checking ==
992 SSH_STRICT_HOSTKEY_YES) {
994 * User has requested strict host key checking. We
995 * will not add the host key automatically. The only
996 * alternative left is to abort.
998 error("No %s host key is known for %.200s and you "
999 "have requested strict checking.", type, host);
1001 } else if (options.strict_host_key_checking ==
1002 SSH_STRICT_HOSTKEY_ASK) {
1003 char msg1[1024], msg2[1024];
1005 if (show_other_keys(host_hostkeys, host_key))
1006 snprintf(msg1, sizeof(msg1),
1007 "\nbut keys of different type are already"
1008 " known for this host.");
1010 snprintf(msg1, sizeof(msg1), ".");
1012 fp = sshkey_fingerprint(host_key,
1013 options.fingerprint_hash, SSH_FP_DEFAULT);
1014 ra = sshkey_fingerprint(host_key,
1015 options.fingerprint_hash, SSH_FP_RANDOMART);
1016 if (fp == NULL || ra == NULL)
1017 fatal("%s: sshkey_fingerprint fail", __func__);
1019 if (options.verify_host_key_dns) {
1020 if (matching_host_key_dns)
1021 snprintf(msg2, sizeof(msg2),
1022 "Matching host key fingerprint"
1023 " found in DNS.\n");
1025 snprintf(msg2, sizeof(msg2),
1026 "No matching host key fingerprint"
1027 " found in DNS.\n");
1029 snprintf(msg, sizeof(msg),
1030 "The authenticity of host '%.200s (%s)' can't be "
1032 "%s key fingerprint is %s.%s%s\n%s"
1033 "Are you sure you want to continue connecting "
1035 host, ip, msg1, type, fp,
1036 options.visual_host_key ? "\n" : "",
1037 options.visual_host_key ? ra : "",
1043 hostkey_trusted = 1; /* user explicitly confirmed */
1046 * If in "new" or "off" strict mode, add the key automatically
1047 * to the local known_hosts file.
1049 if (options.check_host_ip && ip_status == HOST_NEW) {
1050 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1052 if (options.hash_known_hosts) {
1053 /* Add hash of host and IP separately */
1054 r = add_host_to_hostfile(user_hostfiles[0],
1055 host, host_key, options.hash_known_hosts) &&
1056 add_host_to_hostfile(user_hostfiles[0], ip,
1057 host_key, options.hash_known_hosts);
1059 /* Add unhashed "host,ip" */
1060 r = add_host_to_hostfile(user_hostfiles[0],
1062 options.hash_known_hosts);
1065 r = add_host_to_hostfile(user_hostfiles[0], host,
1066 host_key, options.hash_known_hosts);
1071 logit("Failed to add the host to the list of known "
1072 "hosts (%.500s).", user_hostfiles[0]);
1074 logit("Warning: Permanently added '%.200s' (%s) to the "
1075 "list of known hosts.", hostp, type);
1078 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1079 error("@ WARNING: REVOKED HOST KEY DETECTED! @");
1080 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1081 error("The %s host key for %s is marked as revoked.", type, host);
1082 error("This could mean that a stolen key is being used to");
1083 error("impersonate this host.");
1086 * If strict host key checking is in use, the user will have
1087 * to edit the key manually and we can only abort.
1089 if (options.strict_host_key_checking !=
1090 SSH_STRICT_HOSTKEY_OFF) {
1091 error("%s host key for %.200s was revoked and you have "
1092 "requested strict checking.", type, host);
1095 goto continue_unsafe;
1100 * This is only a debug() since it is valid to have
1101 * CAs with wildcard DNS matches that don't match
1102 * all hosts that one might visit.
1104 debug("Host certificate authority does not "
1105 "match %s in %s:%lu", CA_MARKER,
1106 host_found->file, host_found->line);
1109 if (readonly == ROQUIET)
1111 if (options.check_host_ip && host_ip_differ) {
1113 if (ip_status == HOST_NEW)
1114 key_msg = "is unknown";
1115 else if (ip_status == HOST_OK)
1116 key_msg = "is unchanged";
1118 key_msg = "has a different value";
1119 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1120 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1121 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1122 error("The %s host key for %s has changed,", type, host);
1123 error("and the key for the corresponding IP address %s", ip);
1124 error("%s. This could either mean that", key_msg);
1125 error("DNS SPOOFING is happening or the IP address for the host");
1126 error("and its host key have changed at the same time.");
1127 if (ip_status != HOST_NEW)
1128 error("Offending key for IP in %s:%lu",
1129 ip_found->file, ip_found->line);
1131 /* The host key has changed. */
1132 warn_changed_key(host_key);
1133 error("Add correct host key in %.100s to get rid of this message.",
1135 error("Offending %s key in %s:%lu",
1136 sshkey_type(host_found->key),
1137 host_found->file, host_found->line);
1140 * If strict host key checking is in use, the user will have
1141 * to edit the key manually and we can only abort.
1143 if (options.strict_host_key_checking !=
1144 SSH_STRICT_HOSTKEY_OFF) {
1145 error("%s host key for %.200s has changed and you have "
1146 "requested strict checking.", type, host);
1152 * If strict host key checking has not been requested, allow
1153 * the connection but without MITM-able authentication or
1156 if (options.password_authentication) {
1157 error("Password authentication is disabled to avoid "
1158 "man-in-the-middle attacks.");
1159 options.password_authentication = 0;
1160 cancelled_forwarding = 1;
1162 if (options.kbd_interactive_authentication) {
1163 error("Keyboard-interactive authentication is disabled"
1164 " to avoid man-in-the-middle attacks.");
1165 options.kbd_interactive_authentication = 0;
1166 options.challenge_response_authentication = 0;
1167 cancelled_forwarding = 1;
1169 if (options.challenge_response_authentication) {
1170 error("Challenge/response authentication is disabled"
1171 " to avoid man-in-the-middle attacks.");
1172 options.challenge_response_authentication = 0;
1173 cancelled_forwarding = 1;
1175 if (options.forward_agent) {
1176 error("Agent forwarding is disabled to avoid "
1177 "man-in-the-middle attacks.");
1178 options.forward_agent = 0;
1179 cancelled_forwarding = 1;
1181 if (options.forward_x11) {
1182 error("X11 forwarding is disabled to avoid "
1183 "man-in-the-middle attacks.");
1184 options.forward_x11 = 0;
1185 cancelled_forwarding = 1;
1187 if (options.num_local_forwards > 0 ||
1188 options.num_remote_forwards > 0) {
1189 error("Port forwarding is disabled to avoid "
1190 "man-in-the-middle attacks.");
1191 options.num_local_forwards =
1192 options.num_remote_forwards = 0;
1193 cancelled_forwarding = 1;
1195 if (options.tun_open != SSH_TUNMODE_NO) {
1196 error("Tunnel forwarding is disabled to avoid "
1197 "man-in-the-middle attacks.");
1198 options.tun_open = SSH_TUNMODE_NO;
1199 cancelled_forwarding = 1;
1201 if (options.exit_on_forward_failure && cancelled_forwarding)
1202 fatal("Error: forwarding disabled due to host key "
1206 * XXX Should permit the user to change to use the new id.
1207 * This could be done by converting the host key to an
1208 * identifying sentence, tell that the host identifies itself
1209 * by that sentence, and ask the user if he/she wishes to
1210 * accept the authentication.
1214 fatal("internal error");
1218 if (options.check_host_ip && host_status != HOST_CHANGED &&
1219 ip_status == HOST_CHANGED) {
1220 snprintf(msg, sizeof(msg),
1221 "Warning: the %s host key for '%.200s' "
1222 "differs from the key for the IP address '%.128s'"
1223 "\nOffending key for IP in %s:%lu",
1224 type, host, ip, ip_found->file, ip_found->line);
1225 if (host_status == HOST_OK) {
1227 snprintf(msg + len, sizeof(msg) - len,
1228 "\nMatching host key in %s:%lu",
1229 host_found->file, host_found->line);
1231 if (options.strict_host_key_checking ==
1232 SSH_STRICT_HOSTKEY_ASK) {
1233 strlcat(msg, "\nAre you sure you want "
1234 "to continue connecting (yes/no)? ", sizeof(msg));
1237 } else if (options.strict_host_key_checking !=
1238 SSH_STRICT_HOSTKEY_OFF) {
1240 error("Exiting, you have requested strict checking.");
1247 if (!hostkey_trusted && options.update_hostkeys) {
1248 debug("%s: hostkey not known or explicitly trusted: "
1249 "disabling UpdateHostkeys", __func__);
1250 options.update_hostkeys = 0;
1255 if (host_hostkeys != NULL)
1256 free_hostkeys(host_hostkeys);
1257 if (ip_hostkeys != NULL)
1258 free_hostkeys(ip_hostkeys);
1262 if (want_cert && host_status != HOST_REVOKED) {
1264 * No matching certificate. Downgrade cert to raw key and
1267 debug("No matching CA found. Retry with plain key");
1268 if ((r = sshkey_from_private(host_key, &raw_key)) != 0)
1269 fatal("%s: sshkey_from_private: %s",
1270 __func__, ssh_err(r));
1271 if ((r = sshkey_drop_cert(raw_key)) != 0)
1272 fatal("Couldn't drop certificate: %s", ssh_err(r));
1276 sshkey_free(raw_key);
1279 if (host_hostkeys != NULL)
1280 free_hostkeys(host_hostkeys);
1281 if (ip_hostkeys != NULL)
1282 free_hostkeys(ip_hostkeys);
1286 /* returns 0 if key verifies or -1 if key does NOT verify */
1288 verify_host_key(char *host, struct sockaddr *hostaddr, struct sshkey *host_key)
1291 int r = -1, flags = 0;
1292 char valid[64], *fp = NULL, *cafp = NULL;
1293 struct sshkey *plain = NULL;
1295 if ((fp = sshkey_fingerprint(host_key,
1296 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
1297 error("%s: fingerprint host key: %s", __func__, ssh_err(r));
1302 if (sshkey_is_cert(host_key)) {
1303 if ((cafp = sshkey_fingerprint(host_key->cert->signature_key,
1304 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
1305 error("%s: fingerprint CA key: %s",
1306 __func__, ssh_err(r));
1310 sshkey_format_cert_validity(host_key->cert,
1311 valid, sizeof(valid));
1312 debug("Server host certificate: %s %s, serial %llu "
1313 "ID \"%s\" CA %s %s valid %s",
1314 sshkey_ssh_name(host_key), fp,
1315 (unsigned long long)host_key->cert->serial,
1316 host_key->cert->key_id,
1317 sshkey_ssh_name(host_key->cert->signature_key), cafp,
1319 for (i = 0; i < host_key->cert->nprincipals; i++) {
1320 debug2("Server host certificate hostname: %s",
1321 host_key->cert->principals[i]);
1324 debug("Server host key: %s %s", sshkey_ssh_name(host_key), fp);
1327 if (sshkey_equal(previous_host_key, host_key)) {
1328 debug2("%s: server host key %s %s matches cached key",
1329 __func__, sshkey_type(host_key), fp);
1334 /* Check in RevokedHostKeys file if specified */
1335 if (options.revoked_host_keys != NULL) {
1336 r = sshkey_check_revoked(host_key, options.revoked_host_keys);
1339 break; /* not revoked */
1340 case SSH_ERR_KEY_REVOKED:
1341 error("Host key %s %s revoked by file %s",
1342 sshkey_type(host_key), fp,
1343 options.revoked_host_keys);
1347 error("Error checking host key %s %s in "
1348 "revoked keys file %s: %s", sshkey_type(host_key),
1349 fp, options.revoked_host_keys, ssh_err(r));
1355 if (options.verify_host_key_dns) {
1357 * XXX certs are not yet supported for DNS, so downgrade
1358 * them and try the plain key.
1360 if ((r = sshkey_from_private(host_key, &plain)) != 0)
1362 if (sshkey_is_cert(plain))
1363 sshkey_drop_cert(plain);
1364 if (verify_host_key_dns(host, hostaddr, plain, &flags) == 0) {
1365 if (flags & DNS_VERIFY_FOUND) {
1366 if (options.verify_host_key_dns == 1 &&
1367 flags & DNS_VERIFY_MATCH &&
1368 flags & DNS_VERIFY_SECURE) {
1372 if (flags & DNS_VERIFY_MATCH) {
1373 matching_host_key_dns = 1;
1375 warn_changed_key(plain);
1376 error("Update the SSHFP RR in DNS "
1377 "with the new host key to get rid "
1378 "of this message.");
1383 r = check_host_key(host, hostaddr, options.port, host_key, RDRW,
1384 options.user_hostfiles, options.num_user_hostfiles,
1385 options.system_hostfiles, options.num_system_hostfiles);
1391 if (r == 0 && host_key != NULL) {
1392 sshkey_free(previous_host_key);
1393 r = sshkey_from_private(host_key, &previous_host_key);
1400 * Starts a dialog with the server, and authenticates the current user on the
1401 * server. This does not need any extra privileges. The basic connection
1402 * to the server must already have been established before this is called.
1403 * If login fails, this function prints an error and never returns.
1404 * This function does not require super-user privileges.
1407 ssh_login(Sensitive *sensitive, const char *orighost,
1408 struct sockaddr *hostaddr, u_short port, struct passwd *pw, int timeout_ms)
1411 char *server_user, *local_user;
1413 local_user = xstrdup(pw->pw_name);
1414 server_user = options.user ? options.user : local_user;
1416 /* Convert the user-supplied hostname into all lowercase. */
1417 host = xstrdup(orighost);
1420 /* Exchange protocol version identification strings with the server. */
1421 ssh_exchange_identification(timeout_ms);
1423 /* Put the connection into non-blocking mode. */
1424 packet_set_nonblocking();
1427 /* authenticate user */
1428 debug("Authenticating to %s:%d as '%s'", host, port, server_user);
1429 ssh_kex2(host, hostaddr, port);
1430 ssh_userauth2(local_user, server_user, host, sensitive);
1435 ssh_put_password(char *password)
1440 if (datafellows & SSH_BUG_PASSWORDPAD) {
1441 packet_put_cstring(password);
1444 size = ROUNDUP(strlen(password) + 1, 32);
1445 padded = xcalloc(1, size);
1446 strlcpy(padded, password, size);
1447 packet_put_string(padded, size);
1448 explicit_bzero(padded, size);
1452 /* print all known host keys for a given host, but skip keys of given type */
1454 show_other_keys(struct hostkeys *hostkeys, struct sshkey *key)
1466 const struct hostkey_entry *found;
1468 for (i = 0; type[i] != -1; i++) {
1469 if (type[i] == key->type)
1471 if (!lookup_key_in_hostkeys_by_type(hostkeys, type[i], &found))
1473 fp = sshkey_fingerprint(found->key,
1474 options.fingerprint_hash, SSH_FP_DEFAULT);
1475 ra = sshkey_fingerprint(found->key,
1476 options.fingerprint_hash, SSH_FP_RANDOMART);
1477 if (fp == NULL || ra == NULL)
1478 fatal("%s: sshkey_fingerprint fail", __func__);
1479 logit("WARNING: %s key found for host %s\n"
1481 "%s key fingerprint %s.",
1482 sshkey_type(found->key),
1483 found->host, found->file, found->line,
1484 sshkey_type(found->key), fp);
1485 if (options.visual_host_key)
1495 warn_changed_key(struct sshkey *host_key)
1499 fp = sshkey_fingerprint(host_key, options.fingerprint_hash,
1502 fatal("%s: sshkey_fingerprint fail", __func__);
1504 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1505 error("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @");
1506 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1507 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1508 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1509 error("It is also possible that a host key has just been changed.");
1510 error("The fingerprint for the %s key sent by the remote host is\n%s.",
1511 sshkey_type(host_key), fp);
1512 error("Please contact your system administrator.");
1518 * Execute a local command
1521 ssh_local_cmd(const char *args)
1526 void (*osighand)(int);
1528 if (!options.permit_local_command ||
1529 args == NULL || !*args)
1532 if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
1533 shell = _PATH_BSHELL;
1535 osighand = signal(SIGCHLD, SIG_DFL);
1538 signal(SIGPIPE, SIG_DFL);
1539 debug3("Executing %s -c \"%s\"", shell, args);
1540 execl(shell, shell, "-c", args, (char *)NULL);
1541 error("Couldn't execute %s -c \"%s\": %s",
1542 shell, args, strerror(errno));
1544 } else if (pid == -1)
1545 fatal("fork failed: %.100s", strerror(errno));
1546 while (waitpid(pid, &status, 0) == -1)
1548 fatal("Couldn't wait for child: %s", strerror(errno));
1549 signal(SIGCHLD, osighand);
1551 if (!WIFEXITED(status))
1554 return (WEXITSTATUS(status));
1558 maybe_add_key_to_agent(char *authfile, const struct sshkey *private,
1559 char *comment, char *passphrase)
1561 int auth_sock = -1, r;
1563 if (options.add_keys_to_agent == 0)
1566 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
1567 debug3("no authentication agent, not adding key");
1571 if (options.add_keys_to_agent == 2 &&
1572 !ask_permission("Add key %s (%s) to agent?", authfile, comment)) {
1573 debug3("user denied adding this key");
1578 if ((r = ssh_add_identity_constrained(auth_sock, private, comment, 0,
1579 (options.add_keys_to_agent == 3), 0)) == 0)
1580 debug("identity added to agent: %s", authfile);
1582 debug("could not add identity to agent: %s (%d)", authfile, r);