[BACK]Return to sshconnect.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/sshconnect.c, Revision 1.333

1.333   ! djm         1: /* $OpenBSD: sshconnect.c,v 1.332 2020/09/09 21:57:27 djm Exp $ */
1.1       deraadt     2: /*
1.39      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
                      6:  * Code to connect to a remote host, and to perform the client side of the
                      7:  * login (authentication) dialog.
1.78      deraadt     8:  *
                      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".
1.39      deraadt    14:  */
1.1       deraadt    15:
1.174     stevesk    16: #include <sys/types.h>
                     17: #include <sys/wait.h>
1.175     stevesk    18: #include <sys/stat.h>
1.187     stevesk    19: #include <sys/socket.h>
1.195     stevesk    20: #include <sys/time.h>
1.187     stevesk    21:
1.295     djm        22: #include <net/if.h>
1.187     stevesk    23: #include <netinet/in.h>
1.172     stevesk    24:
1.176     stevesk    25: #include <ctype.h>
1.190     stevesk    26: #include <errno.h>
1.216     dtucker    27: #include <fcntl.h>
1.191     stevesk    28: #include <netdb.h>
1.172     stevesk    29: #include <paths.h>
1.199     deraadt    30: #include <signal.h>
1.188     stevesk    31: #include <pwd.h>
1.198     stevesk    32: #include <stdio.h>
1.196     stevesk    33: #include <stdlib.h>
1.323     deraadt    34: #include <stdarg.h>
1.193     stevesk    35: #include <string.h>
1.192     stevesk    36: #include <unistd.h>
1.295     djm        37: #include <ifaddrs.h>
1.71      markus     38:
1.199     deraadt    39: #include "xmalloc.h"
1.91      markus     40: #include "ssh.h"
1.299     markus     41: #include "sshbuf.h"
1.1       deraadt    42: #include "packet.h"
1.21      markus     43: #include "compat.h"
1.300     markus     44: #include "sshkey.h"
1.71      markus     45: #include "sshconnect.h"
1.58      markus     46: #include "hostfile.h"
1.91      markus     47: #include "log.h"
1.251     millert    48: #include "misc.h"
1.91      markus     49: #include "readconf.h"
                     50: #include "atomicio.h"
1.140     jakob      51: #include "dns.h"
1.239     djm        52: #include "monitor_fdpass.h"
1.219     djm        53: #include "ssh2.h"
1.186     stevesk    54: #include "version.h"
1.252     djm        55: #include "authfile.h"
                     56: #include "ssherr.h"
1.266     jcs        57: #include "authfd.h"
1.309     djm        58: #include "kex.h"
1.310     djm        59:
1.279     markus     60: struct sshkey *previous_host_key = NULL;
1.59      markus     61:
1.169     stevesk    62: static int matching_host_key_dns = 0;
1.145     jakob      63:
1.227     djm        64: static pid_t proxy_command_pid = 0;
                     65:
1.124     markus     66: /* import */
1.307     djm        67: extern int debug_flag;
1.43      markus     68: extern Options options;
1.50      markus     69: extern char *__progname;
1.91      markus     70:
1.279     markus     71: static int show_other_keys(struct hostkeys *, struct sshkey *);
                     72: static void warn_changed_key(struct sshkey *);
1.132     markus     73:
1.239     djm        74: /* Expand a proxy command */
                     75: static char *
                     76: expand_proxy_command(const char *proxy_command, const char *user,
1.325     naddy      77:     const char *host, const char *host_arg, int port)
1.239     djm        78: {
                     79:        char *tmp, *ret, strport[NI_MAXSERV];
1.330     dtucker    80:        const char *keyalias = options.host_key_alias ?
                     81:             options.host_key_alias : host_arg;
1.239     djm        82:
1.241     djm        83:        snprintf(strport, sizeof strport, "%d", port);
1.239     djm        84:        xasprintf(&tmp, "exec %s", proxy_command);
1.318     djm        85:        ret = percent_expand(tmp,
                     86:            "h", host,
1.330     dtucker    87:            "k", keyalias,
1.318     djm        88:            "n", host_arg,
                     89:            "p", strport,
                     90:            "r", options.user,
                     91:            (char *)NULL);
1.239     djm        92:        free(tmp);
                     93:        return ret;
                     94: }
                     95:
1.307     djm        96: static void
                     97: stderr_null(void)
                     98: {
                     99:        int devnull;
                    100:
                    101:        if ((devnull = open(_PATH_DEVNULL, O_WRONLY)) == -1) {
                    102:                error("Can't open %s for stderr redirection: %s",
                    103:                    _PATH_DEVNULL, strerror(errno));
                    104:                return;
                    105:        }
                    106:        if (devnull == STDERR_FILENO)
                    107:                return;
                    108:        if (dup2(devnull, STDERR_FILENO) == -1)
                    109:                error("Cannot redirect stderr to %s", _PATH_DEVNULL);
                    110:        if (devnull > STDERR_FILENO)
                    111:                close(devnull);
                    112: }
                    113:
1.239     djm       114: /*
                    115:  * Connect to the given ssh server using a proxy command that passes a
                    116:  * a connected fd back to us.
                    117:  */
                    118: static int
1.318     djm       119: ssh_proxy_fdpass_connect(struct ssh *ssh, const char *host,
                    120:     const char *host_arg, u_short port, const char *proxy_command)
1.239     djm       121: {
                    122:        char *command_string;
                    123:        int sp[2], sock;
                    124:        pid_t pid;
                    125:        char *shell;
                    126:
                    127:        if ((shell = getenv("SHELL")) == NULL)
                    128:                shell = _PATH_BSHELL;
                    129:
1.317     deraadt   130:        if (socketpair(AF_UNIX, SOCK_STREAM, 0, sp) == -1)
1.239     djm       131:                fatal("Could not create socketpair to communicate with "
                    132:                    "proxy dialer: %.100s", strerror(errno));
                    133:
                    134:        command_string = expand_proxy_command(proxy_command, options.user,
1.325     naddy     135:            host, host_arg, port);
1.239     djm       136:        debug("Executing proxy dialer command: %.500s", command_string);
                    137:
                    138:        /* Fork and execute the proxy command. */
                    139:        if ((pid = fork()) == 0) {
                    140:                char *argv[10];
                    141:
                    142:                close(sp[1]);
                    143:                /* Redirect stdin and stdout. */
                    144:                if (sp[0] != 0) {
1.317     deraadt   145:                        if (dup2(sp[0], 0) == -1)
1.239     djm       146:                                perror("dup2 stdin");
                    147:                }
                    148:                if (sp[0] != 1) {
1.317     deraadt   149:                        if (dup2(sp[0], 1) == -1)
1.239     djm       150:                                perror("dup2 stdout");
                    151:                }
                    152:                if (sp[0] >= 2)
                    153:                        close(sp[0]);
                    154:
                    155:                /*
1.307     djm       156:                 * Stderr is left for non-ControlPersist connections is so
                    157:                 * error messages may be printed on the user's terminal.
1.239     djm       158:                 */
1.308     dtucker   159:                if (!debug_flag && options.control_path != NULL &&
                    160:                    options.control_persist)
1.307     djm       161:                        stderr_null();
                    162:
1.239     djm       163:                argv[0] = shell;
                    164:                argv[1] = "-c";
                    165:                argv[2] = command_string;
                    166:                argv[3] = NULL;
                    167:
                    168:                /*
                    169:                 * Execute the proxy command.
                    170:                 * Note that we gave up any extra privileges above.
                    171:                 */
                    172:                execv(argv[0], argv);
                    173:                perror(argv[0]);
                    174:                exit(1);
                    175:        }
                    176:        /* Parent. */
1.317     deraadt   177:        if (pid == -1)
1.239     djm       178:                fatal("fork failed: %.100s", strerror(errno));
                    179:        close(sp[0]);
                    180:        free(command_string);
                    181:
                    182:        if ((sock = mm_receive_fd(sp[1])) == -1)
                    183:                fatal("proxy dialer did not pass back a connection");
1.271     markus    184:        close(sp[1]);
1.239     djm       185:
                    186:        while (waitpid(pid, NULL, 0) == -1)
                    187:                if (errno != EINTR)
                    188:                        fatal("Couldn't wait for child: %s", strerror(errno));
                    189:
                    190:        /* Set the connection file descriptors. */
1.286     djm       191:        if (ssh_packet_set_connection(ssh, sock, sock) == NULL)
                    192:                return -1; /* ssh_packet_set_connection logs error */
1.239     djm       193:
                    194:        return 0;
                    195: }
                    196:
1.39      deraadt   197: /*
                    198:  * Connect to the given ssh server using a proxy command.
                    199:  */
1.109     itojun    200: static int
1.318     djm       201: ssh_proxy_connect(struct ssh *ssh, const char *host, const char *host_arg,
                    202:     u_short port, const char *proxy_command)
