1 /* $OpenBSD: sshconnect.c,v 1.262 2015/05/28 05:41:29 dtucker 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/param.h> /* roundup */
20 #include <sys/types.h>
23 #include <sys/socket.h>
24 #ifdef HAVE_SYS_TIME_H
25 # include <sys/time.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
57 #include "sshconnect.h"
65 #include "monitor_fdpass.h"
71 char *client_version_string = NULL;
72 char *server_version_string = NULL;
73 Key *previous_host_key = NULL;
75 static int matching_host_key_dns = 0;
77 static pid_t proxy_command_pid = 0;
80 extern Options options;
81 extern char *__progname;
82 extern uid_t original_real_uid;
83 extern uid_t original_effective_uid;
85 static int show_other_keys(struct hostkeys *, Key *);
86 static void warn_changed_key(Key *);
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(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) {
131 /* Child. Permanently give up superuser privileges. */
132 permanently_drop_suid(original_real_uid);
135 /* Redirect stdin and stdout. */
137 if (dup2(sp[0], 0) < 0)
138 perror("dup2 stdin");
141 if (dup2(sp[0], 1) < 0)
142 perror("dup2 stdout");
148 * Stderr is left as it is so that error messages get
149 * printed on the user's terminal.
153 argv[2] = command_string;
157 * Execute the proxy command.
158 * Note that we gave up any extra privileges above.
160 execv(argv[0], argv);
166 fatal("fork failed: %.100s", strerror(errno));
168 free(command_string);
170 if ((sock = mm_receive_fd(sp[1])) == -1)
171 fatal("proxy dialer did not pass back a connection");
173 while (waitpid(pid, NULL, 0) == -1)
175 fatal("Couldn't wait for child: %s", strerror(errno));
177 /* Set the connection file descriptors. */
178 packet_set_connection(sock, sock);
184 * Connect to the given ssh server using a proxy command.
187 ssh_proxy_connect(const char *host, u_short port, 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 /* Child. Permanently give up superuser privileges. */
211 permanently_drop_suid(original_real_uid);
213 /* Redirect stdin and stdout. */
216 if (dup2(pin[0], 0) < 0)
217 perror("dup2 stdin");
221 if (dup2(pout[1], 1) < 0)
222 perror("dup2 stdout");
223 /* Cannot be 1 because pin allocated two descriptors. */
226 /* Stderr is left as it is so that error messages get
227 printed on the user's terminal. */
230 argv[2] = command_string;
233 /* Execute the proxy command. Note that we gave up any
234 extra privileges above. */
235 signal(SIGPIPE, SIG_DFL);
236 execv(argv[0], argv);
242 fatal("fork failed: %.100s", strerror(errno));
244 proxy_command_pid = pid; /* save pid to clean up later */
246 /* Close child side of the descriptors. */
250 /* Free the command name. */
251 free(command_string);
253 /* Set the connection file descriptors. */
254 packet_set_connection(pout[0], pin[1]);
256 /* Indicate OK return */
261 ssh_kill_proxy_command(void)
264 * Send SIGHUP to proxy command if used. We don't wait() in
265 * case it hangs and instead rely on init to reap the child
267 if (proxy_command_pid > 1)
268 kill(proxy_command_pid, SIGHUP);
272 * Creates a (possibly privileged) socket for use as the ssh connection.
275 ssh_create_socket(int privileged, struct addrinfo *ai)
278 struct addrinfo hints, *res = NULL;
280 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
282 error("socket: %s", strerror(errno));
285 fcntl(sock, F_SETFD, FD_CLOEXEC);
287 /* Bind the socket to an alternative local IP address */
288 if (options.bind_address == NULL && !privileged)
291 if (options.bind_address) {
292 memset(&hints, 0, sizeof(hints));
293 hints.ai_family = ai->ai_family;
294 hints.ai_socktype = ai->ai_socktype;
295 hints.ai_protocol = ai->ai_protocol;
296 hints.ai_flags = AI_PASSIVE;
297 gaierr = getaddrinfo(options.bind_address, NULL, &hints, &res);
299 error("getaddrinfo: %s: %s", options.bind_address,
300 ssh_gai_strerror(gaierr));
306 * If we are running as root and want to connect to a privileged
307 * port, bind our own socket to a privileged port.
311 r = bindresvport_sa(sock, res ? res->ai_addr : NULL);
314 error("bindresvport_sa: af=%d %s", ai->ai_family,
319 if (bind(sock, res->ai_addr, res->ai_addrlen) < 0) {
320 error("bind: %s: %s", options.bind_address,
334 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
335 socklen_t addrlen, int *timeoutp)
338 struct timeval tv, t_start;
340 int optval, rc, result = -1;
342 gettimeofday(&t_start, NULL);
344 if (*timeoutp <= 0) {
345 result = connect(sockfd, serv_addr, addrlen);
349 set_nonblock(sockfd);
350 rc = connect(sockfd, serv_addr, addrlen);
352 unset_nonblock(sockfd);
356 if (errno != EINPROGRESS) {
361 fdset = (fd_set *)xcalloc(howmany(sockfd + 1, NFDBITS),
363 FD_SET(sockfd, fdset);
364 ms_to_timeval(&tv, *timeoutp);
367 rc = select(sockfd + 1, NULL, fdset, NULL, &tv);
368 if (rc != -1 || errno != EINTR)
379 debug("select: %s", strerror(errno));
382 /* Completed or failed */
384 optlen = sizeof(optval);
385 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval,
387 debug("getsockopt: %s", strerror(errno));
395 unset_nonblock(sockfd);
398 /* Should not occur */
399 fatal("Bogus return (%d) from select()", rc);
405 if (result == 0 && *timeoutp > 0) {
406 ms_subtract_diff(&t_start, timeoutp);
407 if (*timeoutp <= 0) {
417 * Opens a TCP/IP connection to the remote server on the given host.
418 * The address of the remote host will be returned in hostaddr.
419 * If port is 0, the default port will be used. If needpriv is true,
420 * a privileged port will be allocated to make the connection.
421 * This requires super-user privileges if needpriv is true.
422 * Connection_attempts specifies the maximum number of tries (one per
423 * second). If proxy_command is non-NULL, it specifies the command (with %h
424 * and %p substituted for host and port, respectively) to use to contact
428 ssh_connect_direct(const char *host, struct addrinfo *aitop,
429 struct sockaddr_storage *hostaddr, u_short port, int family,
430 int connection_attempts, int *timeout_ms, int want_keepalive, int needpriv)
433 int sock = -1, attempt;
434 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
437 debug2("ssh_connect: needpriv %d", needpriv);
439 for (attempt = 0; attempt < connection_attempts; attempt++) {
441 /* Sleep a moment before retrying. */
443 debug("Trying again...");
446 * Loop through addresses for this host, and try each one in
447 * sequence until the connection succeeds.
449 for (ai = aitop; ai; ai = ai->ai_next) {
450 if (ai->ai_family != AF_INET &&
451 ai->ai_family != AF_INET6)
453 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
454 ntop, sizeof(ntop), strport, sizeof(strport),
455 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
456 error("ssh_connect: getnameinfo failed");
459 debug("Connecting to %.200s [%.100s] port %s.",
460 host, ntop, strport);
462 /* Create a socket for connecting. */
463 sock = ssh_create_socket(needpriv, ai);
465 /* Any error is already output */
468 if (timeout_connect(sock, ai->ai_addr, ai->ai_addrlen,
470 /* Successful connection. */
471 memcpy(hostaddr, ai->ai_addr, ai->ai_addrlen);
474 debug("connect to address %s port %s: %s",
475 ntop, strport, strerror(errno));
481 break; /* Successful connection. */
484 /* Return failure if we didn't get a successful connection. */
486 error("ssh: connect to host %s port %s: %s",
487 host, strport, strerror(errno));
491 debug("Connection established.");
493 /* Set SO_KEEPALIVE if requested. */
494 if (want_keepalive &&
495 setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
497 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
499 /* Set the connection. */
500 packet_set_connection(sock, sock);
506 ssh_connect(const char *host, struct addrinfo *addrs,
507 struct sockaddr_storage *hostaddr, u_short port, int family,
508 int connection_attempts, int *timeout_ms, int want_keepalive, int needpriv)
510 if (options.proxy_command == NULL) {
511 return ssh_connect_direct(host, addrs, hostaddr, port, family,
512 connection_attempts, timeout_ms, want_keepalive, needpriv);
513 } else if (strcmp(options.proxy_command, "-") == 0) {
514 packet_set_connection(STDIN_FILENO, STDOUT_FILENO);
515 return 0; /* Always succeeds */
516 } else if (options.proxy_use_fdpass) {
517 return ssh_proxy_fdpass_connect(host, port,
518 options.proxy_command);
520 return ssh_proxy_connect(host, port, options.proxy_command);
524 send_client_banner(int connection_out, int minor1)
526 /* Send our own protocol version identification. */
527 xasprintf(&client_version_string, "SSH-%d.%d-%.100s%s%s%s",
528 compat20 ? PROTOCOL_MAJOR_2 : PROTOCOL_MAJOR_1,
529 compat20 ? PROTOCOL_MINOR_2 : minor1,
531 *options.version_addendum == '\0' ? "" : " ",
532 options.version_addendum, compat20 ? "\r\n" : "\n");
533 if (roaming_atomicio(vwrite, connection_out, client_version_string,
534 strlen(client_version_string)) != strlen(client_version_string))
535 fatal("write: %.100s", strerror(errno));
536 chop(client_version_string);
537 debug("Local version string %.100s", client_version_string);
541 * Waits for the server identification string, and sends our own
542 * identification string.
545 ssh_exchange_identification(int timeout_ms)
547 char buf[256], remote_version[256]; /* must be same size! */
548 int remote_major, remote_minor, mismatch;
549 int connection_in = packet_get_connection_in();
550 int connection_out = packet_get_connection_out();
551 int minor1 = PROTOCOL_MINOR_1, client_banner_sent = 0;
554 int fdsetsz, remaining, rc;
555 struct timeval t_start, t_remaining;
558 fdsetsz = howmany(connection_in + 1, NFDBITS) * sizeof(fd_mask);
559 fdset = xcalloc(1, fdsetsz);
562 * If we are SSH2-only then we can send the banner immediately and
565 if (options.protocol == SSH_PROTO_2) {
567 send_client_banner(connection_out, 0);
568 client_banner_sent = 1;
571 /* Read other side's version identification. */
572 remaining = timeout_ms;
574 for (i = 0; i < sizeof(buf) - 1; i++) {
575 if (timeout_ms > 0) {
576 gettimeofday(&t_start, NULL);
577 ms_to_timeval(&t_remaining, remaining);
578 FD_SET(connection_in, fdset);
579 rc = select(connection_in + 1, fdset, NULL,
580 fdset, &t_remaining);
581 ms_subtract_diff(&t_start, &remaining);
582 if (rc == 0 || remaining <= 0)
583 fatal("Connection timed out during "
588 fatal("ssh_exchange_identification: "
589 "select: %s", strerror(errno));
593 len = roaming_atomicio(read, connection_in, &buf[i], 1);
595 if (len != 1 && errno == EPIPE)
596 fatal("ssh_exchange_identification: "
597 "Connection closed by remote host");
599 fatal("ssh_exchange_identification: "
600 "read: %.100s", strerror(errno));
601 if (buf[i] == '\r') {
604 continue; /**XXX wait for \n */
606 if (buf[i] == '\n') {
611 fatal("ssh_exchange_identification: "
612 "No banner received");
614 buf[sizeof(buf) - 1] = 0;
615 if (strncmp(buf, "SSH-", 4) == 0)
617 debug("ssh_exchange_identification: %s", buf);
619 server_version_string = xstrdup(buf);
623 * Check that the versions match. In future this might accept
624 * several versions and set appropriate flags to handle them.
626 if (sscanf(server_version_string, "SSH-%d.%d-%[^\n]\n",
627 &remote_major, &remote_minor, remote_version) != 3)
628 fatal("Bad remote protocol version identification: '%.100s'", buf);
629 debug("Remote protocol version %d.%d, remote software version %.100s",
630 remote_major, remote_minor, remote_version);
632 active_state->compat = compat_datafellows(remote_version);
635 switch (remote_major) {
637 if (remote_minor == 99 &&
638 (options.protocol & SSH_PROTO_2) &&
639 !(options.protocol & SSH_PROTO_1_PREFERRED)) {
643 if (!(options.protocol & SSH_PROTO_1)) {
647 if (remote_minor < 3) {
648 fatal("Remote machine has too old SSH software version.");
649 } else if (remote_minor == 3 || remote_minor == 4) {
650 /* We speak 1.3, too. */
653 if (options.forward_agent) {
654 logit("Agent forwarding disabled for protocol 1.3");
655 options.forward_agent = 0;
660 if (options.protocol & SSH_PROTO_2) {
670 fatal("Protocol major versions differ: %d vs. %d",
671 (options.protocol & SSH_PROTO_2) ? PROTOCOL_MAJOR_2 : PROTOCOL_MAJOR_1,
673 if ((datafellows & SSH_BUG_DERIVEKEY) != 0)
674 fatal("Server version \"%.100s\" uses unsafe key agreement; "
675 "refusing connection", remote_version);
676 if ((datafellows & SSH_BUG_RSASIGMD5) != 0)
677 logit("Server version \"%.100s\" uses unsafe RSA signature "
678 "scheme; disabling use of RSA keys", remote_version);
679 if (!client_banner_sent)
680 send_client_banner(connection_out, minor1);
681 chop(server_version_string);
684 /* defaults to 'no' */
686 confirm(const char *prompt)
688 const char *msg, *again = "Please type 'yes' or 'no': ";
692 if (options.batch_mode)
694 for (msg = prompt;;msg = again) {
695 p = read_passphrase(msg, RP_ECHO);
697 (p[0] == '\0') || (p[0] == '\n') ||
698 strncasecmp(p, "no", 2) == 0)
700 if (p && strncasecmp(p, "yes", 3) == 0)
709 check_host_cert(const char *host, const Key *host_key)
713 if (key_cert_check_authority(host_key, 1, 0, host, &reason) != 0) {
717 if (buffer_len(host_key->cert->critical) != 0) {
718 error("Certificate for %s contains unsupported "
719 "critical options(s)", host);
726 sockaddr_is_local(struct sockaddr *hostaddr)
728 switch (hostaddr->sa_family) {
730 return (ntohl(((struct sockaddr_in *)hostaddr)->
731 sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
733 return IN6_IS_ADDR_LOOPBACK(
734 &(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
741 * Prepare the hostname and ip address strings that are used to lookup
742 * host keys in known_hosts files. These may have a port number appended.
745 get_hostfile_hostname_ipaddr(char *hostname, struct sockaddr *hostaddr,
746 u_short port, char **hostfile_hostname, char **hostfile_ipaddr)
748 char ntop[NI_MAXHOST];
751 switch (hostaddr == NULL ? -1 : hostaddr->sa_family) {
756 addrlen = sizeof(struct sockaddr_in);
759 addrlen = sizeof(struct sockaddr_in6);
762 addrlen = sizeof(struct sockaddr);
767 * We don't have the remote ip-address for connections
768 * using a proxy command
770 if (hostfile_ipaddr != NULL) {
771 if (options.proxy_command == NULL) {
772 if (getnameinfo(hostaddr, addrlen,
773 ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST) != 0)
774 fatal("%s: getnameinfo failed", __func__);
775 *hostfile_ipaddr = put_host_port(ntop, port);
777 *hostfile_ipaddr = xstrdup("<no hostip for proxy "
783 * Allow the user to record the key under a different name or
784 * differentiate a non-standard port. This is useful for ssh
785 * tunneling over forwarded connections or if you run multiple
786 * sshd's on different ports on the same machine.
788 if (hostfile_hostname != NULL) {
789 if (options.host_key_alias != NULL) {
790 *hostfile_hostname = xstrdup(options.host_key_alias);
791 debug("using hostkeyalias: %s", *hostfile_hostname);
793 *hostfile_hostname = put_host_port(hostname, port);
799 * check whether the supplied host key is valid, return -1 if the key
800 * is not valid. user_hostfile[0] will not be updated if 'readonly' is true.
806 check_host_key(char *hostname, struct sockaddr *hostaddr, u_short port,
807 Key *host_key, int readonly,
808 char **user_hostfiles, u_int num_user_hostfiles,
809 char **system_hostfiles, u_int num_system_hostfiles)
811 HostStatus host_status;
812 HostStatus ip_status;
814 char *ip = NULL, *host = NULL;
815 char hostline[1000], *hostp, *fp, *ra;
818 const struct hostkey_entry *host_found, *ip_found;
819 int len, cancelled_forwarding = 0;
820 int local = sockaddr_is_local(hostaddr);
821 int r, want_cert = key_is_cert(host_key), host_ip_differ = 0;
822 int hostkey_trusted = 0; /* Known or explicitly accepted by user */
823 struct hostkeys *host_hostkeys, *ip_hostkeys;
827 * Force accepting of the host key for loopback/localhost. The
828 * problem is that if the home directory is NFS-mounted to multiple
829 * machines, localhost will refer to a different machine in each of
830 * them, and the user will get bogus HOST_CHANGED warnings. This
831 * essentially disables host authentication for localhost; however,
832 * this is probably not a real problem.
834 if (options.no_host_authentication_for_localhost == 1 && local &&
835 options.host_key_alias == NULL) {
836 debug("Forcing accepting of host key for "
837 "loopback/localhost.");
842 * Prepare the hostname and address strings used for hostkey lookup.
843 * In some cases, these will have a port number appended.
845 get_hostfile_hostname_ipaddr(hostname, hostaddr, port, &host, &ip);
848 * Turn off check_host_ip if the connection is to localhost, via proxy
849 * command or if we don't have a hostname to compare with
851 if (options.check_host_ip && (local ||
852 strcmp(hostname, ip) == 0 || options.proxy_command != NULL))
853 options.check_host_ip = 0;
855 host_hostkeys = init_hostkeys();
856 for (i = 0; i < num_user_hostfiles; i++)
857 load_hostkeys(host_hostkeys, host, user_hostfiles[i]);
858 for (i = 0; i < num_system_hostfiles; i++)
859 load_hostkeys(host_hostkeys, host, system_hostfiles[i]);
862 if (!want_cert && options.check_host_ip) {
863 ip_hostkeys = init_hostkeys();
864 for (i = 0; i < num_user_hostfiles; i++)
865 load_hostkeys(ip_hostkeys, ip, user_hostfiles[i]);
866 for (i = 0; i < num_system_hostfiles; i++)
867 load_hostkeys(ip_hostkeys, ip, system_hostfiles[i]);
871 /* Reload these as they may have changed on cert->key downgrade */
872 want_cert = key_is_cert(host_key);
873 type = key_type(host_key);
876 * Check if the host key is present in the user's list of known
877 * hosts or in the systemwide list.
879 host_status = check_key_in_hostkeys(host_hostkeys, host_key,
883 * Also perform check for the ip address, skip the check if we are
884 * localhost, looking for a certificate, or the hostname was an ip
885 * address to begin with.
887 if (!want_cert && ip_hostkeys != NULL) {
888 ip_status = check_key_in_hostkeys(ip_hostkeys, host_key,
890 if (host_status == HOST_CHANGED &&
891 (ip_status != HOST_CHANGED ||
893 !key_equal(ip_found->key, host_found->key))))
896 ip_status = host_status;
898 switch (host_status) {
900 /* The host is known and the key matches. */
901 debug("Host '%.200s' is known and matches the %s host %s.",
902 host, type, want_cert ? "certificate" : "key");
903 debug("Found %s in %s:%lu", want_cert ? "CA key" : "key",
904 host_found->file, host_found->line);
905 if (want_cert && !check_host_cert(hostname, host_key))
907 if (options.check_host_ip && ip_status == HOST_NEW) {
908 if (readonly || want_cert)
909 logit("%s host key for IP address "
910 "'%.128s' not in list of known hosts.",
912 else if (!add_host_to_hostfile(user_hostfiles[0], ip,
913 host_key, options.hash_known_hosts))
914 logit("Failed to add the %s host key for IP "
915 "address '%.128s' to the list of known "
916 "hosts (%.500s).", type, ip,
919 logit("Warning: Permanently added the %s host "
920 "key for IP address '%.128s' to the list "
921 "of known hosts.", type, ip);
922 } else if (options.visual_host_key) {
923 fp = sshkey_fingerprint(host_key,
924 options.fingerprint_hash, SSH_FP_DEFAULT);
925 ra = sshkey_fingerprint(host_key,
926 options.fingerprint_hash, SSH_FP_RANDOMART);
927 if (fp == NULL || ra == NULL)
928 fatal("%s: sshkey_fingerprint fail", __func__);
929 logit("Host key fingerprint is %s\n%s\n", fp, ra);
936 if (options.host_key_alias == NULL && port != 0 &&
937 port != SSH_DEFAULT_PORT) {
938 debug("checking without port identifier");
939 if (check_host_key(hostname, hostaddr, 0, host_key,
940 ROQUIET, user_hostfiles, num_user_hostfiles,
941 system_hostfiles, num_system_hostfiles) == 0) {
942 debug("found matching key w/out port");
946 if (readonly || want_cert)
948 /* The host is new. */
949 if (options.strict_host_key_checking == 1) {
951 * User has requested strict host key checking. We
952 * will not add the host key automatically. The only
953 * alternative left is to abort.
955 error("No %s host key is known for %.200s and you "
956 "have requested strict checking.", type, host);
958 } else if (options.strict_host_key_checking == 2) {
959 char msg1[1024], msg2[1024];
961 if (show_other_keys(host_hostkeys, host_key))
962 snprintf(msg1, sizeof(msg1),
963 "\nbut keys of different type are already"
964 " known for this host.");
966 snprintf(msg1, sizeof(msg1), ".");
968 fp = sshkey_fingerprint(host_key,
969 options.fingerprint_hash, SSH_FP_DEFAULT);
970 ra = sshkey_fingerprint(host_key,
971 options.fingerprint_hash, SSH_FP_RANDOMART);
972 if (fp == NULL || ra == NULL)
973 fatal("%s: sshkey_fingerprint fail", __func__);
975 if (options.verify_host_key_dns) {
976 if (matching_host_key_dns)
977 snprintf(msg2, sizeof(msg2),
978 "Matching host key fingerprint"
981 snprintf(msg2, sizeof(msg2),
982 "No matching host key fingerprint"
985 snprintf(msg, sizeof(msg),
986 "The authenticity of host '%.200s (%s)' can't be "
988 "%s key fingerprint is %s.%s%s\n%s"
989 "Are you sure you want to continue connecting "
991 host, ip, msg1, type, fp,
992 options.visual_host_key ? "\n" : "",
993 options.visual_host_key ? ra : "",
999 hostkey_trusted = 1; /* user explicitly confirmed */
1002 * If not in strict mode, add the key automatically to the
1003 * local known_hosts file.
1005 if (options.check_host_ip && ip_status == HOST_NEW) {
1006 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1008 if (options.hash_known_hosts) {
1009 /* Add hash of host and IP separately */
1010 r = add_host_to_hostfile(user_hostfiles[0],
1011 host, host_key, options.hash_known_hosts) &&
1012 add_host_to_hostfile(user_hostfiles[0], ip,
1013 host_key, options.hash_known_hosts);
1015 /* Add unhashed "host,ip" */
1016 r = add_host_to_hostfile(user_hostfiles[0],
1018 options.hash_known_hosts);
1021 r = add_host_to_hostfile(user_hostfiles[0], host,
1022 host_key, options.hash_known_hosts);
1027 logit("Failed to add the host to the list of known "
1028 "hosts (%.500s).", user_hostfiles[0]);
1030 logit("Warning: Permanently added '%.200s' (%s) to the "
1031 "list of known hosts.", hostp, type);
1034 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1035 error("@ WARNING: REVOKED HOST KEY DETECTED! @");
1036 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1037 error("The %s host key for %s is marked as revoked.", type, host);
1038 error("This could mean that a stolen key is being used to");
1039 error("impersonate this host.");
1042 * If strict host key checking is in use, the user will have
1043 * to edit the key manually and we can only abort.
1045 if (options.strict_host_key_checking) {
1046 error("%s host key for %.200s was revoked and you have "
1047 "requested strict checking.", type, host);
1050 goto continue_unsafe;
1055 * This is only a debug() since it is valid to have
1056 * CAs with wildcard DNS matches that don't match
1057 * all hosts that one might visit.
1059 debug("Host certificate authority does not "
1060 "match %s in %s:%lu", CA_MARKER,
1061 host_found->file, host_found->line);
1064 if (readonly == ROQUIET)
1066 if (options.check_host_ip && host_ip_differ) {
1068 if (ip_status == HOST_NEW)
1069 key_msg = "is unknown";
1070 else if (ip_status == HOST_OK)
1071 key_msg = "is unchanged";
1073 key_msg = "has a different value";
1074 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1075 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1076 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1077 error("The %s host key for %s has changed,", type, host);
1078 error("and the key for the corresponding IP address %s", ip);
1079 error("%s. This could either mean that", key_msg);
1080 error("DNS SPOOFING is happening or the IP address for the host");
1081 error("and its host key have changed at the same time.");
1082 if (ip_status != HOST_NEW)
1083 error("Offending key for IP in %s:%lu",
1084 ip_found->file, ip_found->line);
1086 /* The host key has changed. */
1087 warn_changed_key(host_key);
1088 error("Add correct host key in %.100s to get rid of this message.",
1090 error("Offending %s key in %s:%lu", key_type(host_found->key),
1091 host_found->file, host_found->line);
1094 * If strict host key checking is in use, the user will have
1095 * to edit the key manually and we can only abort.
1097 if (options.strict_host_key_checking) {
1098 error("%s host key for %.200s has changed and you have "
1099 "requested strict checking.", type, host);
1105 * If strict host key checking has not been requested, allow
1106 * the connection but without MITM-able authentication or
1109 if (options.password_authentication) {
1110 error("Password authentication is disabled to avoid "
1111 "man-in-the-middle attacks.");
1112 options.password_authentication = 0;
1113 cancelled_forwarding = 1;
1115 if (options.kbd_interactive_authentication) {
1116 error("Keyboard-interactive authentication is disabled"
1117 " to avoid man-in-the-middle attacks.");
1118 options.kbd_interactive_authentication = 0;
1119 options.challenge_response_authentication = 0;
1120 cancelled_forwarding = 1;
1122 if (options.challenge_response_authentication) {
1123 error("Challenge/response authentication is disabled"
1124 " to avoid man-in-the-middle attacks.");
1125 options.challenge_response_authentication = 0;
1126 cancelled_forwarding = 1;
1128 if (options.forward_agent) {
1129 error("Agent forwarding is disabled to avoid "
1130 "man-in-the-middle attacks.");
1131 options.forward_agent = 0;
1132 cancelled_forwarding = 1;
1134 if (options.forward_x11) {
1135 error("X11 forwarding is disabled to avoid "
1136 "man-in-the-middle attacks.");
1137 options.forward_x11 = 0;
1138 cancelled_forwarding = 1;
1140 if (options.num_local_forwards > 0 ||
1141 options.num_remote_forwards > 0) {
1142 error("Port forwarding is disabled to avoid "
1143 "man-in-the-middle attacks.");
1144 options.num_local_forwards =
1145 options.num_remote_forwards = 0;
1146 cancelled_forwarding = 1;
1148 if (options.tun_open != SSH_TUNMODE_NO) {
1149 error("Tunnel forwarding is disabled to avoid "
1150 "man-in-the-middle attacks.");
1151 options.tun_open = SSH_TUNMODE_NO;
1152 cancelled_forwarding = 1;
1154 if (options.exit_on_forward_failure && cancelled_forwarding)
1155 fatal("Error: forwarding disabled due to host key "
1159 * XXX Should permit the user to change to use the new id.
1160 * This could be done by converting the host key to an
1161 * identifying sentence, tell that the host identifies itself
1162 * by that sentence, and ask the user if he/she wishes to
1163 * accept the authentication.
1167 fatal("internal error");
1171 if (options.check_host_ip && host_status != HOST_CHANGED &&
1172 ip_status == HOST_CHANGED) {
1173 snprintf(msg, sizeof(msg),
1174 "Warning: the %s host key for '%.200s' "
1175 "differs from the key for the IP address '%.128s'"
1176 "\nOffending key for IP in %s:%lu",
1177 type, host, ip, ip_found->file, ip_found->line);
1178 if (host_status == HOST_OK) {
1180 snprintf(msg + len, sizeof(msg) - len,
1181 "\nMatching host key in %s:%lu",
1182 host_found->file, host_found->line);
1184 if (options.strict_host_key_checking == 1) {
1186 error("Exiting, you have requested strict checking.");
1188 } else if (options.strict_host_key_checking == 2) {
1189 strlcat(msg, "\nAre you sure you want "
1190 "to continue connecting (yes/no)? ", sizeof(msg));
1198 if (!hostkey_trusted && options.update_hostkeys) {
1199 debug("%s: hostkey not known or explicitly trusted: "
1200 "disabling UpdateHostkeys", __func__);
1201 options.update_hostkeys = 0;
1206 if (host_hostkeys != NULL)
1207 free_hostkeys(host_hostkeys);
1208 if (ip_hostkeys != NULL)
1209 free_hostkeys(ip_hostkeys);
1213 if (want_cert && host_status != HOST_REVOKED) {
1215 * No matching certificate. Downgrade cert to raw key and
1218 debug("No matching CA found. Retry with plain key");
1219 raw_key = key_from_private(host_key);
1220 if (key_drop_cert(raw_key) != 0)
1221 fatal("Couldn't drop certificate");
1225 if (raw_key != NULL)
1229 if (host_hostkeys != NULL)
1230 free_hostkeys(host_hostkeys);
1231 if (ip_hostkeys != NULL)
1232 free_hostkeys(ip_hostkeys);
1236 /* returns 0 if key verifies or -1 if key does NOT verify */
1238 verify_host_key(char *host, struct sockaddr *hostaddr, Key *host_key)
1240 int r = -1, flags = 0;
1242 struct sshkey *plain = NULL;
1244 if ((fp = sshkey_fingerprint(host_key,
1245 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
1246 error("%s: fingerprint host key: %s", __func__, ssh_err(r));
1251 debug("Server host key: %s %s",
1252 compat20 ? sshkey_ssh_name(host_key) : sshkey_type(host_key), fp);
1254 if (sshkey_equal(previous_host_key, host_key)) {
1255 debug2("%s: server host key %s %s matches cached key",
1256 __func__, sshkey_type(host_key), fp);
1261 /* Check in RevokedHostKeys file if specified */
1262 if (options.revoked_host_keys != NULL) {
1263 r = sshkey_check_revoked(host_key, options.revoked_host_keys);
1266 break; /* not revoked */
1267 case SSH_ERR_KEY_REVOKED:
1268 error("Host key %s %s revoked by file %s",
1269 sshkey_type(host_key), fp,
1270 options.revoked_host_keys);
1274 error("Error checking host key %s %s in "
1275 "revoked keys file %s: %s", sshkey_type(host_key),
1276 fp, options.revoked_host_keys, ssh_err(r));
1282 if (options.verify_host_key_dns) {
1284 * XXX certs are not yet supported for DNS, so downgrade
1285 * them and try the plain key.
1287 if ((r = sshkey_from_private(host_key, &plain)) != 0)
1289 if (sshkey_is_cert(plain))
1290 sshkey_drop_cert(plain);
1291 if (verify_host_key_dns(host, hostaddr, plain, &flags) == 0) {
1292 if (flags & DNS_VERIFY_FOUND) {
1293 if (options.verify_host_key_dns == 1 &&
1294 flags & DNS_VERIFY_MATCH &&
1295 flags & DNS_VERIFY_SECURE) {
1299 if (flags & DNS_VERIFY_MATCH) {
1300 matching_host_key_dns = 1;
1302 warn_changed_key(plain);
1303 error("Update the SSHFP RR in DNS "
1304 "with the new host key to get rid "
1305 "of this message.");
1310 r = check_host_key(host, hostaddr, options.port, host_key, RDRW,
1311 options.user_hostfiles, options.num_user_hostfiles,
1312 options.system_hostfiles, options.num_system_hostfiles);
1317 if (r == 0 && host_key != NULL) {
1318 key_free(previous_host_key);
1319 previous_host_key = key_from_private(host_key);
1326 * Starts a dialog with the server, and authenticates the current user on the
1327 * server. This does not need any extra privileges. The basic connection
1328 * to the server must already have been established before this is called.
1329 * If login fails, this function prints an error and never returns.
1330 * This function does not require super-user privileges.
1333 ssh_login(Sensitive *sensitive, const char *orighost,
1334 struct sockaddr *hostaddr, u_short port, struct passwd *pw, int timeout_ms)
1337 char *server_user, *local_user;
1339 local_user = xstrdup(pw->pw_name);
1340 server_user = options.user ? options.user : local_user;
1342 /* Convert the user-supplied hostname into all lowercase. */
1343 host = xstrdup(orighost);
1346 /* Exchange protocol version identification strings with the server. */
1347 ssh_exchange_identification(timeout_ms);
1349 /* Put the connection into non-blocking mode. */
1350 packet_set_nonblocking();
1353 /* authenticate user */
1354 debug("Authenticating to %s:%d as '%s'", host, port, server_user);
1356 ssh_kex2(host, hostaddr, port);
1357 ssh_userauth2(local_user, server_user, host, sensitive);
1360 ssh_kex(host, hostaddr);
1361 ssh_userauth1(local_user, server_user, host, sensitive);
1363 fatal("ssh1 is not supported");
1370 ssh_put_password(char *password)
1375 if (datafellows & SSH_BUG_PASSWORDPAD) {
1376 packet_put_cstring(password);
1379 size = roundup(strlen(password) + 1, 32);
1380 padded = xcalloc(1, size);
1381 strlcpy(padded, password, size);
1382 packet_put_string(padded, size);
1383 explicit_bzero(padded, size);
1387 /* print all known host keys for a given host, but skip keys of given type */
1389 show_other_keys(struct hostkeys *hostkeys, Key *key)
1401 const struct hostkey_entry *found;
1403 for (i = 0; type[i] != -1; i++) {
1404 if (type[i] == key->type)
1406 if (!lookup_key_in_hostkeys_by_type(hostkeys, type[i], &found))
1408 fp = sshkey_fingerprint(found->key,
1409 options.fingerprint_hash, SSH_FP_DEFAULT);
1410 ra = sshkey_fingerprint(found->key,
1411 options.fingerprint_hash, SSH_FP_RANDOMART);
1412 if (fp == NULL || ra == NULL)
1413 fatal("%s: sshkey_fingerprint fail", __func__);
1414 logit("WARNING: %s key found for host %s\n"
1416 "%s key fingerprint %s.",
1417 key_type(found->key),
1418 found->host, found->file, found->line,
1419 key_type(found->key), fp);
1420 if (options.visual_host_key)
1430 warn_changed_key(Key *host_key)
1434 fp = sshkey_fingerprint(host_key, options.fingerprint_hash,
1437 fatal("%s: sshkey_fingerprint fail", __func__);
1439 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1440 error("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @");
1441 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1442 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1443 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1444 error("It is also possible that a host key has just been changed.");
1445 error("The fingerprint for the %s key sent by the remote host is\n%s.",
1446 key_type(host_key), fp);
1447 error("Please contact your system administrator.");
1453 * Execute a local command
1456 ssh_local_cmd(const char *args)
1461 void (*osighand)(int);
1463 if (!options.permit_local_command ||
1464 args == NULL || !*args)
1467 if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
1468 shell = _PATH_BSHELL;
1470 osighand = signal(SIGCHLD, SIG_DFL);
1473 signal(SIGPIPE, SIG_DFL);
1474 debug3("Executing %s -c \"%s\"", shell, args);
1475 execl(shell, shell, "-c", args, (char *)NULL);
1476 error("Couldn't execute %s -c \"%s\": %s",
1477 shell, args, strerror(errno));
1479 } else if (pid == -1)
1480 fatal("fork failed: %.100s", strerror(errno));
1481 while (waitpid(pid, &status, 0) == -1)
1483 fatal("Couldn't wait for child: %s", strerror(errno));
1484 signal(SIGCHLD, osighand);
1486 if (!WIFEXITED(status))
1489 return (WEXITSTATUS(status));