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

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