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

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