1.1       deraadt   203: {
1.239     djm       204:        char *command_string;
1.38      markus    205:        int pin[2], pout[2];
1.69      deraadt   206:        pid_t pid;
1.239     djm       207:        char *shell;
1.237     markus    208:
1.226     djm       209:        if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
1.201     djm       210:                shell = _PATH_BSHELL;
1.38      markus    211:
                    212:        /* Create pipes for communicating with the proxy. */
1.317     deraadt   213:        if (pipe(pin) == -1 || pipe(pout) == -1)
1.38      markus    214:                fatal("Could not create pipes to communicate with the proxy: %.100s",
1.118     deraadt   215:                    strerror(errno));
1.38      markus    216:
1.239     djm       217:        command_string = expand_proxy_command(proxy_command, options.user,
1.325     naddy     218:            host, host_arg, port);
1.38      markus    219:        debug("Executing proxy command: %.500s", command_string);
                    220:
                    221:        /* Fork and execute the proxy command. */
                    222:        if ((pid = fork()) == 0) {
                    223:                char *argv[10];
                    224:
                    225:                /* Redirect stdin and stdout. */
                    226:                close(pin[1]);
                    227:                if (pin[0] != 0) {
1.317     deraadt   228:                        if (dup2(pin[0], 0) == -1)
1.38      markus    229:                                perror("dup2 stdin");
                    230:                        close(pin[0]);
                    231:                }
                    232:                close(pout[0]);
1.317     deraadt   233:                if (dup2(pout[1], 1) == -1)
1.38      markus    234:                        perror("dup2 stdout");
                    235:                /* Cannot be 1 because pin allocated two descriptors. */
                    236:                close(pout[1]);
                    237:
1.307     djm       238:                /*
                    239:                 * Stderr is left for non-ControlPersist connections is so
                    240:                 * error messages may be printed on the user's terminal.
                    241:                 */
1.308     dtucker   242:                if (!debug_flag && options.control_path != NULL &&
                    243:                    options.control_persist)
1.307     djm       244:                        stderr_null();
                    245:
1.201     djm       246:                argv[0] = shell;
1.38      markus    247:                argv[1] = "-c";
                    248:                argv[2] = command_string;
                    249:                argv[3] = NULL;
                    250:
                    251:                /* Execute the proxy command.  Note that we gave up any
                    252:                   extra privileges above. */
1.327     dtucker   253:                ssh_signal(SIGPIPE, SIG_DFL);
1.89      markus    254:                execv(argv[0], argv);
                    255:                perror(argv[0]);
1.38      markus    256:                exit(1);
                    257:        }
                    258:        /* Parent. */
1.317     deraadt   259:        if (pid == -1)
1.38      markus    260:                fatal("fork failed: %.100s", strerror(errno));
1.135     djm       261:        else
                    262:                proxy_command_pid = pid; /* save pid to clean up later */
1.38      markus    263:
                    264:        /* Close child side of the descriptors. */
                    265:        close(pin[0]);
                    266:        close(pout[1]);
                    267:
                    268:        /* Free the command name. */
1.238     djm       269:        free(command_string);
1.38      markus    270:
                    271:        /* Set the connection file descriptors. */
1.286     djm       272:        if (ssh_packet_set_connection(ssh, pout[0], pin[1]) == NULL)
                    273:                return -1; /* ssh_packet_set_connection logs error */
1.1       deraadt   274:
1.110     markus    275:        return 0;
1.227     djm       276: }
                    277:
                    278: void
                    279: ssh_kill_proxy_command(void)
                    280: {
                    281:        /*
                    282:         * Send SIGHUP to proxy command if used. We don't wait() in
                    283:         * case it hangs and instead rely on init to reap the child
                    284:         */
                    285:        if (proxy_command_pid > 1)
1.228     djm       286:                kill(proxy_command_pid, SIGHUP);
1.1       deraadt   287: }
                    288:
1.39      deraadt   289: /*
1.295     djm       290:  * Search a interface address list (returned from getifaddrs(3)) for an
1.298     djm       291:  * address that matches the desired address family on the specified interface.
1.295     djm       292:  * Returns 0 and fills in *resultp and *rlenp on success. Returns -1 on failure.
                    293:  */
                    294: static int
                    295: check_ifaddrs(const char *ifname, int af, const struct ifaddrs *ifaddrs,
                    296:     struct sockaddr_storage *resultp, socklen_t *rlenp)
                    297: {
                    298:        struct sockaddr_in6 *sa6;
                    299:        struct sockaddr_in *sa;
                    300:        struct in6_addr *v6addr;
                    301:        const struct ifaddrs *ifa;
                    302:        int allow_local;
                    303:
                    304:        /*
                    305:         * Prefer addresses that are not loopback or linklocal, but use them
                    306:         * if nothing else matches.
                    307:         */
                    308:        for (allow_local = 0; allow_local < 2; allow_local++) {
                    309:                for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
                    310:                        if (ifa->ifa_addr == NULL || ifa->ifa_name == NULL ||
                    311:                            (ifa->ifa_flags & IFF_UP) == 0 ||
                    312:                            ifa->ifa_addr->sa_family != af ||
                    313:                            strcmp(ifa->ifa_name, options.bind_interface) != 0)
                    314:                                continue;
                    315:                        switch (ifa->ifa_addr->sa_family) {
                    316:                        case AF_INET:
                    317:                                sa = (struct sockaddr_in *)ifa->ifa_addr;
                    318:                                if (!allow_local && sa->sin_addr.s_addr ==
                    319:                                    htonl(INADDR_LOOPBACK))
                    320:                                        continue;
                    321:                                if (*rlenp < sizeof(struct sockaddr_in)) {
                    322:                                        error("%s: v4 addr doesn't fit",
                    323:                                            __func__);
                    324:                                        return -1;
                    325:                                }
                    326:                                *rlenp = sizeof(struct sockaddr_in);
                    327:                                memcpy(resultp, sa, *rlenp);
                    328:                                return 0;
                    329:                        case AF_INET6:
                    330:                                sa6 = (struct sockaddr_in6 *)ifa->ifa_addr;
                    331:                                v6addr = &sa6->sin6_addr;
                    332:                                if (!allow_local &&
                    333:                                    (IN6_IS_ADDR_LINKLOCAL(v6addr) ||
                    334:                                    IN6_IS_ADDR_LOOPBACK(v6addr)))
                    335:                                        continue;
                    336:                                if (*rlenp < sizeof(struct sockaddr_in6)) {
                    337:                                        error("%s: v6 addr doesn't fit",
                    338:                                            __func__);
                    339:                                        return -1;
                    340:                                }
                    341:                                *rlenp = sizeof(struct sockaddr_in6);
                    342:                                memcpy(resultp, sa6, *rlenp);
                    343:                                return 0;
                    344:                        }
                    345:                }
                    346:        }
                    347:        return -1;
                    348: }
                    349:
                    350: /*
1.303     dtucker   351:  * Creates a socket for use as the ssh connection.
1.39      deraadt   352:  */
1.109     itojun    353: static int
1.302     dtucker   354: ssh_create_socket(struct addrinfo *ai)
1.1       deraadt   355: {
1.301     dtucker   356:        int sock, r;
1.295     djm       357:        struct sockaddr_storage bindaddr;
                    358:        socklen_t bindaddrlen = 0;
1.246     djm       359:        struct addrinfo hints, *res = NULL;
1.295     djm       360:        struct ifaddrs *ifaddrs = NULL;
                    361:        char ntop[NI_MAXHOST];
1.1       deraadt   362:
1.217     dtucker   363:        sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1.317     deraadt   364:        if (sock == -1) {
1.240     djm       365:                error("socket: %s", strerror(errno));
1.216     dtucker   366:                return -1;
                    367:        }
                    368:        fcntl(sock, F_SETFD, FD_CLOEXEC);
1.105     markus    369:
                    370:        /* Bind the socket to an alternative local IP address */
1.302     dtucker   371:        if (options.bind_address == NULL && options.bind_interface == NULL)
1.105     markus    372:                return sock;
                    373:
1.295     djm       374:        if (options.bind_address != NULL) {
1.246     djm       375:                memset(&hints, 0, sizeof(hints));
                    376:                hints.ai_family = ai->ai_family;
                    377:                hints.ai_socktype = ai->ai_socktype;
                    378:                hints.ai_protocol = ai->ai_protocol;
                    379:                hints.ai_flags = AI_PASSIVE;
1.295     djm       380:                if ((r = getaddrinfo(options.bind_address, NULL,
                    381:                    &hints, &res)) != 0) {
1.246     djm       382:                        error("getaddrinfo: %s: %s", options.bind_address,
1.295     djm       383:                            ssh_gai_strerror(r));
                    384:                        goto fail;
                    385:                }
1.296     dtucker   386:                if (res == NULL) {
1.295     djm       387:                        error("getaddrinfo: no addrs");
                    388:                        goto fail;
                    389:                }
                    390:                memcpy(&bindaddr, res->ai_addr, res->ai_addrlen);
                    391:                bindaddrlen = res->ai_addrlen;
                    392:        } else if (options.bind_interface != NULL) {
                    393:                if ((r = getifaddrs(&ifaddrs)) != 0) {
                    394:                        error("getifaddrs: %s: %s", options.bind_interface,
                    395:                              strerror(errno));
                    396:                        goto fail;
                    397:                }
                    398:                bindaddrlen = sizeof(bindaddr);
                    399:                if (check_ifaddrs(options.bind_interface, ai->ai_family,
                    400:                    ifaddrs, &bindaddr, &bindaddrlen) != 0) {
                    401:                        logit("getifaddrs: %s: no suitable addresses",
                    402:                              options.bind_interface);
                    403:                        goto fail;
1.246     djm       404:                }
1.105     markus    405:        }
1.295     djm       406:        if ((r = getnameinfo((struct sockaddr *)&bindaddr, bindaddrlen,
                    407:            ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST)) != 0) {
                    408:                error("%s: getnameinfo failed: %s", __func__,
                    409:                    ssh_gai_strerror(r));
                    410:                goto fail;
                    411:        }
1.301     dtucker   412:        if (bind(sock, (struct sockaddr *)&bindaddr, bindaddrlen) != 0) {
1.295     djm       413:                error("bind %s: %s", ntop, strerror(errno));
                    414:                goto fail;
1.38      markus    415:        }
1.295     djm       416:        debug("%s: bound to %s", __func__, ntop);
                    417:        /* success */
                    418:        goto out;
                    419: fail:
                    420:        close(sock);
                    421:        sock = -1;
                    422:  out:
1.246     djm       423:        if (res != NULL)
                    424:                freeaddrinfo(res);
1.295     djm       425:        if (ifaddrs != NULL)
                    426:                freeifaddrs(ifaddrs);
1.38      markus    427:        return sock;
1.1       deraadt   428: }
                    429:
