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

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