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

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