1.282     djm       430: /*
1.49      markus    431:  * Opens a TCP/IP connection to the remote server on the given host.
                    432:  * The address of the remote host will be returned in hostaddr.
1.302     dtucker   433:  * If port is 0, the default port will be used.
1.39      deraadt   434:  * Connection_attempts specifies the maximum number of tries (one per
                    435:  * second).  If proxy_command is non-NULL, it specifies the command (with %h
                    436:  * and %p substituted for host and port, respectively) to use to contact
                    437:  * the daemon.
                    438:  */
1.241     djm       439: static int
1.286     djm       440: ssh_connect_direct(struct ssh *ssh, const char *host, struct addrinfo *aitop,
1.241     djm       441:     struct sockaddr_storage *hostaddr, u_short port, int family,
1.302     dtucker   442:     int connection_attempts, int *timeout_ms, int want_keepalive)
1.1       deraadt   443: {
1.313     dtucker   444:        int on = 1, saved_timeout_ms = *timeout_ms;
1.290     djm       445:        int oerrno, sock = -1, attempt;
1.90      markus    446:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1.241     djm       447:        struct addrinfo *ai;
1.38      markus    448:
1.302     dtucker   449:        debug2("%s", __func__);
1.268     djm       450:        memset(ntop, 0, sizeof(ntop));
                    451:        memset(strport, 0, sizeof(strport));
1.38      markus    452:
1.181     markus    453:        for (attempt = 0; attempt < connection_attempts; attempt++) {
1.200     markus    454:                if (attempt > 0) {
                    455:                        /* Sleep a moment before retrying. */
                    456:                        sleep(1);
1.38      markus    457:                        debug("Trying again...");
1.200     markus    458:                }
1.181     markus    459:                /*
                    460:                 * Loop through addresses for this host, and try each one in
                    461:                 * sequence until the connection succeeds.
                    462:                 */
1.49      markus    463:                for (ai = aitop; ai; ai = ai->ai_next) {
1.241     djm       464:                        if (ai->ai_family != AF_INET &&
1.290     djm       465:                            ai->ai_family != AF_INET6) {
                    466:                                errno = EAFNOSUPPORT;
1.49      markus    467:                                continue;
1.290     djm       468:                        }
1.49      markus    469:                        if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
                    470:                            ntop, sizeof(ntop), strport, sizeof(strport),
                    471:                            NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1.290     djm       472:                                oerrno = errno;
1.265     djm       473:                                error("%s: getnameinfo failed", __func__);
1.290     djm       474:                                errno = oerrno;
1.49      markus    475:                                continue;
                    476:                        }
                    477:                        debug("Connecting to %.200s [%.100s] port %s.",
                    478:                                host, ntop, strport);
                    479:
                    480:                        /* Create a socket for connecting. */
1.302     dtucker   481:                        sock = ssh_create_socket(ai);
1.292     stsp      482:                        if (sock < 0) {
1.110     markus    483:                                /* Any error is already output */
1.290     djm       484:                                errno = 0;
1.49      markus    485:                                continue;
1.292     stsp      486:                        }
1.49      markus    487:
1.313     dtucker   488:                        *timeout_ms = saved_timeout_ms;
1.141     djm       489:                        if (timeout_connect(sock, ai->ai_addr, ai->ai_addrlen,
1.202     djm       490:                            timeout_ms) >= 0) {
1.49      markus    491:                                /* Successful connection. */
1.102     markus    492:                                memcpy(hostaddr, ai->ai_addr, ai->ai_addrlen);
1.38      markus    493:                                break;
1.49      markus    494:                        } else {
1.290     djm       495:                                oerrno = errno;
1.131     itojun    496:                                debug("connect to address %s port %s: %s",
                    497:                                    ntop, strport, strerror(errno));
1.38      markus    498:                                close(sock);
1.181     markus    499:                                sock = -1;
1.290     djm       500:                                errno = oerrno;
1.38      markus    501:                        }
                    502:                }
1.181     markus    503:                if (sock != -1)
1.49      markus    504:                        break;  /* Successful connection. */
1.38      markus    505:        }
1.49      markus    506:
1.38      markus    507:        /* Return failure if we didn't get a successful connection. */
1.181     markus    508:        if (sock == -1) {
1.159     markus    509:                error("ssh: connect to host %s port %s: %s",
1.290     djm       510:                    host, strport, errno == 0 ? "failure" : strerror(errno));
                    511:                return -1;
1.130     itojun    512:        }
1.38      markus    513:
                    514:        debug("Connection established.");
1.90      markus    515:
1.155     markus    516:        /* Set SO_KEEPALIVE if requested. */
1.202     djm       517:        if (want_keepalive &&
1.90      markus    518:            setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
1.317     deraadt   519:            sizeof(on)) == -1)
1.90      markus    520:                error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1.38      markus    521:
                    522:        /* Set the connection. */
1.286     djm       523:        if (ssh_packet_set_connection(ssh, sock, sock) == NULL)
                    524:                return -1; /* ssh_packet_set_connection logs error */
1.1       deraadt   525:
1.319     djm       526:        return 0;
1.59      markus    527: }
                    528:
1.241     djm       529: int
1.318     djm       530: ssh_connect(struct ssh *ssh, const char *host, const char *host_arg,
                    531:     struct addrinfo *addrs, struct sockaddr_storage *hostaddr, u_short port,
                    532:     int family, int connection_attempts, int *timeout_ms, int want_keepalive)
1.241     djm       533: {
1.314     markus    534:        int in, out;
                    535:
1.241     djm       536:        if (options.proxy_command == NULL) {
1.286     djm       537:                return ssh_connect_direct(ssh, host, addrs, hostaddr, port,
1.302     dtucker   538:                    family, connection_attempts, timeout_ms, want_keepalive);
1.241     djm       539:        } else if (strcmp(options.proxy_command, "-") == 0) {
1.317     deraadt   540:                if ((in = dup(STDIN_FILENO)) == -1 ||
                    541:                    (out = dup(STDOUT_FILENO)) == -1) {
1.314     markus    542:                        if (in >= 0)
                    543:                                close(in);
                    544:                        error("%s: dup() in/out failed", __func__);
                    545:                        return -1; /* ssh_packet_set_connection logs error */
                    546:                }
                    547:                if ((ssh_packet_set_connection(ssh, in, out)) == NULL)
1.286     djm       548:                        return -1; /* ssh_packet_set_connection logs error */
                    549:                return 0;
1.241     djm       550:        } else if (options.proxy_use_fdpass) {
1.318     djm       551:                return ssh_proxy_fdpass_connect(ssh, host, host_arg, port,
1.241     djm       552:                    options.proxy_command);
                    553:        }
1.318     djm       554:        return ssh_proxy_connect(ssh, host, host_arg, port,
                    555:            options.proxy_command);
1.241     djm       556: }
                    557:
