[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.271

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