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

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