1.96      markus    558: /* defaults to 'no' */
1.109     itojun    559: static int
1.312     dtucker   560: confirm(const char *prompt, const char *fingerprint)
1.1       deraadt   561: {
1.119     markus    562:        const char *msg, *again = "Please type 'yes' or 'no': ";
1.312     dtucker   563:        const char *again_fp = "Please type 'yes', 'no' or the fingerprint: ";
1.326     dtucker   564:        char *p, *cp;
1.119     markus    565:        int ret = -1;
1.96      markus    566:
                    567:        if (options.batch_mode)
                    568:                return 0;
1.312     dtucker   569:        for (msg = prompt;;msg = fingerprint ? again_fp : again) {
1.326     dtucker   570:                cp = p = read_passphrase(msg, RP_ECHO);
1.289     djm       571:                if (p == NULL)
                    572:                        return 0;
1.326     dtucker   573:                p += strspn(p, " \t"); /* skip leading whitespace */
                    574:                p[strcspn(p, " \t\n")] = '\0'; /* remove trailing whitespace */
1.289     djm       575:                if (p[0] == '\0' || strcasecmp(p, "no") == 0)
1.119     markus    576:                        ret = 0;
1.312     dtucker   577:                else if (strcasecmp(p, "yes") == 0 || (fingerprint != NULL &&
1.332     djm       578:                    strcmp(p, fingerprint) == 0))
1.119     markus    579:                        ret = 1;
1.326     dtucker   580:                free(cp);
1.119     markus    581:                if (ret != -1)
                    582:                        return ret;
1.1       deraadt   583:        }
                    584: }
                    585:
1.219     djm       586: static int
1.305     djm       587: check_host_cert(const char *host, const struct sshkey *key)
1.219     djm       588: {
                    589:        const char *reason;
1.305     djm       590:        int r;
1.219     djm       591:
1.305     djm       592:        if (sshkey_cert_check_authority(key, 1, 0, host, &reason) != 0) {
1.219     djm       593:                error("%s", reason);
                    594:                return 0;
                    595:        }
1.305     djm       596:        if (sshbuf_len(key->cert->critical) != 0) {
1.223     djm       597:                error("Certificate for %s contains unsupported "
                    598:                    "critical options(s)", host);
1.219     djm       599:                return 0;
                    600:        }
1.305     djm       601:        if ((r = sshkey_check_cert_sigtype(key,
                    602:            options.ca_sign_algorithms)) != 0) {
                    603:                logit("%s: certificate signature algorithm %s: %s", __func__,
                    604:                    (key->cert == NULL || key->cert->signature_type == NULL) ?
                    605:                    "(null)" : key->cert->signature_type, ssh_err(r));
                    606:                return 0;
                    607:        }
                    608:
1.219     djm       609:        return 1;
                    610: }
                    611:
