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

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