1 /* $OpenBSD: sshconnect.c,v 1.246 2014/02/06 22:21:01 djm Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * Code to connect to a remote host, and to perform the client side of the
8 * login (authentication) dialog.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
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"
69 char *client_version_string = NULL;
70 char *server_version_string = NULL;
72 static int matching_host_key_dns = 0;
74 static pid_t proxy_command_pid = 0;
77 extern Options options;
78 extern char *__progname;
79 extern uid_t original_real_uid;
80 extern uid_t original_effective_uid;
82 static int show_other_keys(struct hostkeys *, Key *);
83 static void warn_changed_key(Key *);
85 /* Expand a proxy command */
87 expand_proxy_command(const char *proxy_command, const char *user,
88 const char *host, int port)
90 char *tmp, *ret, strport[NI_MAXSERV];
92 snprintf(strport, sizeof strport, "%d", port);
93 xasprintf(&tmp, "exec %s", proxy_command);
94 ret = percent_expand(tmp, "h", host, "p", strport,
95 "r", options.user, (char *)NULL);
101 * Connect to the given ssh server using a proxy command that passes a
102 * a connected fd back to us.
105 ssh_proxy_fdpass_connect(const char *host, u_short port,
106 const char *proxy_command)
108 char *command_string;
113 if ((shell = getenv("SHELL")) == NULL)
114 shell = _PATH_BSHELL;
116 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sp) < 0)
117 fatal("Could not create socketpair to communicate with "
118 "proxy dialer: %.100s", strerror(errno));
120 command_string = expand_proxy_command(proxy_command, options.user,
122 debug("Executing proxy dialer command: %.500s", command_string);
124 /* Fork and execute the proxy command. */
125 if ((pid = fork()) == 0) {
128 /* Child. Permanently give up superuser privileges. */
129 permanently_drop_suid(original_real_uid);
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");
170 while (waitpid(pid, NULL, 0) == -1)
172 fatal("Couldn't wait for child: %s", strerror(errno));
174 /* Set the connection file descriptors. */
175 packet_set_connection(sock, sock);
181 * Connect to the given ssh server using a proxy command.
184 ssh_proxy_connect(const char *host, u_short port, const char *proxy_command)
186 char *command_string;
191 if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
192 shell = _PATH_BSHELL;
194 /* Create pipes for communicating with the proxy. */
195 if (pipe(pin) < 0 || pipe(pout) < 0)
196 fatal("Could not create pipes to communicate with the proxy: %.100s",
199 command_string = expand_proxy_command(proxy_command, options.user,
201 debug("Executing proxy command: %.500s", command_string);
203 /* Fork and execute the proxy command. */
204 if ((pid = fork()) == 0) {
207 /* Child. Permanently give up superuser privileges. */
208 permanently_drop_suid(original_real_uid);
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 packet_set_connection(pout[0], pin[1]);
253 /* Indicate OK return */
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);
269 * Set TCP receive buffer if requested.
270 * Note: tuning needs to happen after the socket is created but before the
271 * connection happens so winscale is negotiated properly.
274 ssh_set_socket_recvbuf(int sock)
276 void *buf = (void *)&options.tcp_rcv_buf;
277 int socksize, sz = sizeof(options.tcp_rcv_buf);
278 socklen_t len = sizeof(int);
280 debug("setsockopt attempting to set SO_RCVBUF to %d",
281 options.tcp_rcv_buf);
282 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, buf, sz) >= 0) {
283 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &socksize, &len);
284 debug("setsockopt SO_RCVBUF: %.100s %d", strerror(errno),
287 error("Couldn't set socket receive buffer to %d: %.100s",
288 options.tcp_rcv_buf, strerror(errno));
292 * Creates a (possibly privileged) socket for use as the ssh connection.
295 ssh_create_socket(int privileged, struct addrinfo *ai)
298 struct addrinfo hints, *res = NULL;
300 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
302 error("socket: %s", strerror(errno));
305 fcntl(sock, F_SETFD, FD_CLOEXEC);
307 if (options.tcp_rcv_buf > 0)
308 ssh_set_socket_recvbuf(sock);
310 /* Bind the socket to an alternative local IP address */
311 if (options.bind_address == NULL && !privileged)
314 if (options.bind_address) {
315 memset(&hints, 0, sizeof(hints));
316 hints.ai_family = ai->ai_family;
317 hints.ai_socktype = ai->ai_socktype;
318 hints.ai_protocol = ai->ai_protocol;
319 hints.ai_flags = AI_PASSIVE;
320 gaierr = getaddrinfo(options.bind_address, NULL, &hints, &res);
322 error("getaddrinfo: %s: %s", options.bind_address,
323 ssh_gai_strerror(gaierr));
329 * If we are running as root and want to connect to a privileged
330 * port, bind our own socket to a privileged port.
334 r = bindresvport_sa(sock, res ? res->ai_addr : NULL);
337 error("bindresvport_sa: af=%d %s", ai->ai_family,
342 if (bind(sock, res->ai_addr, res->ai_addrlen) < 0) {
343 error("bind: %s: %s", options.bind_address,
357 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
358 socklen_t addrlen, int *timeoutp)
361 struct timeval tv, t_start;
363 int optval, rc, result = -1;
365 gettimeofday(&t_start, NULL);
367 if (*timeoutp <= 0) {
368 result = connect(sockfd, serv_addr, addrlen);
372 set_nonblock(sockfd);
373 rc = connect(sockfd, serv_addr, addrlen);
375 unset_nonblock(sockfd);
379 if (errno != EINPROGRESS) {
384 fdset = (fd_set *)xcalloc(howmany(sockfd + 1, NFDBITS),
386 FD_SET(sockfd, fdset);
387 ms_to_timeval(&tv, *timeoutp);
390 rc = select(sockfd + 1, NULL, fdset, NULL, &tv);
391 if (rc != -1 || errno != EINTR)
402 debug("select: %s", strerror(errno));
405 /* Completed or failed */
407 optlen = sizeof(optval);
408 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval,
410 debug("getsockopt: %s", strerror(errno));
418 unset_nonblock(sockfd);
421 /* Should not occur */
422 fatal("Bogus return (%d) from select()", rc);
428 if (result == 0 && *timeoutp > 0) {
429 ms_subtract_diff(&t_start, timeoutp);
430 if (*timeoutp <= 0) {
440 * Opens a TCP/IP connection to the remote server on the given host.
441 * The address of the remote host will be returned in hostaddr.
442 * If port is 0, the default port will be used. If needpriv is true,
443 * a privileged port will be allocated to make the connection.
444 * This requires super-user privileges if needpriv is true.
445 * Connection_attempts specifies the maximum number of tries (one per
446 * second). If proxy_command is non-NULL, it specifies the command (with %h
447 * and %p substituted for host and port, respectively) to use to contact
451 ssh_connect_direct(const char *host, struct addrinfo *aitop,
452 struct sockaddr_storage *hostaddr, u_short port, int family,
453 int connection_attempts, int *timeout_ms, int want_keepalive, int needpriv)
456 int sock = -1, attempt;
457 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
460 debug2("ssh_connect: needpriv %d", needpriv);
462 for (attempt = 0; attempt < connection_attempts; attempt++) {
464 /* Sleep a moment before retrying. */
466 debug("Trying again...");
469 * Loop through addresses for this host, and try each one in
470 * sequence until the connection succeeds.
472 for (ai = aitop; ai; ai = ai->ai_next) {
473 if (ai->ai_family != AF_INET &&
474 ai->ai_family != AF_INET6)
476 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
477 ntop, sizeof(ntop), strport, sizeof(strport),
478 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
479 error("ssh_connect: getnameinfo failed");
482 debug("Connecting to %.200s [%.100s] port %s.",
483 host, ntop, strport);
485 /* Create a socket for connecting. */
486 sock = ssh_create_socket(needpriv, ai);
488 /* Any error is already output */
491 if (timeout_connect(sock, ai->ai_addr, ai->ai_addrlen,
493 /* Successful connection. */
494 memcpy(hostaddr, ai->ai_addr, ai->ai_addrlen);
497 debug("connect to address %s port %s: %s",
498 ntop, strport, strerror(errno));
504 break; /* Successful connection. */
507 /* Return failure if we didn't get a successful connection. */
509 error("ssh: connect to host %s port %s: %s",
510 host, strport, strerror(errno));
514 debug("Connection established.");
516 /* Set SO_KEEPALIVE if requested. */
517 if (want_keepalive &&
518 setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
520 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
522 /* Set the connection. */
523 packet_set_connection(sock, sock);
529 ssh_connect(const char *host, struct addrinfo *addrs,
530 struct sockaddr_storage *hostaddr, u_short port, int family,
531 int connection_attempts, int *timeout_ms, int want_keepalive, int needpriv)
533 if (options.proxy_command == NULL) {
534 return ssh_connect_direct(host, addrs, hostaddr, port, family,
535 connection_attempts, timeout_ms, want_keepalive, needpriv);
536 } else if (strcmp(options.proxy_command, "-") == 0) {
537 packet_set_connection(STDIN_FILENO, STDOUT_FILENO);
538 return 0; /* Always succeeds */
539 } else if (options.proxy_use_fdpass) {
540 return ssh_proxy_fdpass_connect(host, port,
541 options.proxy_command);
543 return ssh_proxy_connect(host, port, options.proxy_command);
547 send_client_banner(int connection_out, int minor1)
549 /* Send our own protocol version identification. */
550 xasprintf(&client_version_string, "SSH-%d.%d-%.100s%s%s%s%s",
551 compat20 ? PROTOCOL_MAJOR_2 : PROTOCOL_MAJOR_1,
552 compat20 ? PROTOCOL_MINOR_2 : minor1,
553 SSH_VERSION, options.hpn_disabled ? "" : SSH_VERSION_HPN,
554 *options.version_addendum == '\0' ? "" : " ",
555 options.version_addendum, compat20 ? "\r\n" : "\n");
556 if (roaming_atomicio(vwrite, connection_out, client_version_string,
557 strlen(client_version_string)) != strlen(client_version_string))
558 fatal("write: %.100s", strerror(errno));
559 chop(client_version_string);
560 debug("Local version string %.100s", client_version_string);
564 * Waits for the server identification string, and sends our own
565 * identification string.
568 ssh_exchange_identification(int timeout_ms)
570 char buf[256], remote_version[256]; /* must be same size! */
571 int remote_major, remote_minor, mismatch;
572 int connection_in = packet_get_connection_in();
573 int connection_out = packet_get_connection_out();
574 int minor1 = PROTOCOL_MINOR_1, client_banner_sent = 0;
577 int fdsetsz, remaining, rc;
578 struct timeval t_start, t_remaining;
581 fdsetsz = howmany(connection_in + 1, NFDBITS) * sizeof(fd_mask);
582 fdset = xcalloc(1, fdsetsz);
585 * If we are SSH2-only then we can send the banner immediately and
588 if (options.protocol == SSH_PROTO_2) {
590 send_client_banner(connection_out, 0);
591 client_banner_sent = 1;
594 /* Read other side's version identification. */
595 remaining = timeout_ms;
597 for (i = 0; i < sizeof(buf) - 1; i++) {
598 if (timeout_ms > 0) {
599 gettimeofday(&t_start, NULL);
600 ms_to_timeval(&t_remaining, remaining);
601 FD_SET(connection_in, fdset);
602 rc = select(connection_in + 1, fdset, NULL,
603 fdset, &t_remaining);
604 ms_subtract_diff(&t_start, &remaining);
605 if (rc == 0 || remaining <= 0)
606 fatal("Connection timed out during "
611 fatal("ssh_exchange_identification: "
612 "select: %s", strerror(errno));
616 len = roaming_atomicio(read, connection_in, &buf[i], 1);
618 if (len != 1 && errno == EPIPE)
619 fatal("ssh_exchange_identification: "
620 "Connection closed by remote host");
622 fatal("ssh_exchange_identification: "
623 "read: %.100s", strerror(errno));
624 if (buf[i] == '\r') {
627 continue; /**XXX wait for \n */
629 if (buf[i] == '\n') {
634 fatal("ssh_exchange_identification: "
635 "No banner received");
637 buf[sizeof(buf) - 1] = 0;
638 if (strncmp(buf, "SSH-", 4) == 0)
640 debug("ssh_exchange_identification: %s", buf);
642 server_version_string = xstrdup(buf);
646 * Check that the versions match. In future this might accept
647 * several versions and set appropriate flags to handle them.
649 if (sscanf(server_version_string, "SSH-%d.%d-%[^\n]\n",
650 &remote_major, &remote_minor, remote_version) != 3)
651 fatal("Bad remote protocol version identification: '%.100s'", buf);
652 debug("Remote protocol version %d.%d, remote software version %.100s",
653 remote_major, remote_minor, remote_version);
655 compat_datafellows(remote_version);
658 switch (remote_major) {
660 if (remote_minor == 99 &&
661 (options.protocol & SSH_PROTO_2) &&
662 !(options.protocol & SSH_PROTO_1_PREFERRED)) {
666 if (!(options.protocol & SSH_PROTO_1)) {
670 if (remote_minor < 3) {
671 fatal("Remote machine has too old SSH software version.");
672 } else if (remote_minor == 3 || remote_minor == 4) {
673 /* We speak 1.3, too. */
676 if (options.forward_agent) {
677 logit("Agent forwarding disabled for protocol 1.3");
678 options.forward_agent = 0;
683 if (options.protocol & SSH_PROTO_2) {
693 fatal("Protocol major versions differ: %d vs. %d",
694 (options.protocol & SSH_PROTO_2) ? PROTOCOL_MAJOR_2 : PROTOCOL_MAJOR_1,
696 if ((datafellows & SSH_BUG_DERIVEKEY) != 0)
697 fatal("Server version \"%.100s\" uses unsafe key agreement; "
698 "refusing connection", remote_version);
699 if ((datafellows & SSH_BUG_RSASIGMD5) != 0)
700 logit("Server version \"%.100s\" uses unsafe RSA signature "
701 "scheme; disabling use of RSA keys", remote_version);
702 if (!client_banner_sent)
703 send_client_banner(connection_out, minor1);
704 chop(server_version_string);
707 /* defaults to 'no' */
709 confirm(const char *prompt)
711 const char *msg, *again = "Please type 'yes' or 'no': ";
715 if (options.batch_mode)
717 for (msg = prompt;;msg = again) {
718 p = read_passphrase(msg, RP_ECHO);
720 (p[0] == '\0') || (p[0] == '\n') ||
721 strncasecmp(p, "no", 2) == 0)
723 if (p && strncasecmp(p, "yes", 3) == 0)
732 check_host_cert(const char *host, const Key *host_key)
736 if (key_cert_check_authority(host_key, 1, 0, host, &reason) != 0) {
740 if (buffer_len(&host_key->cert->critical) != 0) {
741 error("Certificate for %s contains unsupported "
742 "critical options(s)", host);
749 sockaddr_is_local(struct sockaddr *hostaddr)
751 switch (hostaddr->sa_family) {
753 return (ntohl(((struct sockaddr_in *)hostaddr)->
754 sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
756 return IN6_IS_ADDR_LOOPBACK(
757 &(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
764 * Prepare the hostname and ip address strings that are used to lookup
765 * host keys in known_hosts files. These may have a port number appended.
768 get_hostfile_hostname_ipaddr(char *hostname, struct sockaddr *hostaddr,
769 u_short port, char **hostfile_hostname, char **hostfile_ipaddr)
771 char ntop[NI_MAXHOST];
774 switch (hostaddr == NULL ? -1 : hostaddr->sa_family) {
779 addrlen = sizeof(struct sockaddr_in);
782 addrlen = sizeof(struct sockaddr_in6);
785 addrlen = sizeof(struct sockaddr);
790 * We don't have the remote ip-address for connections
791 * using a proxy command
793 if (hostfile_ipaddr != NULL) {
794 if (options.proxy_command == NULL) {
795 if (getnameinfo(hostaddr, addrlen,
796 ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST) != 0)
797 fatal("check_host_key: getnameinfo failed");
798 *hostfile_ipaddr = put_host_port(ntop, port);
800 *hostfile_ipaddr = xstrdup("<no hostip for proxy "
806 * Allow the user to record the key under a different name or
807 * differentiate a non-standard port. This is useful for ssh
808 * tunneling over forwarded connections or if you run multiple
809 * sshd's on different ports on the same machine.
811 if (hostfile_hostname != NULL) {
812 if (options.host_key_alias != NULL) {
813 *hostfile_hostname = xstrdup(options.host_key_alias);
814 debug("using hostkeyalias: %s", *hostfile_hostname);
816 *hostfile_hostname = put_host_port(hostname, port);
822 * check whether the supplied host key is valid, return -1 if the key
823 * is not valid. user_hostfile[0] will not be updated if 'readonly' is true.
829 check_host_key(char *hostname, struct sockaddr *hostaddr, u_short port,
830 Key *host_key, int readonly,
831 char **user_hostfiles, u_int num_user_hostfiles,
832 char **system_hostfiles, u_int num_system_hostfiles)
834 HostStatus host_status;
835 HostStatus ip_status;
837 char *ip = NULL, *host = NULL;
838 char hostline[1000], *hostp, *fp, *ra;
841 const struct hostkey_entry *host_found, *ip_found;
842 int len, cancelled_forwarding = 0;
843 int local = sockaddr_is_local(hostaddr);
844 int r, want_cert = key_is_cert(host_key), host_ip_differ = 0;
845 struct hostkeys *host_hostkeys, *ip_hostkeys;
849 * Force accepting of the host key for loopback/localhost. The
850 * problem is that if the home directory is NFS-mounted to multiple
851 * machines, localhost will refer to a different machine in each of
852 * them, and the user will get bogus HOST_CHANGED warnings. This
853 * essentially disables host authentication for localhost; however,
854 * this is probably not a real problem.
856 if (options.no_host_authentication_for_localhost == 1 && local &&
857 options.host_key_alias == NULL) {
858 debug("Forcing accepting of host key for "
859 "loopback/localhost.");
864 * Prepare the hostname and address strings used for hostkey lookup.
865 * In some cases, these will have a port number appended.
867 get_hostfile_hostname_ipaddr(hostname, hostaddr, port, &host, &ip);
870 * Turn off check_host_ip if the connection is to localhost, via proxy
871 * command or if we don't have a hostname to compare with
873 if (options.check_host_ip && (local ||
874 strcmp(hostname, ip) == 0 || options.proxy_command != NULL))
875 options.check_host_ip = 0;
877 host_hostkeys = init_hostkeys();
878 for (i = 0; i < num_user_hostfiles; i++)
879 load_hostkeys(host_hostkeys, host, user_hostfiles[i]);
880 for (i = 0; i < num_system_hostfiles; i++)
881 load_hostkeys(host_hostkeys, host, system_hostfiles[i]);
884 if (!want_cert && options.check_host_ip) {
885 ip_hostkeys = init_hostkeys();
886 for (i = 0; i < num_user_hostfiles; i++)
887 load_hostkeys(ip_hostkeys, ip, user_hostfiles[i]);
888 for (i = 0; i < num_system_hostfiles; i++)
889 load_hostkeys(ip_hostkeys, ip, system_hostfiles[i]);
893 /* Reload these as they may have changed on cert->key downgrade */
894 want_cert = key_is_cert(host_key);
895 type = key_type(host_key);
898 * Check if the host key is present in the user's list of known
899 * hosts or in the systemwide list.
901 host_status = check_key_in_hostkeys(host_hostkeys, host_key,
905 * Also perform check for the ip address, skip the check if we are
906 * localhost, looking for a certificate, or the hostname was an ip
907 * address to begin with.
909 if (!want_cert && ip_hostkeys != NULL) {
910 ip_status = check_key_in_hostkeys(ip_hostkeys, host_key,
912 if (host_status == HOST_CHANGED &&
913 (ip_status != HOST_CHANGED ||
915 !key_equal(ip_found->key, host_found->key))))
918 ip_status = host_status;
920 switch (host_status) {
922 /* The host is known and the key matches. */
923 debug("Host '%.200s' is known and matches the %s host %s.",
924 host, type, want_cert ? "certificate" : "key");
925 debug("Found %s in %s:%lu", want_cert ? "CA key" : "key",
926 host_found->file, host_found->line);
927 if (want_cert && !check_host_cert(hostname, host_key))
929 if (options.check_host_ip && ip_status == HOST_NEW) {
930 if (readonly || want_cert)
931 logit("%s host key for IP address "
932 "'%.128s' not in list of known hosts.",
934 else if (!add_host_to_hostfile(user_hostfiles[0], ip,
935 host_key, options.hash_known_hosts))
936 logit("Failed to add the %s host key for IP "
937 "address '%.128s' to the list of known "
938 "hosts (%.30s).", type, ip,
941 logit("Warning: Permanently added the %s host "
942 "key for IP address '%.128s' to the list "
943 "of known hosts.", type, ip);
944 } else if (options.visual_host_key) {
945 fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX);
946 ra = key_fingerprint(host_key, SSH_FP_MD5,
948 logit("Host key fingerprint is %s\n%s\n", fp, ra);
954 if (options.host_key_alias == NULL && port != 0 &&
955 port != SSH_DEFAULT_PORT) {
956 debug("checking without port identifier");
957 if (check_host_key(hostname, hostaddr, 0, host_key,
958 ROQUIET, user_hostfiles, num_user_hostfiles,
959 system_hostfiles, num_system_hostfiles) == 0) {
960 debug("found matching key w/out port");
964 if (readonly || want_cert)
966 /* The host is new. */
967 if (options.strict_host_key_checking == 1) {
969 * User has requested strict host key checking. We
970 * will not add the host key automatically. The only
971 * alternative left is to abort.
973 error("No %s host key is known for %.200s and you "
974 "have requested strict checking.", type, host);
976 } else if (options.strict_host_key_checking == 2) {
977 char msg1[1024], msg2[1024];
979 if (show_other_keys(host_hostkeys, host_key))
980 snprintf(msg1, sizeof(msg1),
981 "\nbut keys of different type are already"
982 " known for this host.");
984 snprintf(msg1, sizeof(msg1), ".");
986 fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX);
987 ra = key_fingerprint(host_key, SSH_FP_MD5,
990 if (options.verify_host_key_dns) {
991 if (matching_host_key_dns)
992 snprintf(msg2, sizeof(msg2),
993 "Matching host key fingerprint"
996 snprintf(msg2, sizeof(msg2),
997 "No matching host key fingerprint"
1000 snprintf(msg, sizeof(msg),
1001 "The authenticity of host '%.200s (%s)' can't be "
1003 "%s key fingerprint is %s.%s%s\n%s"
1004 "Are you sure you want to continue connecting "
1006 host, ip, msg1, type, fp,
1007 options.visual_host_key ? "\n" : "",
1008 options.visual_host_key ? ra : "",
1016 * If not in strict mode, add the key automatically to the
1017 * local known_hosts file.
1019 if (options.check_host_ip && ip_status == HOST_NEW) {
1020 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1022 if (options.hash_known_hosts) {
1023 /* Add hash of host and IP separately */
1024 r = add_host_to_hostfile(user_hostfiles[0],
1025 host, host_key, options.hash_known_hosts) &&
1026 add_host_to_hostfile(user_hostfiles[0], ip,
1027 host_key, options.hash_known_hosts);
1029 /* Add unhashed "host,ip" */
1030 r = add_host_to_hostfile(user_hostfiles[0],
1032 options.hash_known_hosts);
1035 r = add_host_to_hostfile(user_hostfiles[0], host,
1036 host_key, options.hash_known_hosts);
1041 logit("Failed to add the host to the list of known "
1042 "hosts (%.500s).", user_hostfiles[0]);
1044 logit("Warning: Permanently added '%.200s' (%s) to the "
1045 "list of known hosts.", hostp, type);
1048 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1049 error("@ WARNING: REVOKED HOST KEY DETECTED! @");
1050 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1051 error("The %s host key for %s is marked as revoked.", type, host);
1052 error("This could mean that a stolen key is being used to");
1053 error("impersonate this host.");
1056 * If strict host key checking is in use, the user will have
1057 * to edit the key manually and we can only abort.
1059 if (options.strict_host_key_checking) {
1060 error("%s host key for %.200s was revoked and you have "
1061 "requested strict checking.", type, host);
1064 goto continue_unsafe;
1069 * This is only a debug() since it is valid to have
1070 * CAs with wildcard DNS matches that don't match
1071 * all hosts that one might visit.
1073 debug("Host certificate authority does not "
1074 "match %s in %s:%lu", CA_MARKER,
1075 host_found->file, host_found->line);
1078 if (readonly == ROQUIET)
1080 if (options.check_host_ip && host_ip_differ) {
1082 if (ip_status == HOST_NEW)
1083 key_msg = "is unknown";
1084 else if (ip_status == HOST_OK)
1085 key_msg = "is unchanged";
1087 key_msg = "has a different value";
1088 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1089 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1090 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1091 error("The %s host key for %s has changed,", type, host);
1092 error("and the key for the corresponding IP address %s", ip);
1093 error("%s. This could either mean that", key_msg);
1094 error("DNS SPOOFING is happening or the IP address for the host");
1095 error("and its host key have changed at the same time.");
1096 if (ip_status != HOST_NEW)
1097 error("Offending key for IP in %s:%lu",
1098 ip_found->file, ip_found->line);
1100 /* The host key has changed. */
1101 warn_changed_key(host_key);
1102 error("Add correct host key in %.100s to get rid of this message.",
1104 error("Offending %s key in %s:%lu", key_type(host_found->key),
1105 host_found->file, host_found->line);
1108 * If strict host key checking is in use, the user will have
1109 * to edit the key manually and we can only abort.
1111 if (options.strict_host_key_checking) {
1112 error("%s host key for %.200s has changed and you have "
1113 "requested strict checking.", type, host);
1119 * If strict host key checking has not been requested, allow
1120 * the connection but without MITM-able authentication or
1123 if (options.password_authentication) {
1124 error("Password authentication is disabled to avoid "
1125 "man-in-the-middle attacks.");
1126 options.password_authentication = 0;
1127 cancelled_forwarding = 1;
1129 if (options.kbd_interactive_authentication) {
1130 error("Keyboard-interactive authentication is disabled"
1131 " to avoid man-in-the-middle attacks.");
1132 options.kbd_interactive_authentication = 0;
1133 options.challenge_response_authentication = 0;
1134 cancelled_forwarding = 1;
1136 if (options.challenge_response_authentication) {
1137 error("Challenge/response authentication is disabled"
1138 " to avoid man-in-the-middle attacks.");
1139 options.challenge_response_authentication = 0;
1140 cancelled_forwarding = 1;
1142 if (options.forward_agent) {
1143 error("Agent forwarding is disabled to avoid "
1144 "man-in-the-middle attacks.");
1145 options.forward_agent = 0;
1146 cancelled_forwarding = 1;
1148 if (options.forward_x11) {
1149 error("X11 forwarding is disabled to avoid "
1150 "man-in-the-middle attacks.");
1151 options.forward_x11 = 0;
1152 cancelled_forwarding = 1;
1154 if (options.num_local_forwards > 0 ||
1155 options.num_remote_forwards > 0) {
1156 error("Port forwarding is disabled to avoid "
1157 "man-in-the-middle attacks.");
1158 options.num_local_forwards =
1159 options.num_remote_forwards = 0;
1160 cancelled_forwarding = 1;
1162 if (options.tun_open != SSH_TUNMODE_NO) {
1163 error("Tunnel forwarding is disabled to avoid "
1164 "man-in-the-middle attacks.");
1165 options.tun_open = SSH_TUNMODE_NO;
1166 cancelled_forwarding = 1;
1168 if (options.exit_on_forward_failure && cancelled_forwarding)
1169 fatal("Error: forwarding disabled due to host key "
1173 * XXX Should permit the user to change to use the new id.
1174 * This could be done by converting the host key to an
1175 * identifying sentence, tell that the host identifies itself
1176 * by that sentence, and ask the user if he/she wishes to
1177 * accept the authentication.
1181 fatal("internal error");
1185 if (options.check_host_ip && host_status != HOST_CHANGED &&
1186 ip_status == HOST_CHANGED) {
1187 snprintf(msg, sizeof(msg),
1188 "Warning: the %s host key for '%.200s' "
1189 "differs from the key for the IP address '%.128s'"
1190 "\nOffending key for IP in %s:%lu",
1191 type, host, ip, ip_found->file, ip_found->line);
1192 if (host_status == HOST_OK) {
1194 snprintf(msg + len, sizeof(msg) - len,
1195 "\nMatching host key in %s:%lu",
1196 host_found->file, host_found->line);
1198 if (options.strict_host_key_checking == 1) {
1200 error("Exiting, you have requested strict checking.");
1202 } else if (options.strict_host_key_checking == 2) {
1203 strlcat(msg, "\nAre you sure you want "
1204 "to continue connecting (yes/no)? ", sizeof(msg));
1214 if (host_hostkeys != NULL)
1215 free_hostkeys(host_hostkeys);
1216 if (ip_hostkeys != NULL)
1217 free_hostkeys(ip_hostkeys);
1221 if (want_cert && host_status != HOST_REVOKED) {
1223 * No matching certificate. Downgrade cert to raw key and
1226 debug("No matching CA found. Retry with plain key");
1227 raw_key = key_from_private(host_key);
1228 if (key_drop_cert(raw_key) != 0)
1229 fatal("Couldn't drop certificate");
1233 if (raw_key != NULL)
1237 if (host_hostkeys != NULL)
1238 free_hostkeys(host_hostkeys);
1239 if (ip_hostkeys != NULL)
1240 free_hostkeys(ip_hostkeys);
1244 /* returns 0 if key verifies or -1 if key does NOT verify */
1246 verify_host_key(char *host, struct sockaddr *hostaddr, Key *host_key)
1252 fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX);
1253 debug("Server host key: %s %s", key_type(host_key), fp);
1256 if (options.verify_host_key_dns) {
1258 * XXX certs are not yet supported for DNS, so downgrade
1259 * them and try the plain key.
1261 plain = key_from_private(host_key);
1262 if (key_is_cert(plain))
1263 key_drop_cert(plain);
1264 if (verify_host_key_dns(host, hostaddr, plain, &flags) == 0) {
1265 if (flags & DNS_VERIFY_FOUND) {
1266 if (options.verify_host_key_dns == 1 &&
1267 flags & DNS_VERIFY_MATCH &&
1268 flags & DNS_VERIFY_SECURE) {
1272 if (flags & DNS_VERIFY_MATCH) {
1273 matching_host_key_dns = 1;
1275 warn_changed_key(plain);
1276 error("Update the SSHFP RR in DNS "
1277 "with the new host key to get rid "
1278 "of this message.");
1285 return check_host_key(host, hostaddr, options.port, host_key, RDRW,
1286 options.user_hostfiles, options.num_user_hostfiles,
1287 options.system_hostfiles, options.num_system_hostfiles);
1291 * Starts a dialog with the server, and authenticates the current user on the
1292 * server. This does not need any extra privileges. The basic connection
1293 * to the server must already have been established before this is called.
1294 * If login fails, this function prints an error and never returns.
1295 * This function does not require super-user privileges.
1298 ssh_login(Sensitive *sensitive, const char *orighost,
1299 struct sockaddr *hostaddr, u_short port, struct passwd *pw, int timeout_ms)
1302 char *server_user, *local_user;
1304 local_user = xstrdup(pw->pw_name);
1305 server_user = options.user ? options.user : local_user;
1307 /* Convert the user-supplied hostname into all lowercase. */
1308 host = xstrdup(orighost);
1311 /* Exchange protocol version identification strings with the server. */
1312 ssh_exchange_identification(timeout_ms);
1314 /* Put the connection into non-blocking mode. */
1315 packet_set_nonblocking();
1318 /* authenticate user */
1320 ssh_kex2(host, hostaddr, port);
1321 ssh_userauth2(local_user, server_user, host, sensitive);
1323 ssh_kex(host, hostaddr);
1324 ssh_userauth1(local_user, server_user, host, sensitive);
1330 ssh_put_password(char *password)
1335 if (datafellows & SSH_BUG_PASSWORDPAD) {
1336 packet_put_cstring(password);
1339 size = roundup(strlen(password) + 1, 32);
1340 padded = xcalloc(1, size);
1341 strlcpy(padded, password, size);
1342 packet_put_string(padded, size);
1343 explicit_bzero(padded, size);
1347 /* print all known host keys for a given host, but skip keys of given type */
1349 show_other_keys(struct hostkeys *hostkeys, Key *key)
1361 const struct hostkey_entry *found;
1363 for (i = 0; type[i] != -1; i++) {
1364 if (type[i] == key->type)
1366 if (!lookup_key_in_hostkeys_by_type(hostkeys, type[i], &found))
1368 fp = key_fingerprint(found->key, SSH_FP_MD5, SSH_FP_HEX);
1369 ra = key_fingerprint(found->key, SSH_FP_MD5, SSH_FP_RANDOMART);
1370 logit("WARNING: %s key found for host %s\n"
1372 "%s key fingerprint %s.",
1373 key_type(found->key),
1374 found->host, found->file, found->line,
1375 key_type(found->key), fp);
1376 if (options.visual_host_key)
1386 warn_changed_key(Key *host_key)
1390 fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX);
1392 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1393 error("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @");
1394 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1395 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1396 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1397 error("It is also possible that a host key has just been changed.");
1398 error("The fingerprint for the %s key sent by the remote host is\n%s.",
1399 key_type(host_key), fp);
1400 error("Please contact your system administrator.");
1406 * Execute a local command
1409 ssh_local_cmd(const char *args)
1414 void (*osighand)(int);
1416 if (!options.permit_local_command ||
1417 args == NULL || !*args)
1420 if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
1421 shell = _PATH_BSHELL;
1423 osighand = signal(SIGCHLD, SIG_DFL);
1426 signal(SIGPIPE, SIG_DFL);
1427 debug3("Executing %s -c \"%s\"", shell, args);
1428 execl(shell, shell, "-c", args, (char *)NULL);
1429 error("Couldn't execute %s -c \"%s\": %s",
1430 shell, args, strerror(errno));
1432 } else if (pid == -1)
1433 fatal("fork failed: %.100s", strerror(errno));
1434 while (waitpid(pid, &status, 0) == -1)
1436 fatal("Couldn't wait for child: %s", strerror(errno));
1437 signal(SIGCHLD, osighand);
1439 if (!WIFEXITED(status))
1442 return (WEXITSTATUS(status));