1.229     djm       612: static int
                    613: sockaddr_is_local(struct sockaddr *hostaddr)
                    614: {
                    615:        switch (hostaddr->sa_family) {
                    616:        case AF_INET:
                    617:                return (ntohl(((struct sockaddr_in *)hostaddr)->
                    618:                    sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
                    619:        case AF_INET6:
                    620:                return IN6_IS_ADDR_LOOPBACK(
                    621:                    &(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
                    622:        default:
                    623:                return 0;
                    624:        }
                    625: }
                    626:
                    627: /*
                    628:  * Prepare the hostname and ip address strings that are used to lookup
                    629:  * host keys in known_hosts files. These may have a port number appended.
                    630:  */
                    631: void
                    632: get_hostfile_hostname_ipaddr(char *hostname, struct sockaddr *hostaddr,
                    633:     u_short port, char **hostfile_hostname, char **hostfile_ipaddr)
                    634: {
                    635:        char ntop[NI_MAXHOST];
                    636:
                    637:        /*
                    638:         * We don't have the remote ip-address for connections
                    639:         * using a proxy command
                    640:         */
                    641:        if (hostfile_ipaddr != NULL) {
                    642:                if (options.proxy_command == NULL) {
                    643:                        if (getnameinfo(hostaddr, hostaddr->sa_len,
                    644:                            ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST) != 0)
1.259     djm       645:                        fatal("%s: getnameinfo failed", __func__);
1.229     djm       646:                        *hostfile_ipaddr = put_host_port(ntop, port);
                    647:                } else {
                    648:                        *hostfile_ipaddr = xstrdup("<no hostip for proxy "
                    649:                            "command>");
                    650:                }
                    651:        }
                    652:
                    653:        /*
                    654:         * Allow the user to record the key under a different name or
                    655:         * differentiate a non-standard port.  This is useful for ssh
                    656:         * tunneling over forwarded connections or if you run multiple
                    657:         * sshd's on different ports on the same machine.
                    658:         */
                    659:        if (hostfile_hostname != NULL) {
                    660:                if (options.host_key_alias != NULL) {
                    661:                        *hostfile_hostname = xstrdup(options.host_key_alias);
                    662:                        debug("using hostkeyalias: %s", *hostfile_hostname);
                    663:                } else {
                    664:                        *hostfile_hostname = put_host_port(hostname, port);
                    665:                }
                    666:        }
                    667: }
                    668:
1.39      deraadt   669: /*
1.108     markus    670:  * check whether the supplied host key is valid, return -1 if the key
1.234     djm       671:  * is not valid. user_hostfile[0] will not be updated if 'readonly' is true.
1.333   ! djm       672:  *
        !           673:  * If cert_fallbackp is not NULL then will attempt to convert certificate host
        !           674:  * keys to plain keys if no certificate match was found and will return
        !           675:  * non-zero via *cert_fallbackp if this fall-back was used.
1.39      deraadt   676:  */
1.197     dtucker   677: #define RDRW   0
                    678: #define RDONLY 1
                    679: #define ROQUIET        2
1.109     itojun    680: static int
1.197     dtucker   681: check_host_key(char *hostname, struct sockaddr *hostaddr, u_short port,
1.279     markus    682:     struct sshkey *host_key, int readonly,
1.234     djm       683:     char **user_hostfiles, u_int num_user_hostfiles,
1.333   ! djm       684:     char **system_hostfiles, u_int num_system_hostfiles, int *cert_fallbackp)
1.1       deraadt   685: {
1.234     djm       686:        HostStatus host_status;
                    687:        HostStatus ip_status;
1.279     markus    688:        struct sshkey *raw_key = NULL;
1.189     dtucker   689:        char *ip = NULL, *host = NULL;
1.204     grunk     690:        char hostline[1000], *hostp, *fp, *ra;
1.119     markus    691:        char msg[1024];
1.234     djm       692:        const char *type;
                    693:        const struct hostkey_entry *host_found, *ip_found;
1.312     dtucker   694:        int len, cancelled_forwarding = 0, confirmed;
1.333   ! djm       695:        int local = sockaddr_is_local(hostaddr), cert_fallback = 0;
1.280     markus    696:        int r, want_cert = sshkey_is_cert(host_key), host_ip_differ = 0;
1.257     djm       697:        int hostkey_trusted = 0; /* Known or explicitly accepted by user */
1.229     djm       698:        struct hostkeys *host_hostkeys, *ip_hostkeys;
1.234     djm       699:        u_int i;
1.49      markus    700:
1.333   ! djm       701:        if (cert_fallbackp != NULL)
        !           702:                *cert_fallbackp = 0;
        !           703:
1.49      markus    704:        /*
                    705:         * Force accepting of the host key for loopback/localhost. The
                    706:         * problem is that if the home directory is NFS-mounted to multiple
                    707:         * machines, localhost will refer to a different machine in each of
                    708:         * them, and the user will get bogus HOST_CHANGED warnings.  This
                    709:         * essentially disables host authentication for localhost; however,
                    710:         * this is probably not a real problem.
                    711:         */
1.111     markus    712:        if (options.no_host_authentication_for_localhost == 1 && local &&
                    713:            options.host_key_alias == NULL) {
1.88      markus    714:                debug("Forcing accepting of host key for "
                    715:                    "loopback/localhost.");
1.108     markus    716:                return 0;
1.49      markus    717:        }
1.42      markus    718:
                    719:        /*
1.229     djm       720:         * Prepare the hostname and address strings used for hostkey lookup.
                    721:         * In some cases, these will have a port number appended.
1.42      markus    722:         */
1.229     djm       723:        get_hostfile_hostname_ipaddr(hostname, hostaddr, port, &host, &ip);
1.206     grunk     724:
                    725:        /*
1.88      markus    726:         * Turn off check_host_ip if the connection is to localhost, via proxy
                    727:         * command or if we don't have a hostname to compare with
                    728:         */
1.189     dtucker   729:        if (options.check_host_ip && (local ||
                    730:            strcmp(hostname, ip) == 0 || options.proxy_command != NULL))
1.88      markus    731:                options.check_host_ip = 0;
1.86      markus    732:
1.229     djm       733:        host_hostkeys = init_hostkeys();
1.234     djm       734:        for (i = 0; i < num_user_hostfiles; i++)
                    735:                load_hostkeys(host_hostkeys, host, user_hostfiles[i]);
                    736:        for (i = 0; i < num_system_hostfiles; i++)
                    737:                load_hostkeys(host_hostkeys, host, system_hostfiles[i]);
1.229     djm       738:
                    739:        ip_hostkeys = NULL;
                    740:        if (!want_cert && options.check_host_ip) {
                    741:                ip_hostkeys = init_hostkeys();
1.234     djm       742:                for (i = 0; i < num_user_hostfiles; i++)
                    743:                        load_hostkeys(ip_hostkeys, ip, user_hostfiles[i]);
                    744:                for (i = 0; i < num_system_hostfiles; i++)
                    745:                        load_hostkeys(ip_hostkeys, ip, system_hostfiles[i]);
1.84      markus    746:        }
1.38      markus    747:
1.219     djm       748:  retry:
1.229     djm       749:        /* Reload these as they may have changed on cert->key downgrade */
1.280     markus    750:        want_cert = sshkey_is_cert(host_key);
                    751:        type = sshkey_type(host_key);
1.219     djm       752:
1.46      markus    753:        /*
1.170     djm       754:         * Check if the host key is present in the user's list of known
1.40      markus    755:         * hosts or in the systemwide list.
                    756:         */
1.229     djm       757:        host_status = check_key_in_hostkeys(host_hostkeys, host_key,
                    758:            &host_found);
                    759:
1.40      markus    760:        /*
                    761:         * Also perform check for the ip address, skip the check if we are
1.219     djm       762:         * localhost, looking for a certificate, or the hostname was an ip
                    763:         * address to begin with.
1.40      markus    764:         */
1.229     djm       765:        if (!want_cert && ip_hostkeys != NULL) {
                    766:                ip_status = check_key_in_hostkeys(ip_hostkeys, host_key,
                    767:                    &ip_found);
1.38      markus    768:                if (host_status == HOST_CHANGED &&
1.319     djm       769:                    (ip_status != HOST_CHANGED ||
1.229     djm       770:                    (ip_found != NULL &&
1.280     markus    771:                    !sshkey_equal(ip_found->key, host_found->key))))
1.38      markus    772:                        host_ip_differ = 1;
                    773:        } else
                    774:                ip_status = host_status;
                    775:
                    776:        switch (host_status) {
                    777:        case HOST_OK:
                    778:                /* The host is known and the key matches. */
1.219     djm       779:                debug("Host '%.200s' is known and matches the %s host %s.",
                    780:                    host, type, want_cert ? "certificate" : "key");
1.229     djm       781:                debug("Found %s in %s:%lu", want_cert ? "CA key" : "key",
                    782:                    host_found->file, host_found->line);
1.281     djm       783:                if (want_cert &&
                    784:                    !check_host_cert(options.host_key_alias == NULL ?
                    785:                    hostname : options.host_key_alias, host_key))
1.219     djm       786:                        goto fail;
1.88      markus    787:                if (options.check_host_ip && ip_status == HOST_NEW) {
1.219     djm       788:                        if (readonly || want_cert)
1.138     itojun    789:                                logit("%s host key for IP address "
1.108     markus    790:                                    "'%.128s' not in list of known hosts.",
                    791:                                    type, ip);
1.234     djm       792:                        else if (!add_host_to_hostfile(user_hostfiles[0], ip,
1.160     djm       793:                            host_key, options.hash_known_hosts))
1.138     itojun    794:                                logit("Failed to add the %s host key for IP "
1.108     markus    795:                                    "address '%.128s' to the list of known "
1.262     dtucker   796:                                    "hosts (%.500s).", type, ip,
1.234     djm       797:                                    user_hostfiles[0]);
1.88      markus    798:                        else
1.138     itojun    799:                                logit("Warning: Permanently added the %s host "
1.108     markus    800:                                    "key for IP address '%.128s' to the list "
                    801:                                    "of known hosts.", type, ip);
1.209     grunk     802:                } else if (options.visual_host_key) {
1.259     djm       803:                        fp = sshkey_fingerprint(host_key,
1.254     djm       804:                            options.fingerprint_hash, SSH_FP_DEFAULT);
1.259     djm       805:                        ra = sshkey_fingerprint(host_key,
1.254     djm       806:                            options.fingerprint_hash, SSH_FP_RANDOMART);
1.259     djm       807:                        if (fp == NULL || ra == NULL)
                    808:                                fatal("%s: sshkey_fingerprint fail", __func__);
1.264     djm       809:                        logit("Host key fingerprint is %s\n%s", fp, ra);
1.238     djm       810:                        free(ra);
                    811:                        free(fp);
1.38      markus    812:                }
1.257     djm       813:                hostkey_trusted = 1;
1.38      markus    814:                break;
                    815:        case HOST_NEW:
1.197     dtucker   816:                if (options.host_key_alias == NULL && port != 0 &&
                    817:                    port != SSH_DEFAULT_PORT) {
                    818:                        debug("checking without port identifier");
1.333   ! djm       819:                        /*
        !           820:                         * NB. do not perform cert->key fallback in this
        !           821:                         * recursive call. Fallback will only be performed in
        !           822:                         * the top-level call.
        !           823:                         */
1.212     stevesk   824:                        if (check_host_key(hostname, hostaddr, 0, host_key,
1.234     djm       825:                            ROQUIET, user_hostfiles, num_user_hostfiles,
1.333   ! djm       826:                            system_hostfiles, num_system_hostfiles,
        !           827:                            NULL) == 0) {
1.197     dtucker   828:                                debug("found matching key w/out port");
                    829:                                break;
                    830:                        }
                    831:                }
1.219     djm       832:                if (readonly || want_cert)
1.108     markus    833:                        goto fail;
1.38      markus    834:                /* The host is new. */
1.285     djm       835:                if (options.strict_host_key_checking ==
                    836:                    SSH_STRICT_HOSTKEY_YES) {
1.108     markus    837:                        /*
                    838:                         * User has requested strict host key checking.  We
                    839:                         * will not add the host key automatically.  The only
                    840:                         * alternative left is to abort.
                    841:                         */
                    842:                        error("No %s host key is known for %.200s and you "
                    843:                            "have requested strict checking.", type, host);
                    844:                        goto fail;
1.285     djm       845:                } else if (options.strict_host_key_checking ==
                    846:                    SSH_STRICT_HOSTKEY_ASK) {
1.145     jakob     847:                        char msg1[1024], msg2[1024];
                    848:
1.229     djm       849:                        if (show_other_keys(host_hostkeys, host_key))
1.145     jakob     850:                                snprintf(msg1, sizeof(msg1),
1.168     djm       851:                                    "\nbut keys of different type are already"
                    852:                                    " known for this host.");
1.145     jakob     853:                        else
                    854:                                snprintf(msg1, sizeof(msg1), ".");
1.38      markus    855:                        /* The default */
1.259     djm       856:                        fp = sshkey_fingerprint(host_key,
1.254     djm       857:                            options.fingerprint_hash, SSH_FP_DEFAULT);
1.259     djm       858:                        ra = sshkey_fingerprint(host_key,
1.254     djm       859:                            options.fingerprint_hash, SSH_FP_RANDOMART);
1.259     djm       860:                        if (fp == NULL || ra == NULL)
                    861:                                fatal("%s: sshkey_fingerprint fail", __func__);
1.145     jakob     862:                        msg2[0] = '\0';
                    863:                        if (options.verify_host_key_dns) {
1.153     jakob     864:                                if (matching_host_key_dns)
1.145     jakob     865:                                        snprintf(msg2, sizeof(msg2),
                    866:                                            "Matching host key fingerprint"
                    867:                                            " found in DNS.\n");
                    868:                                else
                    869:                                        snprintf(msg2, sizeof(msg2),
                    870:                                            "No matching host key fingerprint"
                    871:                                            " found in DNS.\n");
                    872:                        }
1.119     markus    873:                        snprintf(msg, sizeof(msg),
1.108     markus    874:                            "The authenticity of host '%.200s (%s)' can't be "
1.132     markus    875:                            "established%s\n"
1.209     grunk     876:                            "%s key fingerprint is %s.%s%s\n%s"
1.108     markus    877:                            "Are you sure you want to continue connecting "
1.312     dtucker   878:                            "(yes/no/[fingerprint])? ",
1.209     grunk     879:                            host, ip, msg1, type, fp,
                    880:                            options.visual_host_key ? "\n" : "",
                    881:                            options.visual_host_key ? ra : "",
                    882:                            msg2);
1.238     djm       883:                        free(ra);
1.312     dtucker   884:                        confirmed = confirm(msg, fp);
1.238     djm       885:                        free(fp);
1.312     dtucker   886:                        if (!confirmed)
1.108     markus    887:                                goto fail;
1.257     djm       888:                        hostkey_trusted = 1; /* user explicitly confirmed */
1.38      markus    889:                }
1.161     djm       890:                /*
1.285     djm       891:                 * If in "new" or "off" strict mode, add the key automatically
                    892:                 * to the local known_hosts file.
1.161     djm       893:                 */
1.88      markus    894:                if (options.check_host_ip && ip_status == HOST_NEW) {
1.229     djm       895:                        snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1.38      markus    896:                        hostp = hostline;
1.161     djm       897:                        if (options.hash_known_hosts) {
                    898:                                /* Add hash of host and IP separately */
1.234     djm       899:                                r = add_host_to_hostfile(user_hostfiles[0],
                    900:                                    host, host_key, options.hash_known_hosts) &&
                    901:                                    add_host_to_hostfile(user_hostfiles[0], ip,
1.161     djm       902:                                    host_key, options.hash_known_hosts);
                    903:                        } else {
                    904:                                /* Add unhashed "host,ip" */
1.234     djm       905:                                r = add_host_to_hostfile(user_hostfiles[0],
1.161     djm       906:                                    hostline, host_key,
                    907:                                    options.hash_known_hosts);
                    908:                        }
                    909:                } else {
1.234     djm       910:                        r = add_host_to_hostfile(user_hostfiles[0], host,
                    911:                            host_key, options.hash_known_hosts);
1.38      markus    912:                        hostp = host;
1.161     djm       913:                }
1.38      markus    914:
1.161     djm       915:                if (!r)
1.138     itojun    916:                        logit("Failed to add the host to the list of known "
1.234     djm       917:                            "hosts (%.500s).", user_hostfiles[0]);
1.38      markus    918:                else
1.138     itojun    919:                        logit("Warning: Permanently added '%.200s' (%s) to the "
1.108     markus    920:                            "list of known hosts.", hostp, type);
1.38      markus    921:                break;
1.220     djm       922:        case HOST_REVOKED:
                    923:                error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                    924:                error("@       WARNING: REVOKED HOST KEY DETECTED!               @");
                    925:                error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                    926:                error("The %s host key for %s is marked as revoked.", type, host);
                    927:                error("This could mean that a stolen key is being used to");
                    928:                error("impersonate this host.");
                    929:
                    930:                /*
                    931:                 * If strict host key checking is in use, the user will have
                    932:                 * to edit the key manually and we can only abort.
                    933:                 */
1.285     djm       934:                if (options.strict_host_key_checking !=
                    935:                    SSH_STRICT_HOSTKEY_OFF) {
1.220     djm       936:                        error("%s host key for %.200s was revoked and you have "
                    937:                            "requested strict checking.", type, host);
                    938:                        goto fail;
                    939:                }
                    940:                goto continue_unsafe;
                    941:
1.38      markus    942:        case HOST_CHANGED:
1.219     djm       943:                if (want_cert) {
                    944:                        /*
                    945:                         * This is only a debug() since it is valid to have
                    946:                         * CAs with wildcard DNS matches that don't match
                    947:                         * all hosts that one might visit.
                    948:                         */
                    949:                        debug("Host certificate authority does not "
1.229     djm       950:                            "match %s in %s:%lu", CA_MARKER,
                    951:                            host_found->file, host_found->line);
1.219     djm       952:                        goto fail;
                    953:                }
1.197     dtucker   954:                if (readonly == ROQUIET)
                    955:                        goto fail;
1.38      markus    956:                if (options.check_host_ip && host_ip_differ) {
1.158     avsm      957:                        char *key_msg;
1.38      markus    958:                        if (ip_status == HOST_NEW)
1.158     avsm      959:                                key_msg = "is unknown";
1.38      markus    960:                        else if (ip_status == HOST_OK)
1.158     avsm      961:                                key_msg = "is unchanged";
1.38      markus    962:                        else
1.158     avsm      963:                                key_msg = "has a different value";
1.38      markus    964:                        error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                    965:                        error("@       WARNING: POSSIBLE DNS SPOOFING DETECTED!          @");
                    966:                        error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1.72      markus    967:                        error("The %s host key for %s has changed,", type, host);
1.208     ian       968:                        error("and the key for the corresponding IP address %s", ip);
1.158     avsm      969:                        error("%s. This could either mean that", key_msg);
1.38      markus    970:                        error("DNS SPOOFING is happening or the IP address for the host");
1.85      markus    971:                        error("and its host key have changed at the same time.");
1.88      markus    972:                        if (ip_status != HOST_NEW)
1.229     djm       973:                                error("Offending key for IP in %s:%lu",
                    974:                                    ip_found->file, ip_found->line);
1.38      markus    975:                }
                    976:                /* The host key has changed. */
1.150     jakob     977:                warn_changed_key(host_key);
1.38      markus    978:                error("Add correct host key in %.100s to get rid of this message.",
1.234     djm       979:                    user_hostfiles[0]);
1.280     markus    980:                error("Offending %s key in %s:%lu",
                    981:                    sshkey_type(host_found->key),
1.229     djm       982:                    host_found->file, host_found->line);
1.38      markus    983:
1.40      markus    984:                /*
                    985:                 * If strict host key checking is in use, the user will have
                    986:                 * to edit the key manually and we can only abort.
                    987:                 */
1.285     djm       988:                if (options.strict_host_key_checking !=
                    989:                    SSH_STRICT_HOSTKEY_OFF) {
1.108     markus    990:                        error("%s host key for %.200s has changed and you have "
                    991:                            "requested strict checking.", type, host);
                    992:                        goto fail;
                    993:                }
1.38      markus    994:
1.220     djm       995:  continue_unsafe:
1.40      markus    996:                /*
                    997:                 * If strict host key checking has not been requested, allow
1.144     djm       998:                 * the connection but without MITM-able authentication or
1.194     stevesk   999:                 * forwarding.
1.40      markus   1000:                 */
1.38      markus   1001:                if (options.password_authentication) {
1.108     markus   1002:                        error("Password authentication is disabled to avoid "
                   1003:                            "man-in-the-middle attacks.");
1.38      markus   1004:                        options.password_authentication = 0;
1.210     dtucker  1005:                        cancelled_forwarding = 1;
1.144     djm      1006:                }
                   1007:                if (options.kbd_interactive_authentication) {
                   1008:                        error("Keyboard-interactive authentication is disabled"
                   1009:                            " to avoid man-in-the-middle attacks.");
                   1010:                        options.kbd_interactive_authentication = 0;
                   1011:                        options.challenge_response_authentication = 0;
1.210     dtucker  1012:                        cancelled_forwarding = 1;
1.144     djm      1013:                }
                   1014:                if (options.challenge_response_authentication) {
                   1015:                        error("Challenge/response authentication is disabled"
                   1016:                            " to avoid man-in-the-middle attacks.");
                   1017:                        options.challenge_response_authentication = 0;
1.210     dtucker  1018:                        cancelled_forwarding = 1;
1.38      markus   1019:                }
                   1020:                if (options.forward_agent) {
1.108     markus   1021:                        error("Agent forwarding is disabled to avoid "
                   1022:                            "man-in-the-middle attacks.");
1.38      markus   1023:                        options.forward_agent = 0;
1.210     dtucker  1024:                        cancelled_forwarding = 1;
1.83      markus   1025:                }
                   1026:                if (options.forward_x11) {
1.108     markus   1027:                        error("X11 forwarding is disabled to avoid "
                   1028:                            "man-in-the-middle attacks.");
1.83      markus   1029:                        options.forward_x11 = 0;
1.210     dtucker  1030:                        cancelled_forwarding = 1;
1.83      markus   1031:                }
1.108     markus   1032:                if (options.num_local_forwards > 0 ||
                   1033:                    options.num_remote_forwards > 0) {
                   1034:                        error("Port forwarding is disabled to avoid "
                   1035:                            "man-in-the-middle attacks.");
                   1036:                        options.num_local_forwards =
1.118     deraadt  1037:                            options.num_remote_forwards = 0;
1.210     dtucker  1038:                        cancelled_forwarding = 1;
1.194     stevesk  1039:                }
                   1040:                if (options.tun_open != SSH_TUNMODE_NO) {
                   1041:                        error("Tunnel forwarding is disabled to avoid "
                   1042:                            "man-in-the-middle attacks.");
                   1043:                        options.tun_open = SSH_TUNMODE_NO;
1.210     dtucker  1044:                        cancelled_forwarding = 1;
1.38      markus   1045:                }
1.210     dtucker  1046:                if (options.exit_on_forward_failure && cancelled_forwarding)
                   1047:                        fatal("Error: forwarding disabled due to host key "
                   1048:                            "check failure");
                   1049:
1.40      markus   1050:                /*
                   1051:                 * XXX Should permit the user to change to use the new id.
                   1052:                 * This could be done by converting the host key to an
                   1053:                 * identifying sentence, tell that the host identifies itself
1.218     dtucker  1054:                 * by that sentence, and ask the user if he/she wishes to
1.40      markus   1055:                 * accept the authentication.
                   1056:                 */
1.38      markus   1057:                break;
1.132     markus   1058:        case HOST_FOUND:
                   1059:                fatal("internal error");
                   1060:                break;
1.88      markus   1061:        }
                   1062:
                   1063:        if (options.check_host_ip && host_status != HOST_CHANGED &&
                   1064:            ip_status == HOST_CHANGED) {
1.119     markus   1065:                snprintf(msg, sizeof(msg),
                   1066:                    "Warning: the %s host key for '%.200s' "
                   1067:                    "differs from the key for the IP address '%.128s'"
1.229     djm      1068:                    "\nOffending key for IP in %s:%lu",
                   1069:                    type, host, ip, ip_found->file, ip_found->line);
1.119     markus   1070:                if (host_status == HOST_OK) {
                   1071:                        len = strlen(msg);
                   1072:                        snprintf(msg + len, sizeof(msg) - len,
1.229     djm      1073:                            "\nMatching host key in %s:%lu",
                   1074:                            host_found->file, host_found->line);
1.119     markus   1075:                }
1.285     djm      1076:                if (options.strict_host_key_checking ==
                   1077:                    SSH_STRICT_HOSTKEY_ASK) {
1.119     markus   1078:                        strlcat(msg, "\nAre you sure you want "
                   1079:                            "to continue connecting (yes/no)? ", sizeof(msg));
1.312     dtucker  1080:                        if (!confirm(msg, NULL))
1.108     markus   1081:                                goto fail;
1.285     djm      1082:                } else if (options.strict_host_key_checking !=
                   1083:                    SSH_STRICT_HOSTKEY_OFF) {
                   1084:                        logit("%s", msg);
                   1085:                        error("Exiting, you have requested strict checking.");
                   1086:                        goto fail;
1.119     markus   1087:                } else {
1.143     djm      1088:                        logit("%s", msg);
1.88      markus   1089:                }
1.257     djm      1090:        }
                   1091:
                   1092:        if (!hostkey_trusted && options.update_hostkeys) {
                   1093:                debug("%s: hostkey not known or explicitly trusted: "
                   1094:                    "disabling UpdateHostkeys", __func__);
                   1095:                options.update_hostkeys = 0;
1.38      markus   1096:        }
1.82      provos   1097:
1.238     djm      1098:        free(ip);
                   1099:        free(host);
1.229     djm      1100:        if (host_hostkeys != NULL)
                   1101:                free_hostkeys(host_hostkeys);
                   1102:        if (ip_hostkeys != NULL)
                   1103:                free_hostkeys(ip_hostkeys);
1.333   ! djm      1104:        if (cert_fallbackp != NULL)
        !          1105:                *cert_fallbackp = cert_fallback;
1.108     markus   1106:        return 0;
                   1107:
                   1108: fail:
1.333   ! djm      1109:        if (cert_fallbackp != NULL && want_cert &&
        !          1110:            host_status != HOST_REVOKED) {
1.219     djm      1111:                /*
                   1112:                 * No matching certificate. Downgrade cert to raw key and
                   1113:                 * search normally.
                   1114:                 */
                   1115:                debug("No matching CA found. Retry with plain key");
1.280     markus   1116:                if ((r = sshkey_from_private(host_key, &raw_key)) != 0)
                   1117:                        fatal("%s: sshkey_from_private: %s",
                   1118:                            __func__, ssh_err(r));
                   1119:                if ((r = sshkey_drop_cert(raw_key)) != 0)
                   1120:                        fatal("Couldn't drop certificate: %s", ssh_err(r));
1.219     djm      1121:                host_key = raw_key;
1.333   ! djm      1122:                cert_fallback = 1;
1.219     djm      1123:                goto retry;
                   1124:        }
1.293     dtucker  1125:        sshkey_free(raw_key);
1.238     djm      1126:        free(ip);
                   1127:        free(host);
1.229     djm      1128:        if (host_hostkeys != NULL)
                   1129:                free_hostkeys(host_hostkeys);
                   1130:        if (ip_hostkeys != NULL)
                   1131:                free_hostkeys(ip_hostkeys);
1.108     markus   1132:        return -1;
                   1133: }
                   1134:
1.333   ! djm      1135: /*
        !          1136:  * returns 0 if key verifies or -1 if key does NOT verify.
        !          1137:  *
        !          1138:  * If the host key was a certificate that was downgraded to a plain key in
        !          1139:  * the process of matching, then cert_fallbackp will be non-zero.
        !          1140:  */
1.108     markus   1141: int
1.333   ! djm      1142: verify_host_key(char *host, struct sockaddr *hostaddr, struct sshkey *host_key,
        !          1143:     int *cert_fallbackp)
1.108     markus   1144: {
1.267     djm      1145:        u_int i;
1.333   ! djm      1146:        int r = -1, flags = 0, cert_fallback = 0;
1.267     djm      1147:        char valid[64], *fp = NULL, *cafp = NULL;
1.252     djm      1148:        struct sshkey *plain = NULL;
1.229     djm      1149:
1.333   ! djm      1150:        if (cert_fallbackp != NULL)
        !          1151:                *cert_fallbackp = 0;
        !          1152:
1.252     djm      1153:        if ((fp = sshkey_fingerprint(host_key,
1.254     djm      1154:            options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
1.252     djm      1155:                error("%s: fingerprint host key: %s", __func__, ssh_err(r));
                   1156:                r = -1;
                   1157:                goto out;
                   1158:        }
                   1159:
1.267     djm      1160:        if (sshkey_is_cert(host_key)) {
                   1161:                if ((cafp = sshkey_fingerprint(host_key->cert->signature_key,
                   1162:                    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
                   1163:                        error("%s: fingerprint CA key: %s",
                   1164:                            __func__, ssh_err(r));
                   1165:                        r = -1;
                   1166:                        goto out;
                   1167:                }
                   1168:                sshkey_format_cert_validity(host_key->cert,
                   1169:                    valid, sizeof(valid));
                   1170:                debug("Server host certificate: %s %s, serial %llu "
                   1171:                    "ID \"%s\" CA %s %s valid %s",
                   1172:                    sshkey_ssh_name(host_key), fp,
1.269     djm      1173:                    (unsigned long long)host_key->cert->serial,
                   1174:                    host_key->cert->key_id,
1.267     djm      1175:                    sshkey_ssh_name(host_key->cert->signature_key), cafp,
                   1176:                    valid);
                   1177:                for (i = 0; i < host_key->cert->nprincipals; i++) {
                   1178:                        debug2("Server host certificate hostname: %s",
                   1179:                            host_key->cert->principals[i]);
                   1180:                }
                   1181:        } else {
1.276     djm      1182:                debug("Server host key: %s %s", sshkey_ssh_name(host_key), fp);
1.267     djm      1183:        }
1.252     djm      1184:
                   1185:        if (sshkey_equal(previous_host_key, host_key)) {
                   1186:                debug2("%s: server host key %s %s matches cached key",
                   1187:                    __func__, sshkey_type(host_key), fp);
                   1188:                r = 0;
                   1189:                goto out;
                   1190:        }
                   1191:
                   1192:        /* Check in RevokedHostKeys file if specified */
                   1193:        if (options.revoked_host_keys != NULL) {
                   1194:                r = sshkey_check_revoked(host_key, options.revoked_host_keys);
                   1195:                switch (r) {
                   1196:                case 0:
                   1197:                        break; /* not revoked */
                   1198:                case SSH_ERR_KEY_REVOKED:
                   1199:                        error("Host key %s %s revoked by file %s",
                   1200:                            sshkey_type(host_key), fp,
                   1201:                            options.revoked_host_keys);
                   1202:                        r = -1;
                   1203:                        goto out;
                   1204:                default:
                   1205:                        error("Error checking host key %s %s in "
                   1206:                            "revoked keys file %s: %s", sshkey_type(host_key),
                   1207:                            fp, options.revoked_host_keys, ssh_err(r));
                   1208:                        r = -1;
                   1209:                        goto out;
                   1210:                }
1.250     djm      1211:        }
                   1212:
1.247     djm      1213:        if (options.verify_host_key_dns) {
                   1214:                /*
                   1215:                 * XXX certs are not yet supported for DNS, so downgrade
                   1216:                 * them and try the plain key.
                   1217:                 */
1.252     djm      1218:                if ((r = sshkey_from_private(host_key, &plain)) != 0)
                   1219:                        goto out;
                   1220:                if (sshkey_is_cert(plain))
                   1221:                        sshkey_drop_cert(plain);
1.247     djm      1222:                if (verify_host_key_dns(host, hostaddr, plain, &flags) == 0) {
                   1223:                        if (flags & DNS_VERIFY_FOUND) {
                   1224:                                if (options.verify_host_key_dns == 1 &&
                   1225:                                    flags & DNS_VERIFY_MATCH &&
                   1226:                                    flags & DNS_VERIFY_SECURE) {
1.250     djm      1227:                                        r = 0;
1.252     djm      1228:                                        goto out;
1.247     djm      1229:                                }
                   1230:                                if (flags & DNS_VERIFY_MATCH) {
                   1231:                                        matching_host_key_dns = 1;
                   1232:                                } else {
1.287     djm      1233:                                        warn_changed_key(plain);
                   1234:                                        error("Update the SSHFP RR in DNS "
                   1235:                                            "with the new host key to get rid "
                   1236:                                            "of this message.");
1.247     djm      1237:                                }
1.153     jakob    1238:                        }
1.140     jakob    1239:                }
                   1240:        }
1.250     djm      1241:        r = check_host_key(host, hostaddr, options.port, host_key, RDRW,
1.234     djm      1242:            options.user_hostfiles, options.num_user_hostfiles,
1.333   ! djm      1243:            options.system_hostfiles, options.num_system_hostfiles,
        !          1244:            &cert_fallback);
1.250     djm      1245:
1.252     djm      1246: out:
                   1247:        sshkey_free(plain);
                   1248:        free(fp);
1.267     djm      1249:        free(cafp);
1.333   ! djm      1250:        if (r == 0) {
        !          1251:                if (host_key != NULL) {
        !          1252:                        sshkey_free(previous_host_key);
        !          1253:                        r = sshkey_from_private(host_key, &previous_host_key);
        !          1254:                }
        !          1255:                if (r == 0 && cert_fallbackp != NULL)
        !          1256:                        *cert_fallbackp = cert_fallback;
1.250     djm      1257:        }
                   1258:
                   1259:        return r;
1.51      markus   1260: }
1.70      markus   1261:
1.51      markus   1262: /*
                   1263:  * Starts a dialog with the server, and authenticates the current user on the
                   1264:  * server.  This does not need any extra privileges.  The basic connection
                   1265:  * to the server must already have been established before this is called.
                   1266:  * If login fails, this function prints an error and never returns.
                   1267:  * This function does not require super-user privileges.
                   1268:  */
                   1269: void
1.309     djm      1270: ssh_login(struct ssh *ssh, Sensitive *sensitive, const char *orighost,
1.229     djm      1271:     struct sockaddr *hostaddr, u_short port, struct passwd *pw, int timeout_ms)
1.51      markus   1272: {
1.241     djm      1273:        char *host;
1.70      markus   1274:        char *server_user, *local_user;
1.329     djm      1275:        int r;
1.70      markus   1276:
                   1277:        local_user = xstrdup(pw->pw_name);
                   1278:        server_user = options.user ? options.user : local_user;
1.51      markus   1279:
                   1280:        /* Convert the user-supplied hostname into all lowercase. */
                   1281:        host = xstrdup(orighost);
1.241     djm      1282:        lowercase(host);
1.51      markus   1283:
                   1284:        /* Exchange protocol version identification strings with the server. */
1.329     djm      1285:        if ((r = kex_exchange_identification(ssh, timeout_ms, NULL)) != 0)
                   1286:                sshpkt_fatal(ssh, r, "banner exchange");
1.51      markus   1287:
                   1288:        /* Put the connection into non-blocking mode. */
1.309     djm      1289:        ssh_packet_set_nonblocking(ssh);
1.51      markus   1290:
                   1291:        /* key exchange */
                   1292:        /* authenticate user */
1.261     dtucker  1293:        debug("Authenticating to %s:%d as '%s'", host, port, server_user);
1.309     djm      1294:        ssh_kex2(ssh, host, hostaddr, port);
                   1295:        ssh_userauth2(ssh, local_user, server_user, host, sensitive);
1.238     djm      1296:        free(local_user);
1.315     dtucker  1297:        free(host);
1.132     markus   1298: }
                   1299:
                   1300: /* print all known host keys for a given host, but skip keys of given type */
                   1301: static int
1.279     markus   1302: show_other_keys(struct hostkeys *hostkeys, struct sshkey *key)
1.132     markus   1303: {
1.242     djm      1304:        int type[] = {
                   1305:                KEY_RSA,
                   1306:                KEY_DSA,
                   1307:                KEY_ECDSA,
                   1308:                KEY_ED25519,
1.297     markus   1309:                KEY_XMSS,
1.242     djm      1310:                -1
                   1311:        };
1.229     djm      1312:        int i, ret = 0;
                   1313:        char *fp, *ra;
                   1314:        const struct hostkey_entry *found;
1.132     markus   1315:
                   1316:        for (i = 0; type[i] != -1; i++) {
                   1317:                if (type[i] == key->type)
                   1318:                        continue;
1.229     djm      1319:                if (!lookup_key_in_hostkeys_by_type(hostkeys, type[i], &found))
1.132     markus   1320:                        continue;
1.259     djm      1321:                fp = sshkey_fingerprint(found->key,
1.254     djm      1322:                    options.fingerprint_hash, SSH_FP_DEFAULT);
1.259     djm      1323:                ra = sshkey_fingerprint(found->key,
1.254     djm      1324:                    options.fingerprint_hash, SSH_FP_RANDOMART);
1.259     djm      1325:                if (fp == NULL || ra == NULL)
                   1326:                        fatal("%s: sshkey_fingerprint fail", __func__);
1.229     djm      1327:                logit("WARNING: %s key found for host %s\n"
                   1328:                    "in %s:%lu\n"
                   1329:                    "%s key fingerprint %s.",
1.300     markus   1330:                    sshkey_type(found->key),
1.229     djm      1331:                    found->host, found->file, found->line,
1.300     markus   1332:                    sshkey_type(found->key), fp);
1.229     djm      1333:                if (options.visual_host_key)
                   1334:                        logit("%s", ra);
1.238     djm      1335:                free(ra);
                   1336:                free(fp);
1.229     djm      1337:                ret = 1;
1.132     markus   1338:        }
1.229     djm      1339:        return ret;
1.150     jakob    1340: }
                   1341:
                   1342: static void
1.279     markus   1343: warn_changed_key(struct sshkey *host_key)
1.150     jakob    1344: {
                   1345:        char *fp;
                   1346:
1.259     djm      1347:        fp = sshkey_fingerprint(host_key, options.fingerprint_hash,
1.254     djm      1348:            SSH_FP_DEFAULT);
1.259     djm      1349:        if (fp == NULL)
                   1350:                fatal("%s: sshkey_fingerprint fail", __func__);
1.150     jakob    1351:
                   1352:        error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                   1353:        error("@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @");
                   1354:        error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                   1355:        error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
                   1356:        error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1.230     markus   1357:        error("It is also possible that a host key has just been changed.");
1.150     jakob    1358:        error("The fingerprint for the %s key sent by the remote host is\n%s.",
1.300     markus   1359:            sshkey_type(host_key), fp);
1.150     jakob    1360:        error("Please contact your system administrator.");
                   1361:
1.238     djm      1362:        free(fp);
1.171     reyk     1363: }
                   1364:
                   1365: /*
                   1366:  * Execute a local command
                   1367:  */
                   1368: int
                   1369: ssh_local_cmd(const char *args)
                   1370: {
                   1371:        char *shell;
                   1372:        pid_t pid;
                   1373:        int status;
1.231     djm      1374:        void (*osighand)(int);
1.171     reyk     1375:
                   1376:        if (!options.permit_local_command ||
                   1377:            args == NULL || !*args)
                   1378:                return (1);
                   1379:
1.226     djm      1380:        if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
1.171     reyk     1381:                shell = _PATH_BSHELL;
                   1382:
1.327     dtucker  1383:        osighand = ssh_signal(SIGCHLD, SIG_DFL);
1.171     reyk     1384:        pid = fork();
                   1385:        if (pid == 0) {
1.327     dtucker  1386:                ssh_signal(SIGPIPE, SIG_DFL);
1.171     reyk     1387:                debug3("Executing %s -c \"%s\"", shell, args);
                   1388:                execl(shell, shell, "-c", args, (char *)NULL);
                   1389:                error("Couldn't execute %s -c \"%s\": %s",
                   1390:                    shell, args, strerror(errno));
                   1391:                _exit(1);
                   1392:        } else if (pid == -1)
                   1393:                fatal("fork failed: %.100s", strerror(errno));
                   1394:        while (waitpid(pid, &status, 0) == -1)
                   1395:                if (errno != EINTR)
                   1396:                        fatal("Couldn't wait for child: %s", strerror(errno));
1.327     dtucker  1397:        ssh_signal(SIGCHLD, osighand);
1.171     reyk     1398:
                   1399:        if (!WIFEXITED(status))
                   1400:                return (1);
                   1401:
                   1402:        return (WEXITSTATUS(status));
1.266     jcs      1403: }
                   1404:
                   1405: void
1.328     djm      1406: maybe_add_key_to_agent(const char *authfile, struct sshkey *private,
                   1407:     const char *comment, const char *passphrase)
1.266     jcs      1408: {
                   1409:        int auth_sock = -1, r;
1.321     djm      1410:        const char *skprovider = NULL;
1.266     jcs      1411:
                   1412:        if (options.add_keys_to_agent == 0)
                   1413:                return;
                   1414:
                   1415:        if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
                   1416:                debug3("no authentication agent, not adding key");
                   1417:                return;
                   1418:        }
                   1419:
                   1420:        if (options.add_keys_to_agent == 2 &&
                   1421:            !ask_permission("Add key %s (%s) to agent?", authfile, comment)) {
                   1422:                debug3("user denied adding this key");
1.273     dtucker  1423:                close(auth_sock);
1.266     jcs      1424:                return;
                   1425:        }
1.322     markus   1426:        if (sshkey_is_sk(private))
1.321     djm      1427:                skprovider = options.sk_provider;
1.328     djm      1428:        if ((r = ssh_add_identity_constrained(auth_sock, private,
1.331     djm      1429:            comment == NULL ? authfile : comment,
                   1430:            options.add_keys_to_agent_lifespan,
1.321     djm      1431:            (options.add_keys_to_agent == 3), 0, skprovider)) == 0)
1.266     jcs      1432:                debug("identity added to agent: %s", authfile);
                   1433:        else
                   1434:                debug("could not add identity to agent: %s (%d)", authfile, r);
1.273     dtucker  1435:        close(auth_sock);
1.1       deraadt  1436: }