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

1.1       deraadt     1: /*
1.39      deraadt     2:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      3:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      4:  *                    All rights reserved
                      5:  * Created: Sat Mar 18 22:15:47 1995 ylo
                      6:  * Code to connect to a remote host, and to perform the client side of the
                      7:  * login (authentication) dialog.
                      8:  */
1.1       deraadt     9:
                     10: #include "includes.h"
1.70    ! markus     11: RCSID("$OpenBSD: sshconnect.c,v 1.28 2000/04/18 15:01:33 markus Exp $");
1.1       deraadt    12:
1.66      markus     13: #include <openssl/bn.h>
1.1       deraadt    14: #include "xmalloc.h"
                     15: #include "rsa.h"
                     16: #include "ssh.h"
1.59      markus     17: #include "buffer.h"
1.1       deraadt    18: #include "packet.h"
                     19: #include "authfd.h"
                     20: #include "cipher.h"
                     21: #include "mpaux.h"
                     22: #include "uidswap.h"
1.21      markus     23: #include "compat.h"
1.27      markus     24: #include "readconf.h"
1.1       deraadt    25:
1.59      markus     26: #include "bufaux.h"
1.66      markus     27: #include <openssl/rsa.h>
                     28: #include <openssl/dsa.h>
1.59      markus     29:
                     30: #include "ssh2.h"
1.66      markus     31: #include <openssl/md5.h>
                     32: #include <openssl/dh.h>
                     33: #include <openssl/hmac.h>
1.59      markus     34: #include "kex.h"
                     35: #include "myproposal.h"
1.58      markus     36: #include "key.h"
1.59      markus     37: #include "dsa.h"
1.58      markus     38: #include "hostfile.h"
1.70    ! markus     39: #include "authfile.h"
1.10      deraadt    40:
1.1       deraadt    41: /* Session id for the current session. */
                     42: unsigned char session_id[16];
1.70    ! markus     43: unsigned int supported_authentications = 0;
1.1       deraadt    44:
1.70    ! markus     45: unsigned char *session_id2 = NULL;
        !            46: int session_id2_len = 0;
1.51      markus     47:
1.70    ! markus     48: char *client_version_string = NULL;
        !            49: char *server_version_string = NULL;
1.59      markus     50:
1.43      markus     51: extern Options options;
1.50      markus     52: extern char *__progname;
1.43      markus     53:
1.39      deraadt    54: /*
                     55:  * Connect to the given ssh server using a proxy command.
                     56:  */
1.3       provos     57: int
1.41      markus     58: ssh_proxy_connect(const char *host, u_short port, uid_t original_real_uid,
1.3       provos     59:                  const char *proxy_command)
1.1       deraadt    60: {
1.38      markus     61:        Buffer command;
                     62:        const char *cp;
                     63:        char *command_string;
                     64:        int pin[2], pout[2];
1.69      deraadt    65:        pid_t pid;
1.49      markus     66:        char strport[NI_MAXSERV];
1.38      markus     67:
                     68:        /* Convert the port number into a string. */
1.49      markus     69:        snprintf(strport, sizeof strport, "%hu", port);
1.38      markus     70:
                     71:        /* Build the final command string in the buffer by making the
                     72:           appropriate substitutions to the given proxy command. */
                     73:        buffer_init(&command);
                     74:        for (cp = proxy_command; *cp; cp++) {
                     75:                if (cp[0] == '%' && cp[1] == '%') {
                     76:                        buffer_append(&command, "%", 1);
                     77:                        cp++;
                     78:                        continue;
                     79:                }
                     80:                if (cp[0] == '%' && cp[1] == 'h') {
                     81:                        buffer_append(&command, host, strlen(host));
                     82:                        cp++;
                     83:                        continue;
                     84:                }
                     85:                if (cp[0] == '%' && cp[1] == 'p') {
1.49      markus     86:                        buffer_append(&command, strport, strlen(strport));
1.38      markus     87:                        cp++;
                     88:                        continue;
                     89:                }
                     90:                buffer_append(&command, cp, 1);
                     91:        }
                     92:        buffer_append(&command, "\0", 1);
                     93:
                     94:        /* Get the final command string. */
                     95:        command_string = buffer_ptr(&command);
                     96:
                     97:        /* Create pipes for communicating with the proxy. */
                     98:        if (pipe(pin) < 0 || pipe(pout) < 0)
                     99:                fatal("Could not create pipes to communicate with the proxy: %.100s",
                    100:                      strerror(errno));
                    101:
                    102:        debug("Executing proxy command: %.500s", command_string);
                    103:
                    104:        /* Fork and execute the proxy command. */
                    105:        if ((pid = fork()) == 0) {
                    106:                char *argv[10];
                    107:
                    108:                /* Child.  Permanently give up superuser privileges. */
                    109:                permanently_set_uid(original_real_uid);
                    110:
                    111:                /* Redirect stdin and stdout. */
                    112:                close(pin[1]);
                    113:                if (pin[0] != 0) {
                    114:                        if (dup2(pin[0], 0) < 0)
                    115:                                perror("dup2 stdin");
                    116:                        close(pin[0]);
                    117:                }
                    118:                close(pout[0]);
                    119:                if (dup2(pout[1], 1) < 0)
                    120:                        perror("dup2 stdout");
                    121:                /* Cannot be 1 because pin allocated two descriptors. */
                    122:                close(pout[1]);
                    123:
                    124:                /* Stderr is left as it is so that error messages get
                    125:                   printed on the user's terminal. */
                    126:                argv[0] = "/bin/sh";
                    127:                argv[1] = "-c";
                    128:                argv[2] = command_string;
                    129:                argv[3] = NULL;
                    130:
                    131:                /* Execute the proxy command.  Note that we gave up any
                    132:                   extra privileges above. */
                    133:                execv("/bin/sh", argv);
                    134:                perror("/bin/sh");
                    135:                exit(1);
                    136:        }
                    137:        /* Parent. */
                    138:        if (pid < 0)
                    139:                fatal("fork failed: %.100s", strerror(errno));
                    140:
                    141:        /* Close child side of the descriptors. */
                    142:        close(pin[0]);
                    143:        close(pout[1]);
                    144:
                    145:        /* Free the command name. */
                    146:        buffer_free(&command);
                    147:
                    148:        /* Set the connection file descriptors. */
                    149:        packet_set_connection(pout[0], pin[1]);
1.1       deraadt   150:
1.38      markus    151:        return 1;
1.1       deraadt   152: }
                    153:
1.39      deraadt   154: /*
                    155:  * Creates a (possibly privileged) socket for use as the ssh connection.
                    156:  */
1.38      markus    157: int
1.49      markus    158: ssh_create_socket(uid_t original_real_uid, int privileged, int family)
1.1       deraadt   159: {
1.38      markus    160:        int sock;
1.1       deraadt   161:
1.40      markus    162:        /*
                    163:         * If we are running as root and want to connect to a privileged
                    164:         * port, bind our own socket to a privileged port.
                    165:         */
1.38      markus    166:        if (privileged) {
                    167:                int p = IPPORT_RESERVED - 1;
1.49      markus    168:                sock = rresvport_af(&p, family);
1.38      markus    169:                if (sock < 0)
1.55      markus    170:                        error("rresvport: af=%d %.100s", family, strerror(errno));
                    171:                else
                    172:                        debug("Allocated local port %d.", p);
1.38      markus    173:        } else {
1.46      markus    174:                /*
                    175:                 * Just create an ordinary socket on arbitrary port.  We use
                    176:                 * the user's uid to create the socket.
                    177:                 */
1.38      markus    178:                temporarily_use_uid(original_real_uid);
1.49      markus    179:                sock = socket(family, SOCK_STREAM, 0);
1.38      markus    180:                if (sock < 0)
1.49      markus    181:                        error("socket: %.100s", strerror(errno));
1.38      markus    182:                restore_uid();
                    183:        }
                    184:        return sock;
1.1       deraadt   185: }
                    186:
1.39      deraadt   187: /*
1.49      markus    188:  * Opens a TCP/IP connection to the remote server on the given host.
                    189:  * The address of the remote host will be returned in hostaddr.
                    190:  * If port is 0, the default port will be used.  If anonymous is zero,
1.39      deraadt   191:  * a privileged port will be allocated to make the connection.
                    192:  * This requires super-user privileges if anonymous is false.
                    193:  * Connection_attempts specifies the maximum number of tries (one per
                    194:  * second).  If proxy_command is non-NULL, it specifies the command (with %h
                    195:  * and %p substituted for host and port, respectively) to use to contact
                    196:  * the daemon.
                    197:  */
1.38      markus    198: int
1.49      markus    199: ssh_connect(const char *host, struct sockaddr_storage * hostaddr,
1.41      markus    200:            u_short port, int connection_attempts,
1.38      markus    201:            int anonymous, uid_t original_real_uid,
                    202:            const char *proxy_command)
1.1       deraadt   203: {
1.49      markus    204:        int sock = -1, attempt;
1.38      markus    205:        struct servent *sp;
1.49      markus    206:        struct addrinfo hints, *ai, *aitop;
                    207:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                    208:        int gaierr;
1.38      markus    209:        struct linger linger;
                    210:
                    211:        debug("ssh_connect: getuid %d geteuid %d anon %d",
                    212:              (int) getuid(), (int) geteuid(), anonymous);
                    213:
                    214:        /* Get default port if port has not been set. */
                    215:        if (port == 0) {
                    216:                sp = getservbyname(SSH_SERVICE_NAME, "tcp");
                    217:                if (sp)
                    218:                        port = ntohs(sp->s_port);
                    219:                else
                    220:                        port = SSH_DEFAULT_PORT;
                    221:        }
                    222:        /* If a proxy command is given, connect using it. */
                    223:        if (proxy_command != NULL)
                    224:                return ssh_proxy_connect(host, port, original_real_uid, proxy_command);
                    225:
                    226:        /* No proxy command. */
                    227:
1.49      markus    228:        memset(&hints, 0, sizeof(hints));
                    229:        hints.ai_family = IPv4or6;
                    230:        hints.ai_socktype = SOCK_STREAM;
                    231:        snprintf(strport, sizeof strport, "%d", port);
                    232:        if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
1.50      markus    233:                fatal("%s: %.100s: %s", __progname, host,
                    234:                    gai_strerror(gaierr));
1.38      markus    235:
1.46      markus    236:        /*
                    237:         * Try to connect several times.  On some machines, the first time
                    238:         * will sometimes fail.  In general socket code appears to behave
                    239:         * quite magically on many machines.
                    240:         */
1.38      markus    241:        for (attempt = 0; attempt < connection_attempts; attempt++) {
                    242:                if (attempt > 0)
                    243:                        debug("Trying again...");
                    244:
1.49      markus    245:                /* Loop through addresses for this host, and try each one in
1.68      markus    246:                   sequence until the connection succeeds. */
1.49      markus    247:                for (ai = aitop; ai; ai = ai->ai_next) {
                    248:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                    249:                                continue;
                    250:                        if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
                    251:                            ntop, sizeof(ntop), strport, sizeof(strport),
                    252:                            NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
                    253:                                error("ssh_connect: getnameinfo failed");
                    254:                                continue;
                    255:                        }
                    256:                        debug("Connecting to %.200s [%.100s] port %s.",
                    257:                                host, ntop, strport);
                    258:
                    259:                        /* Create a socket for connecting. */
1.68      markus    260:                        sock = ssh_create_socket(original_real_uid,
1.49      markus    261:                            !anonymous && geteuid() == 0 && port < IPPORT_RESERVED,
                    262:                            ai->ai_family);
                    263:                        if (sock < 0)
                    264:                                continue;
                    265:
                    266:                        /* Connect to the host.  We use the user's uid in the
                    267:                         * hope that it will help with tcp_wrappers showing
                    268:                         * the remote uid as root.
1.40      markus    269:                         */
1.38      markus    270:                        temporarily_use_uid(original_real_uid);
1.49      markus    271:                        if (connect(sock, ai->ai_addr, ai->ai_addrlen) >= 0) {
                    272:                                /* Successful connection. */
                    273:                                memcpy(hostaddr, ai->ai_addr, sizeof(*hostaddr));
1.38      markus    274:                                restore_uid();
                    275:                                break;
1.49      markus    276:                        } else {
1.38      markus    277:                                debug("connect: %.100s", strerror(errno));
                    278:                                restore_uid();
1.40      markus    279:                                /*
                    280:                                 * Close the failed socket; there appear to
                    281:                                 * be some problems when reusing a socket for
                    282:                                 * which connect() has already returned an
                    283:                                 * error.
                    284:                                 */
1.38      markus    285:                                shutdown(sock, SHUT_RDWR);
                    286:                                close(sock);
                    287:                        }
                    288:                }
1.49      markus    289:                if (ai)
                    290:                        break;  /* Successful connection. */
1.1       deraadt   291:
1.38      markus    292:                /* Sleep a moment before retrying. */
                    293:                sleep(1);
                    294:        }
1.49      markus    295:
                    296:        freeaddrinfo(aitop);
                    297:
1.38      markus    298:        /* Return failure if we didn't get a successful connection. */
                    299:        if (attempt >= connection_attempts)
                    300:                return 0;
                    301:
                    302:        debug("Connection established.");
                    303:
1.40      markus    304:        /*
                    305:         * Set socket options.  We would like the socket to disappear as soon
                    306:         * as it has been closed for whatever reason.
                    307:         */
                    308:        /* setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1.38      markus    309:        linger.l_onoff = 1;
                    310:        linger.l_linger = 5;
                    311:        setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
                    312:
                    313:        /* Set the connection. */
                    314:        packet_set_connection(sock, sock);
1.1       deraadt   315:
1.38      markus    316:        return 1;
1.1       deraadt   317: }
                    318:
1.70    ! markus    319:
1.39      deraadt   320: /*
                    321:  * Checks if the user has an authentication agent, and if so, tries to
                    322:  * authenticate using the agent.
                    323:  */
1.3       provos    324: int
                    325: try_agent_authentication()
1.1       deraadt   326: {
1.38      markus    327:        int status, type;
                    328:        char *comment;
                    329:        AuthenticationConnection *auth;
                    330:        unsigned char response[16];
                    331:        unsigned int i;
                    332:        BIGNUM *e, *n, *challenge;
                    333:
                    334:        /* Get connection to the agent. */
                    335:        auth = ssh_get_authentication_connection();
                    336:        if (!auth)
                    337:                return 0;
                    338:
                    339:        e = BN_new();
                    340:        n = BN_new();
                    341:        challenge = BN_new();
                    342:
                    343:        /* Loop through identities served by the agent. */
                    344:        for (status = ssh_get_first_identity(auth, e, n, &comment);
                    345:             status;
                    346:             status = ssh_get_next_identity(auth, e, n, &comment)) {
                    347:                int plen, clen;
                    348:
                    349:                /* Try this identity. */
                    350:                debug("Trying RSA authentication via agent with '%.100s'", comment);
                    351:                xfree(comment);
                    352:
                    353:                /* Tell the server that we are willing to authenticate using this key. */
                    354:                packet_start(SSH_CMSG_AUTH_RSA);
                    355:                packet_put_bignum(n);
                    356:                packet_send();
                    357:                packet_write_wait();
                    358:
                    359:                /* Wait for server's response. */
                    360:                type = packet_read(&plen);
                    361:
                    362:                /* The server sends failure if it doesn\'t like our key or
                    363:                   does not support RSA authentication. */
                    364:                if (type == SSH_SMSG_FAILURE) {
                    365:                        debug("Server refused our key.");
                    366:                        continue;
                    367:                }
                    368:                /* Otherwise it should have sent a challenge. */
                    369:                if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
                    370:                        packet_disconnect("Protocol error during RSA authentication: %d",
                    371:                                          type);
                    372:
                    373:                packet_get_bignum(challenge, &clen);
                    374:
                    375:                packet_integrity_check(plen, clen, type);
                    376:
                    377:                debug("Received RSA challenge from server.");
                    378:
                    379:                /* Ask the agent to decrypt the challenge. */
                    380:                if (!ssh_decrypt_challenge(auth, e, n, challenge,
                    381:                                           session_id, 1, response)) {
                    382:                        /* The agent failed to authenticate this identifier although it
                    383:                           advertised it supports this.  Just return a wrong value. */
                    384:                        log("Authentication agent failed to decrypt challenge.");
                    385:                        memset(response, 0, sizeof(response));
                    386:                }
                    387:                debug("Sending response to RSA challenge.");
1.1       deraadt   388:
1.38      markus    389:                /* Send the decrypted challenge back to the server. */
                    390:                packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
                    391:                for (i = 0; i < 16; i++)
                    392:                        packet_put_char(response[i]);
                    393:                packet_send();
                    394:                packet_write_wait();
                    395:
                    396:                /* Wait for response from the server. */
                    397:                type = packet_read(&plen);
                    398:
                    399:                /* The server returns success if it accepted the authentication. */
                    400:                if (type == SSH_SMSG_SUCCESS) {
                    401:                        debug("RSA authentication accepted by server.");
                    402:                        BN_clear_free(e);
                    403:                        BN_clear_free(n);
                    404:                        BN_clear_free(challenge);
                    405:                        return 1;
                    406:                }
                    407:                /* Otherwise it should return failure. */
                    408:                if (type != SSH_SMSG_FAILURE)
                    409:                        packet_disconnect("Protocol error waiting RSA auth response: %d",
                    410:                                          type);
                    411:        }
                    412:
                    413:        BN_clear_free(e);
                    414:        BN_clear_free(n);
                    415:        BN_clear_free(challenge);
                    416:
                    417:        debug("RSA authentication using agent refused.");
                    418:        return 0;
1.1       deraadt   419: }
                    420:
1.39      deraadt   421: /*
                    422:  * Computes the proper response to a RSA challenge, and sends the response to
                    423:  * the server.
                    424:  */
1.3       provos    425: void
1.38      markus    426: respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
1.1       deraadt   427: {
1.38      markus    428:        unsigned char buf[32], response[16];
                    429:        MD5_CTX md;
                    430:        int i, len;
                    431:
                    432:        /* Decrypt the challenge using the private key. */
                    433:        rsa_private_decrypt(challenge, challenge, prv);
                    434:
                    435:        /* Compute the response. */
                    436:        /* The response is MD5 of decrypted challenge plus session id. */
                    437:        len = BN_num_bytes(challenge);
                    438:        if (len <= 0 || len > sizeof(buf))
                    439:                packet_disconnect("respond_to_rsa_challenge: bad challenge length %d",
                    440:                                  len);
                    441:
                    442:        memset(buf, 0, sizeof(buf));
                    443:        BN_bn2bin(challenge, buf + sizeof(buf) - len);
                    444:        MD5_Init(&md);
                    445:        MD5_Update(&md, buf, 32);
                    446:        MD5_Update(&md, session_id, 16);
                    447:        MD5_Final(response, &md);
                    448:
                    449:        debug("Sending response to host key RSA challenge.");
                    450:
                    451:        /* Send the response back to the server. */
                    452:        packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
                    453:        for (i = 0; i < 16; i++)
                    454:                packet_put_char(response[i]);
                    455:        packet_send();
                    456:        packet_write_wait();
                    457:
                    458:        memset(buf, 0, sizeof(buf));
                    459:        memset(response, 0, sizeof(response));
                    460:        memset(&md, 0, sizeof(md));
1.1       deraadt   461: }
                    462:
1.39      deraadt   463: /*
                    464:  * Checks if the user has authentication file, and if so, tries to authenticate
                    465:  * the user using it.
                    466:  */
1.3       provos    467: int
1.43      markus    468: try_rsa_authentication(const char *authfile)
1.1       deraadt   469: {
1.38      markus    470:        BIGNUM *challenge;
1.70    ! markus    471:        Key *public;
        !           472:        Key *private;
1.38      markus    473:        char *passphrase, *comment;
                    474:        int type, i;
                    475:        int plen, clen;
                    476:
                    477:        /* Try to load identification for the authentication key. */
1.70    ! markus    478:        public = key_new(KEY_RSA);
        !           479:        if (!load_public_key(authfile, public, &comment)) {
        !           480:                key_free(public);
1.43      markus    481:                /* Could not load it.  Fail. */
                    482:                return 0;
1.38      markus    483:        }
                    484:        debug("Trying RSA authentication with key '%.100s'", comment);
                    485:
                    486:        /* Tell the server that we are willing to authenticate using this key. */
                    487:        packet_start(SSH_CMSG_AUTH_RSA);
1.70    ! markus    488:        packet_put_bignum(public->rsa->n);
1.38      markus    489:        packet_send();
                    490:        packet_write_wait();
                    491:
                    492:        /* We no longer need the public key. */
1.70    ! markus    493:        key_free(public);
1.38      markus    494:
                    495:        /* Wait for server's response. */
                    496:        type = packet_read(&plen);
                    497:
1.40      markus    498:        /*
                    499:         * The server responds with failure if it doesn\'t like our key or
                    500:         * doesn\'t support RSA authentication.
                    501:         */
1.38      markus    502:        if (type == SSH_SMSG_FAILURE) {
                    503:                debug("Server refused our key.");
                    504:                xfree(comment);
1.43      markus    505:                return 0;
1.38      markus    506:        }
                    507:        /* Otherwise, the server should respond with a challenge. */
                    508:        if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
                    509:                packet_disconnect("Protocol error during RSA authentication: %d", type);
                    510:
                    511:        /* Get the challenge from the packet. */
                    512:        challenge = BN_new();
                    513:        packet_get_bignum(challenge, &clen);
                    514:
                    515:        packet_integrity_check(plen, clen, type);
                    516:
                    517:        debug("Received RSA challenge from server.");
                    518:
1.70    ! markus    519:        private = key_new(KEY_RSA);
1.40      markus    520:        /*
                    521:         * Load the private key.  Try first with empty passphrase; if it
                    522:         * fails, ask for a passphrase.
                    523:         */
1.70    ! markus    524:        if (!load_private_key(authfile, "", private, NULL)) {
1.38      markus    525:                char buf[300];
                    526:                snprintf(buf, sizeof buf, "Enter passphrase for RSA key '%.100s': ",
1.45      deraadt   527:                    comment);
1.38      markus    528:                if (!options.batch_mode)
                    529:                        passphrase = read_passphrase(buf, 0);
                    530:                else {
                    531:                        debug("Will not query passphrase for %.100s in batch mode.",
                    532:                              comment);
                    533:                        passphrase = xstrdup("");
                    534:                }
                    535:
                    536:                /* Load the authentication file using the pasphrase. */
1.70    ! markus    537:                if (!load_private_key(authfile, passphrase, private, NULL)) {
1.38      markus    538:                        memset(passphrase, 0, strlen(passphrase));
                    539:                        xfree(passphrase);
                    540:                        error("Bad passphrase.");
                    541:
                    542:                        /* Send a dummy response packet to avoid protocol error. */
                    543:                        packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
                    544:                        for (i = 0; i < 16; i++)
                    545:                                packet_put_char(0);
                    546:                        packet_send();
                    547:                        packet_write_wait();
                    548:
                    549:                        /* Expect the server to reject it... */
                    550:                        packet_read_expect(&plen, SSH_SMSG_FAILURE);
                    551:                        xfree(comment);
                    552:                        return 0;
                    553:                }
                    554:                /* Destroy the passphrase. */
                    555:                memset(passphrase, 0, strlen(passphrase));
                    556:                xfree(passphrase);
                    557:        }
                    558:        /* We no longer need the comment. */
                    559:        xfree(comment);
                    560:
                    561:        /* Compute and send a response to the challenge. */
1.70    ! markus    562:        respond_to_rsa_challenge(challenge, private->rsa);
1.38      markus    563:
                    564:        /* Destroy the private key. */
1.70    ! markus    565:        key_free(private);
1.38      markus    566:
                    567:        /* We no longer need the challenge. */
                    568:        BN_clear_free(challenge);
                    569:
                    570:        /* Wait for response from the server. */
                    571:        type = packet_read(&plen);
                    572:        if (type == SSH_SMSG_SUCCESS) {
                    573:                debug("RSA authentication accepted by server.");
                    574:                return 1;
                    575:        }
                    576:        if (type != SSH_SMSG_FAILURE)
                    577:                packet_disconnect("Protocol error waiting RSA auth response: %d", type);
                    578:        debug("RSA authentication refused.");
                    579:        return 0;
1.1       deraadt   580: }
                    581:
1.39      deraadt   582: /*
                    583:  * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
                    584:  * authentication and RSA host authentication.
                    585:  */
1.3       provos    586: int
1.38      markus    587: try_rhosts_rsa_authentication(const char *local_user, RSA * host_key)
1.1       deraadt   588: {
1.38      markus    589:        int type;
                    590:        BIGNUM *challenge;
                    591:        int plen, clen;
                    592:
                    593:        debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
                    594:
                    595:        /* Tell the server that we are willing to authenticate using this key. */
                    596:        packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
                    597:        packet_put_string(local_user, strlen(local_user));
                    598:        packet_put_int(BN_num_bits(host_key->n));
                    599:        packet_put_bignum(host_key->e);
                    600:        packet_put_bignum(host_key->n);
                    601:        packet_send();
                    602:        packet_write_wait();
                    603:
                    604:        /* Wait for server's response. */
                    605:        type = packet_read(&plen);
                    606:
                    607:        /* The server responds with failure if it doesn't admit our
                    608:           .rhosts authentication or doesn't know our host key. */
                    609:        if (type == SSH_SMSG_FAILURE) {
                    610:                debug("Server refused our rhosts authentication or host key.");
                    611:                return 0;
                    612:        }
                    613:        /* Otherwise, the server should respond with a challenge. */
                    614:        if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
                    615:                packet_disconnect("Protocol error during RSA authentication: %d", type);
                    616:
                    617:        /* Get the challenge from the packet. */
                    618:        challenge = BN_new();
                    619:        packet_get_bignum(challenge, &clen);
                    620:
                    621:        packet_integrity_check(plen, clen, type);
                    622:
                    623:        debug("Received RSA challenge for host key from server.");
                    624:
                    625:        /* Compute a response to the challenge. */
                    626:        respond_to_rsa_challenge(challenge, host_key);
                    627:
                    628:        /* We no longer need the challenge. */
                    629:        BN_clear_free(challenge);
                    630:
                    631:        /* Wait for response from the server. */
                    632:        type = packet_read(&plen);
                    633:        if (type == SSH_SMSG_SUCCESS) {
                    634:                debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
                    635:                return 1;
                    636:        }
                    637:        if (type != SSH_SMSG_FAILURE)
                    638:                packet_disconnect("Protocol error waiting RSA auth response: %d", type);
                    639:        debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
                    640:        return 0;
1.1       deraadt   641: }
                    642:
                    643: #ifdef KRB4
1.38      markus    644: int
                    645: try_kerberos_authentication()
1.1       deraadt   646: {
1.38      markus    647:        KTEXT_ST auth;          /* Kerberos data */
                    648:        char *reply;
                    649:        char inst[INST_SZ];
                    650:        char *realm;
                    651:        CREDENTIALS cred;
                    652:        int r, type, plen;
1.57      markus    653:        socklen_t slen;
1.38      markus    654:        Key_schedule schedule;
                    655:        u_long checksum, cksum;
                    656:        MSG_DAT msg_data;
                    657:        struct sockaddr_in local, foreign;
                    658:        struct stat st;
                    659:
                    660:        /* Don't do anything if we don't have any tickets. */
                    661:        if (stat(tkt_string(), &st) < 0)
                    662:                return 0;
                    663:
                    664:        strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ);
                    665:
                    666:        realm = (char *) krb_realmofhost(get_canonical_hostname());
                    667:        if (!realm) {
                    668:                debug("Kerberos V4: no realm for %s", get_canonical_hostname());
                    669:                return 0;
                    670:        }
                    671:        /* This can really be anything. */
                    672:        checksum = (u_long) getpid();
                    673:
                    674:        r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
                    675:        if (r != KSUCCESS) {
                    676:                debug("Kerberos V4 krb_mk_req failed: %s", krb_err_txt[r]);
                    677:                return 0;
                    678:        }
                    679:        /* Get session key to decrypt the server's reply with. */
                    680:        r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
                    681:        if (r != KSUCCESS) {
                    682:                debug("get_cred failed: %s", krb_err_txt[r]);
                    683:                return 0;
                    684:        }
                    685:        des_key_sched((des_cblock *) cred.session, schedule);
                    686:
                    687:        /* Send authentication info to server. */
                    688:        packet_start(SSH_CMSG_AUTH_KERBEROS);
                    689:        packet_put_string((char *) auth.dat, auth.length);
                    690:        packet_send();
                    691:        packet_write_wait();
                    692:
                    693:        /* Zero the buffer. */
                    694:        (void) memset(auth.dat, 0, MAX_KTXT_LEN);
                    695:
1.57      markus    696:        slen = sizeof(local);
1.38      markus    697:        memset(&local, 0, sizeof(local));
                    698:        if (getsockname(packet_get_connection_in(),
1.57      markus    699:                        (struct sockaddr *) & local, &slen) < 0)
1.38      markus    700:                debug("getsockname failed: %s", strerror(errno));
                    701:
1.57      markus    702:        slen = sizeof(foreign);
1.38      markus    703:        memset(&foreign, 0, sizeof(foreign));
                    704:        if (getpeername(packet_get_connection_in(),
1.57      markus    705:                        (struct sockaddr *) & foreign, &slen) < 0) {
1.38      markus    706:                debug("getpeername failed: %s", strerror(errno));
                    707:                fatal_cleanup();
                    708:        }
                    709:        /* Get server reply. */
                    710:        type = packet_read(&plen);
                    711:        switch (type) {
                    712:        case SSH_SMSG_FAILURE:
                    713:                /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
                    714:                debug("Kerberos V4 authentication failed.");
                    715:                return 0;
                    716:                break;
                    717:
                    718:        case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
                    719:                /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
                    720:                debug("Kerberos V4 authentication accepted.");
                    721:
                    722:                /* Get server's response. */
                    723:                reply = packet_get_string((unsigned int *) &auth.length);
                    724:                memcpy(auth.dat, reply, auth.length);
                    725:                xfree(reply);
                    726:
                    727:                packet_integrity_check(plen, 4 + auth.length, type);
                    728:
1.40      markus    729:                /*
                    730:                 * If his response isn't properly encrypted with the session
                    731:                 * key, and the decrypted checksum fails to match, he's
                    732:                 * bogus. Bail out.
                    733:                 */
1.38      markus    734:                r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
                    735:                                &foreign, &local, &msg_data);
                    736:                if (r != KSUCCESS) {
                    737:                        debug("Kerberos V4 krb_rd_priv failed: %s", krb_err_txt[r]);
                    738:                        packet_disconnect("Kerberos V4 challenge failed!");
                    739:                }
                    740:                /* Fetch the (incremented) checksum that we supplied in the request. */
                    741:                (void) memcpy((char *) &cksum, (char *) msg_data.app_data, sizeof(cksum));
                    742:                cksum = ntohl(cksum);
                    743:
                    744:                /* If it matches, we're golden. */
                    745:                if (cksum == checksum + 1) {
                    746:                        debug("Kerberos V4 challenge successful.");
                    747:                        return 1;
                    748:                } else
                    749:                        packet_disconnect("Kerberos V4 challenge failed!");
                    750:                break;
                    751:
                    752:        default:
                    753:                packet_disconnect("Protocol error on Kerberos V4 response: %d", type);
                    754:        }
                    755:        return 0;
1.1       deraadt   756: }
1.38      markus    757:
1.1       deraadt   758: #endif /* KRB4 */
                    759:
                    760: #ifdef AFS
1.38      markus    761: int
                    762: send_kerberos_tgt()
1.1       deraadt   763: {
1.38      markus    764:        CREDENTIALS *creds;
                    765:        char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
                    766:        int r, type, plen;
1.57      markus    767:        char buffer[8192];
1.38      markus    768:        struct stat st;
                    769:
                    770:        /* Don't do anything if we don't have any tickets. */
                    771:        if (stat(tkt_string(), &st) < 0)
                    772:                return 0;
                    773:
                    774:        creds = xmalloc(sizeof(*creds));
                    775:
                    776:        if ((r = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm)) != KSUCCESS) {
                    777:                debug("Kerberos V4 tf_fullname failed: %s", krb_err_txt[r]);
                    778:                return 0;
                    779:        }
                    780:        if ((r = krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) {
                    781:                debug("Kerberos V4 get_cred failed: %s", krb_err_txt[r]);
                    782:                return 0;
                    783:        }
                    784:        if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
                    785:                debug("Kerberos V4 ticket expired: %s", TKT_FILE);
                    786:                return 0;
                    787:        }
1.57      markus    788:        creds_to_radix(creds, (unsigned char *)buffer);
1.38      markus    789:        xfree(creds);
                    790:
                    791:        packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
1.57      markus    792:        packet_put_string(buffer, strlen(buffer));
1.38      markus    793:        packet_send();
                    794:        packet_write_wait();
                    795:
                    796:        type = packet_read(&plen);
1.1       deraadt   797:
1.38      markus    798:        if (type == SSH_SMSG_FAILURE)
                    799:                debug("Kerberos TGT for realm %s rejected.", prealm);
                    800:        else if (type != SSH_SMSG_SUCCESS)
                    801:                packet_disconnect("Protocol error on Kerberos TGT response: %d", type);
                    802:
                    803:        return 1;
1.1       deraadt   804: }
                    805:
1.38      markus    806: void
                    807: send_afs_tokens(void)
1.1       deraadt   808: {
1.38      markus    809:        CREDENTIALS creds;
                    810:        struct ViceIoctl parms;
                    811:        struct ClearToken ct;
                    812:        int i, type, len, plen;
                    813:        char buf[2048], *p, *server_cell;
1.57      markus    814:        char buffer[8192];
1.38      markus    815:
                    816:        /* Move over ktc_GetToken, here's something leaner. */
                    817:        for (i = 0; i < 100; i++) {     /* just in case */
                    818:                parms.in = (char *) &i;
                    819:                parms.in_size = sizeof(i);
                    820:                parms.out = buf;
                    821:                parms.out_size = sizeof(buf);
                    822:                if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
                    823:                        break;
                    824:                p = buf;
                    825:
                    826:                /* Get secret token. */
                    827:                memcpy(&creds.ticket_st.length, p, sizeof(unsigned int));
                    828:                if (creds.ticket_st.length > MAX_KTXT_LEN)
                    829:                        break;
                    830:                p += sizeof(unsigned int);
                    831:                memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
                    832:                p += creds.ticket_st.length;
                    833:
                    834:                /* Get clear token. */
                    835:                memcpy(&len, p, sizeof(len));
                    836:                if (len != sizeof(struct ClearToken))
                    837:                        break;
                    838:                p += sizeof(len);
                    839:                memcpy(&ct, p, len);
                    840:                p += len;
                    841:                p += sizeof(len);       /* primary flag */
                    842:                server_cell = p;
                    843:
                    844:                /* Flesh out our credentials. */
                    845:                strlcpy(creds.service, "afs", sizeof creds.service);
                    846:                creds.instance[0] = '\0';
                    847:                strlcpy(creds.realm, server_cell, REALM_SZ);
                    848:                memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
                    849:                creds.issue_date = ct.BeginTimestamp;
                    850:                creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp);
                    851:                creds.kvno = ct.AuthHandle;
                    852:                snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
                    853:                creds.pinst[0] = '\0';
                    854:
                    855:                /* Encode token, ship it off. */
1.57      markus    856:                if (!creds_to_radix(&creds, (unsigned char*) buffer))
1.38      markus    857:                        break;
                    858:                packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
1.57      markus    859:                packet_put_string(buffer, strlen(buffer));
1.38      markus    860:                packet_send();
                    861:                packet_write_wait();
                    862:
                    863:                /* Roger, Roger. Clearance, Clarence. What's your vector,
                    864:                   Victor? */
                    865:                type = packet_read(&plen);
                    866:
                    867:                if (type == SSH_SMSG_FAILURE)
                    868:                        debug("AFS token for cell %s rejected.", server_cell);
                    869:                else if (type != SSH_SMSG_SUCCESS)
                    870:                        packet_disconnect("Protocol error on AFS token response: %d", type);
                    871:        }
1.1       deraadt   872: }
1.38      markus    873:
1.1       deraadt   874: #endif /* AFS */
                    875:
1.39      deraadt   876: /*
1.43      markus    877:  * Tries to authenticate with any string-based challenge/response system.
                    878:  * Note that the client code is not tied to s/key or TIS.
                    879:  */
                    880: int
                    881: try_skey_authentication()
                    882: {
1.57      markus    883:        int type, i;
                    884:        int payload_len;
                    885:        unsigned int clen;
1.43      markus    886:        char *challenge, *response;
                    887:
                    888:        debug("Doing skey authentication.");
                    889:
                    890:        /* request a challenge */
                    891:        packet_start(SSH_CMSG_AUTH_TIS);
                    892:        packet_send();
                    893:        packet_write_wait();
                    894:
                    895:        type = packet_read(&payload_len);
                    896:        if (type != SSH_SMSG_FAILURE &&
                    897:            type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
                    898:                packet_disconnect("Protocol error: got %d in response "
                    899:                                  "to skey-auth", type);
                    900:        }
                    901:        if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
                    902:                debug("No challenge for skey authentication.");
                    903:                return 0;
                    904:        }
1.57      markus    905:        challenge = packet_get_string(&clen);
                    906:        packet_integrity_check(payload_len, (4 + clen), type);
1.43      markus    907:        if (options.cipher == SSH_CIPHER_NONE)
                    908:                log("WARNING: Encryption is disabled! "
                    909:                    "Reponse will be transmitted in clear text.");
                    910:        fprintf(stderr, "%s\n", challenge);
1.54      markus    911:        xfree(challenge);
1.43      markus    912:        fflush(stderr);
                    913:        for (i = 0; i < options.number_of_password_prompts; i++) {
                    914:                if (i != 0)
                    915:                        error("Permission denied, please try again.");
                    916:                response = read_passphrase("Response: ", 0);
                    917:                packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
                    918:                packet_put_string(response, strlen(response));
                    919:                memset(response, 0, strlen(response));
                    920:                xfree(response);
                    921:                packet_send();
                    922:                packet_write_wait();
                    923:                type = packet_read(&payload_len);
                    924:                if (type == SSH_SMSG_SUCCESS)
                    925:                        return 1;
                    926:                if (type != SSH_SMSG_FAILURE)
                    927:                        packet_disconnect("Protocol error: got %d in response "
                    928:                                          "to skey-auth-reponse", type);
                    929:        }
                    930:        /* failure */
                    931:        return 0;
                    932: }
                    933:
                    934: /*
                    935:  * Tries to authenticate with plain passwd authentication.
                    936:  */
                    937: int
                    938: try_password_authentication(char *prompt)
                    939: {
                    940:        int type, i, payload_len;
                    941:        char *password;
                    942:
                    943:        debug("Doing password authentication.");
                    944:        if (options.cipher == SSH_CIPHER_NONE)
                    945:                log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
                    946:        for (i = 0; i < options.number_of_password_prompts; i++) {
                    947:                if (i != 0)
                    948:                        error("Permission denied, please try again.");
                    949:                password = read_passphrase(prompt, 0);
                    950:                packet_start(SSH_CMSG_AUTH_PASSWORD);
                    951:                packet_put_string(password, strlen(password));
                    952:                memset(password, 0, strlen(password));
                    953:                xfree(password);
                    954:                packet_send();
                    955:                packet_write_wait();
                    956:
                    957:                type = packet_read(&payload_len);
                    958:                if (type == SSH_SMSG_SUCCESS)
                    959:                        return 1;
                    960:                if (type != SSH_SMSG_FAILURE)
                    961:                        packet_disconnect("Protocol error: got %d in response to passwd auth", type);
                    962:        }
                    963:        /* failure */
                    964:        return 0;
                    965: }
                    966:
1.70    ! markus    967:
1.59      markus    968: char *
                    969: chop(char *s)
                    970: {
                    971:        char *t = s;
                    972:        while (*t) {
                    973:                if(*t == '\n' || *t == '\r') {
                    974:                        *t = '\0';
                    975:                        return s;
                    976:                }
                    977:                t++;
                    978:        }
                    979:        return s;
                    980:
                    981: }
                    982:
1.43      markus    983: /*
1.39      deraadt   984:  * Waits for the server identification string, and sends our own
                    985:  * identification string.
                    986:  */
1.38      markus    987: void
                    988: ssh_exchange_identification()
1.1       deraadt   989: {
1.38      markus    990:        char buf[256], remote_version[256];     /* must be same size! */
1.64      markus    991:        int remote_major, remote_minor, i, mismatch;
1.38      markus    992:        int connection_in = packet_get_connection_in();
                    993:        int connection_out = packet_get_connection_out();
                    994:
                    995:        /* Read other side\'s version identification. */
                    996:        for (i = 0; i < sizeof(buf) - 1; i++) {
1.56      markus    997:                int len = read(connection_in, &buf[i], 1);
                    998:                if (len < 0)
1.38      markus    999:                        fatal("ssh_exchange_identification: read: %.100s", strerror(errno));
1.56      markus   1000:                if (len != 1)
                   1001:                        fatal("ssh_exchange_identification: Connection closed by remote host");
1.38      markus   1002:                if (buf[i] == '\r') {
                   1003:                        buf[i] = '\n';
                   1004:                        buf[i + 1] = 0;
1.59      markus   1005:                        continue;               /**XXX wait for \n */
1.38      markus   1006:                }
                   1007:                if (buf[i] == '\n') {
                   1008:                        buf[i + 1] = 0;
                   1009:                        break;
                   1010:                }
                   1011:        }
                   1012:        buf[sizeof(buf) - 1] = 0;
1.59      markus   1013:        server_version_string = xstrdup(buf);
1.38      markus   1014:
1.40      markus   1015:        /*
                   1016:         * Check that the versions match.  In future this might accept
                   1017:         * several versions and set appropriate flags to handle them.
                   1018:         */
1.59      markus   1019:        if (sscanf(server_version_string, "SSH-%d.%d-%[^\n]\n",
                   1020:            &remote_major, &remote_minor, remote_version) != 3)
1.38      markus   1021:                fatal("Bad remote protocol version identification: '%.100s'", buf);
                   1022:        debug("Remote protocol version %d.%d, remote software version %.100s",
                   1023:              remote_major, remote_minor, remote_version);
                   1024:
1.59      markus   1025:        compat_datafellows(remote_version);
1.64      markus   1026:        mismatch = 0;
1.59      markus   1027:
1.64      markus   1028:        switch(remote_major) {
                   1029:        case 1:
                   1030:                if (remote_minor == 99 &&
                   1031:                    (options.protocol & SSH_PROTO_2) &&
                   1032:                    !(options.protocol & SSH_PROTO_1_PREFERRED)) {
                   1033:                        enable_compat20();
                   1034:                        break;
                   1035:                }
                   1036:                if (!(options.protocol & SSH_PROTO_1)) {
                   1037:                        mismatch = 1;
                   1038:                        break;
                   1039:                }
                   1040:                if (remote_minor < 3) {
                   1041:                        fatal("Remote machine has too old SSH software version.");
                   1042:                } else if (remote_minor == 3) {
                   1043:                        /* We speak 1.3, too. */
                   1044:                        enable_compat13();
                   1045:                        if (options.forward_agent) {
                   1046:                                log("Agent forwarding disabled for protocol 1.3");
                   1047:                                options.forward_agent = 0;
                   1048:                        }
                   1049:                }
                   1050:                break;
                   1051:        case 2:
                   1052:                if (options.protocol & SSH_PROTO_2) {
                   1053:                        enable_compat20();
                   1054:                        break;
1.38      markus   1055:                }
1.64      markus   1056:                /* FALLTHROUGH */
1.68      markus   1057:        default:
1.64      markus   1058:                mismatch = 1;
                   1059:                break;
1.38      markus   1060:        }
1.64      markus   1061:        if (mismatch)
1.38      markus   1062:                fatal("Protocol major versions differ: %d vs. %d",
1.64      markus   1063:                    (options.protocol & SSH_PROTO_2) ? PROTOCOL_MAJOR_2 : PROTOCOL_MAJOR_1,
                   1064:                    remote_major);
1.70    ! markus   1065:        if (compat20)
        !          1066:                packet_set_ssh2_format();
1.38      markus   1067:        /* Send our own protocol version identification. */
                   1068:        snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
1.64      markus   1069:            compat20 ? PROTOCOL_MAJOR_2 : PROTOCOL_MAJOR_1,
1.65      markus   1070:            compat20 ? PROTOCOL_MINOR_2 : PROTOCOL_MINOR_1,
1.59      markus   1071:            SSH_VERSION);
1.45      deraadt  1072:        if (atomicio(write, connection_out, buf, strlen(buf)) != strlen(buf))
1.38      markus   1073:                fatal("write: %.100s", strerror(errno));
1.59      markus   1074:        client_version_string = xstrdup(buf);
                   1075:        chop(client_version_string);
                   1076:        chop(server_version_string);
                   1077:        debug("Local version string %.100s", client_version_string);
1.1       deraadt  1078: }
                   1079:
1.38      markus   1080: int
                   1081: read_yes_or_no(const char *prompt, int defval)
1.1       deraadt  1082: {
1.38      markus   1083:        char buf[1024];
                   1084:        FILE *f;
                   1085:        int retval = -1;
                   1086:
                   1087:        if (isatty(0))
                   1088:                f = stdin;
                   1089:        else
                   1090:                f = fopen("/dev/tty", "rw");
                   1091:
                   1092:        if (f == NULL)
                   1093:                return 0;
                   1094:
                   1095:        fflush(stdout);
                   1096:
                   1097:        while (1) {
                   1098:                fprintf(stderr, "%s", prompt);
                   1099:                if (fgets(buf, sizeof(buf), f) == NULL) {
                   1100:                        /* Print a newline (the prompt probably didn\'t have one). */
                   1101:                        fprintf(stderr, "\n");
                   1102:                        strlcpy(buf, "no", sizeof buf);
                   1103:                }
                   1104:                /* Remove newline from response. */
                   1105:                if (strchr(buf, '\n'))
                   1106:                        *strchr(buf, '\n') = 0;
                   1107:
                   1108:                if (buf[0] == 0)
                   1109:                        retval = defval;
                   1110:                if (strcmp(buf, "yes") == 0)
                   1111:                        retval = 1;
                   1112:                if (strcmp(buf, "no") == 0)
                   1113:                        retval = 0;
                   1114:
                   1115:                if (retval != -1) {
                   1116:                        if (f != stdin)
                   1117:                                fclose(f);
                   1118:                        return retval;
                   1119:                }
1.1       deraadt  1120:        }
                   1121: }
                   1122:
1.39      deraadt  1123: /*
1.46      markus   1124:  * check whether the supplied host key is valid, return only if ok.
1.39      deraadt  1125:  */
1.46      markus   1126:
1.38      markus   1127: void
1.70    ! markus   1128: check_host_key(char *host, struct sockaddr *hostaddr, Key *host_key,
        !          1129:        const char *user_hostfile, const char *system_hostfile)
1.1       deraadt  1130: {
1.58      markus   1131:        Key *file_key;
1.46      markus   1132:        char *ip = NULL;
1.38      markus   1133:        char hostline[1000], *hostp;
                   1134:        HostStatus host_status;
                   1135:        HostStatus ip_status;
1.49      markus   1136:        int local = 0, host_ip_differ = 0;
                   1137:        char ntop[NI_MAXHOST];
                   1138:
                   1139:        /*
                   1140:         * Force accepting of the host key for loopback/localhost. The
                   1141:         * problem is that if the home directory is NFS-mounted to multiple
                   1142:         * machines, localhost will refer to a different machine in each of
                   1143:         * them, and the user will get bogus HOST_CHANGED warnings.  This
                   1144:         * essentially disables host authentication for localhost; however,
                   1145:         * this is probably not a real problem.
                   1146:         */
1.70    ! markus   1147:        /**  hostaddr == 0! */
1.49      markus   1148:        switch (hostaddr->sa_family) {
                   1149:        case AF_INET:
                   1150:                local = (ntohl(((struct sockaddr_in *)hostaddr)->sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
                   1151:                break;
                   1152:        case AF_INET6:
                   1153:                local = IN6_IS_ADDR_LOOPBACK(&(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
                   1154:                break;
                   1155:        default:
                   1156:                local = 0;
                   1157:                break;
                   1158:        }
                   1159:        if (local) {
                   1160:                debug("Forcing accepting of host key for loopback/localhost.");
                   1161:                return;
                   1162:        }
1.42      markus   1163:
                   1164:        /*
1.44      markus   1165:         * Turn off check_host_ip for proxy connects, since
1.42      markus   1166:         * we don't have the remote ip-address
                   1167:         */
                   1168:        if (options.proxy_command != NULL && options.check_host_ip)
                   1169:                options.check_host_ip = 0;
1.38      markus   1170:
1.49      markus   1171:        if (options.check_host_ip) {
                   1172:                if (getnameinfo(hostaddr, hostaddr->sa_len, ntop, sizeof(ntop),
                   1173:                    NULL, 0, NI_NUMERICHOST) != 0)
                   1174:                        fatal("check_host_key: getnameinfo failed");
                   1175:                ip = xstrdup(ntop);
                   1176:        }
1.38      markus   1177:
1.46      markus   1178:        /*
                   1179:         * Store the host key from the known host file in here so that we can
                   1180:         * compare it with the key for the IP address.
                   1181:         */
1.58      markus   1182:        file_key = key_new(host_key->type);
1.38      markus   1183:
1.40      markus   1184:        /*
                   1185:         * Check if the host key is present in the user\'s list of known
                   1186:         * hosts or in the systemwide list.
                   1187:         */
1.70    ! markus   1188:        host_status = check_host_in_hostfile(user_hostfile, host, host_key, file_key);
1.38      markus   1189:        if (host_status == HOST_NEW)
1.70    ! markus   1190:                host_status = check_host_in_hostfile(system_hostfile, host, host_key, file_key);
1.40      markus   1191:        /*
                   1192:         * Also perform check for the ip address, skip the check if we are
                   1193:         * localhost or the hostname was an ip address to begin with
                   1194:         */
1.38      markus   1195:        if (options.check_host_ip && !local && strcmp(host, ip)) {
1.58      markus   1196:                Key *ip_key = key_new(host_key->type);
1.70    ! markus   1197:                ip_status = check_host_in_hostfile(user_hostfile, ip, host_key, ip_key);
1.38      markus   1198:
                   1199:                if (ip_status == HOST_NEW)
1.70    ! markus   1200:                        ip_status = check_host_in_hostfile(system_hostfile, ip, host_key, ip_key);
1.38      markus   1201:                if (host_status == HOST_CHANGED &&
1.58      markus   1202:                    (ip_status != HOST_CHANGED || !key_equal(ip_key, file_key)))
1.38      markus   1203:                        host_ip_differ = 1;
                   1204:
1.58      markus   1205:                key_free(ip_key);
1.38      markus   1206:        } else
                   1207:                ip_status = host_status;
                   1208:
1.58      markus   1209:        key_free(file_key);
1.38      markus   1210:
                   1211:        switch (host_status) {
                   1212:        case HOST_OK:
                   1213:                /* The host is known and the key matches. */
                   1214:                debug("Host '%.200s' is known and matches the host key.", host);
                   1215:                if (options.check_host_ip) {
                   1216:                        if (ip_status == HOST_NEW) {
1.70    ! markus   1217:                                if (!add_host_to_hostfile(user_hostfile, ip, host_key))
1.38      markus   1218:                                        log("Failed to add the host key for IP address '%.30s' to the list of known hosts (%.30s).",
1.70    ! markus   1219:                                            ip, user_hostfile);
1.38      markus   1220:                                else
                   1221:                                        log("Warning: Permanently added host key for IP address '%.30s' to the list of known hosts.",
                   1222:                                            ip);
                   1223:                        } else if (ip_status != HOST_OK)
                   1224:                                log("Warning: the host key for '%.200s' differs from the key for the IP address '%.30s'",
                   1225:                                    host, ip);
                   1226:                }
                   1227:                break;
                   1228:        case HOST_NEW:
                   1229:                /* The host is new. */
                   1230:                if (options.strict_host_key_checking == 1) {
                   1231:                        /* User has requested strict host key checking.  We will not add the host key
                   1232:                           automatically.  The only alternative left is to abort. */
                   1233:                        fatal("No host key is known for %.200s and you have requested strict checking.", host);
                   1234:                } else if (options.strict_host_key_checking == 2) {
                   1235:                        /* The default */
                   1236:                        char prompt[1024];
1.58      markus   1237:                        char *fp = key_fingerprint(host_key);
1.38      markus   1238:                        snprintf(prompt, sizeof(prompt),
1.45      deraadt  1239:                            "The authenticity of host '%.200s' can't be established.\n"
1.58      markus   1240:                            "Key fingerprint is %s.\n"
1.45      deraadt  1241:                            "Are you sure you want to continue connecting (yes/no)? ",
1.58      markus   1242:                            host, fp);
1.38      markus   1243:                        if (!read_yes_or_no(prompt, -1))
                   1244:                                fatal("Aborted by user!\n");
                   1245:                }
                   1246:                if (options.check_host_ip && ip_status == HOST_NEW && strcmp(host, ip)) {
                   1247:                        snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
                   1248:                        hostp = hostline;
                   1249:                } else
                   1250:                        hostp = host;
                   1251:
                   1252:                /* If not in strict mode, add the key automatically to the local known_hosts file. */
1.70    ! markus   1253:                if (!add_host_to_hostfile(user_hostfile, hostp, host_key))
1.38      markus   1254:                        log("Failed to add the host to the list of known hosts (%.500s).",
1.70    ! markus   1255:                            user_hostfile);
1.38      markus   1256:                else
                   1257:                        log("Warning: Permanently added '%.200s' to the list of known hosts.",
                   1258:                            hostp);
                   1259:                break;
                   1260:        case HOST_CHANGED:
                   1261:                if (options.check_host_ip && host_ip_differ) {
                   1262:                        char *msg;
                   1263:                        if (ip_status == HOST_NEW)
                   1264:                                msg = "is unknown";
                   1265:                        else if (ip_status == HOST_OK)
                   1266:                                msg = "is unchanged";
                   1267:                        else
                   1268:                                msg = "has a different value";
                   1269:                        error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                   1270:                        error("@       WARNING: POSSIBLE DNS SPOOFING DETECTED!          @");
                   1271:                        error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                   1272:                        error("The host key for %s has changed,", host);
                   1273:                        error("and the key for the according IP address %s", ip);
                   1274:                        error("%s. This could either mean that", msg);
                   1275:                        error("DNS SPOOFING is happening or the IP address for the host");
                   1276:                        error("and its host key have changed at the same time");
                   1277:                }
                   1278:                /* The host key has changed. */
                   1279:                error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1.47      markus   1280:                error("@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @");
1.38      markus   1281:                error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                   1282:                error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
                   1283:                error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
                   1284:                error("It is also possible that the host key has just been changed.");
                   1285:                error("Please contact your system administrator.");
                   1286:                error("Add correct host key in %.100s to get rid of this message.",
1.70    ! markus   1287:                      user_hostfile);
1.38      markus   1288:
1.40      markus   1289:                /*
                   1290:                 * If strict host key checking is in use, the user will have
                   1291:                 * to edit the key manually and we can only abort.
                   1292:                 */
1.38      markus   1293:                if (options.strict_host_key_checking)
                   1294:                        fatal("Host key for %.200s has changed and you have requested strict checking.", host);
                   1295:
1.40      markus   1296:                /*
                   1297:                 * If strict host key checking has not been requested, allow
                   1298:                 * the connection but without password authentication or
                   1299:                 * agent forwarding.
                   1300:                 */
1.38      markus   1301:                if (options.password_authentication) {
                   1302:                        error("Password authentication is disabled to avoid trojan horses.");
                   1303:                        options.password_authentication = 0;
                   1304:                }
                   1305:                if (options.forward_agent) {
                   1306:                        error("Agent forwarding is disabled to avoid trojan horses.");
                   1307:                        options.forward_agent = 0;
                   1308:                }
1.40      markus   1309:                /*
                   1310:                 * XXX Should permit the user to change to use the new id.
                   1311:                 * This could be done by converting the host key to an
                   1312:                 * identifying sentence, tell that the host identifies itself
                   1313:                 * by that sentence, and ask the user if he/she whishes to
                   1314:                 * accept the authentication.
                   1315:                 */
1.38      markus   1316:                break;
                   1317:        }
                   1318:        if (options.check_host_ip)
                   1319:                xfree(ip);
1.46      markus   1320: }
                   1321:
                   1322: /*
1.59      markus   1323:  * SSH2 key exchange
                   1324:  */
1.70    ! markus   1325:
1.59      markus   1326: void
                   1327: ssh_kex2(char *host, struct sockaddr *hostaddr)
                   1328: {
                   1329:        Kex *kex;
                   1330:        char *cprop[PROPOSAL_MAX];
                   1331:        char *sprop[PROPOSAL_MAX];
                   1332:        Buffer *client_kexinit;
                   1333:        Buffer *server_kexinit;
                   1334:        int payload_len, dlen;
                   1335:        unsigned int klen, kout;
                   1336:        char *ptr;
                   1337:        char *signature = NULL;
                   1338:        unsigned int slen;
                   1339:        char *server_host_key_blob = NULL;
                   1340:        Key *server_host_key;
                   1341:        unsigned int sbloblen;
                   1342:        DH *dh;
                   1343:        BIGNUM *dh_server_pub = 0;
                   1344:        BIGNUM *shared_secret = 0;
                   1345:        int i;
                   1346:        unsigned char *kbuf;
                   1347:        unsigned char *hash;
                   1348:
                   1349: /* KEXINIT */
                   1350:
                   1351:        debug("Sending KEX init.");
1.64      markus   1352:        if (options.ciphers != NULL) {
1.68      markus   1353:                myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1.64      markus   1354:                myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
                   1355:        } else if (
                   1356:            options.cipher == SSH_CIPHER_ARCFOUR ||
1.68      markus   1357:            options.cipher == SSH_CIPHER_3DES_CBC ||
                   1358:            options.cipher == SSH_CIPHER_CAST128_CBC ||
                   1359:            options.cipher == SSH_CIPHER_BLOWFISH_CBC) {
1.64      markus   1360:                myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1.59      markus   1361:                myproposal[PROPOSAL_ENC_ALGS_STOC] = cipher_name(options.cipher);
                   1362:        }
                   1363:        if (options.compression) {
                   1364:                myproposal[PROPOSAL_COMP_ALGS_CTOS] = "zlib";
                   1365:                myproposal[PROPOSAL_COMP_ALGS_STOC] = "zlib";
                   1366:        } else {
                   1367:                myproposal[PROPOSAL_COMP_ALGS_CTOS] = "none";
                   1368:                myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
                   1369:        }
                   1370:        for (i = 0; i < PROPOSAL_MAX; i++)
                   1371:                cprop[i] = xstrdup(myproposal[i]);
                   1372:
                   1373:        client_kexinit = kex_init(cprop);
                   1374:        packet_start(SSH2_MSG_KEXINIT);
                   1375:        packet_put_raw(buffer_ptr(client_kexinit), buffer_len(client_kexinit));
                   1376:        packet_send();
                   1377:        packet_write_wait();
                   1378:
                   1379:        debug("done");
                   1380:
                   1381:        packet_read_expect(&payload_len, SSH2_MSG_KEXINIT);
                   1382:
                   1383:        /* save payload for session_id */
                   1384:        server_kexinit = xmalloc(sizeof(*server_kexinit));
                   1385:        buffer_init(server_kexinit);
                   1386:        ptr = packet_get_raw(&payload_len);
                   1387:        buffer_append(server_kexinit, ptr, payload_len);
                   1388:
                   1389:        /* skip cookie */
                   1390:        for (i = 0; i < 16; i++)
                   1391:                (void) packet_get_char();
                   1392:        /* kex init proposal strings */
                   1393:        for (i = 0; i < PROPOSAL_MAX; i++) {
                   1394:                sprop[i] = packet_get_string(NULL);
                   1395:                debug("got kexinit string: %s", sprop[i]);
                   1396:        }
                   1397:        i = (int) packet_get_char();
                   1398:        debug("first kex follow == %d", i);
                   1399:        i = packet_get_int();
                   1400:        debug("reserved == %d", i);
1.67      markus   1401:        packet_done();
1.59      markus   1402:
                   1403:        debug("done read kexinit");
                   1404:        kex = kex_choose_conf(cprop, sprop, 0);
                   1405:
                   1406: /* KEXDH */
                   1407:
                   1408:        debug("Sending SSH2_MSG_KEXDH_INIT.");
                   1409:
                   1410:        /* generate and send 'e', client DH public key */
1.63      markus   1411:        dh = dh_new_group1();
1.59      markus   1412:        packet_start(SSH2_MSG_KEXDH_INIT);
                   1413:        packet_put_bignum2(dh->pub_key);
                   1414:        packet_send();
                   1415:        packet_write_wait();
                   1416:
                   1417: #ifdef DEBUG_KEXDH
                   1418:        fprintf(stderr, "\np= ");
                   1419:        bignum_print(dh->p);
                   1420:        fprintf(stderr, "\ng= ");
                   1421:        bignum_print(dh->g);
                   1422:        fprintf(stderr, "\npub= ");
                   1423:        bignum_print(dh->pub_key);
                   1424:        fprintf(stderr, "\n");
1.68      markus   1425:        DHparams_print_fp(stderr, dh);
1.59      markus   1426: #endif
                   1427:
                   1428:        debug("Wait SSH2_MSG_KEXDH_REPLY.");
                   1429:
                   1430:        packet_read_expect(&payload_len, SSH2_MSG_KEXDH_REPLY);
                   1431:
                   1432:        debug("Got SSH2_MSG_KEXDH_REPLY.");
                   1433:
                   1434:        /* key, cert */
                   1435:        server_host_key_blob = packet_get_string(&sbloblen);
1.70    ! markus   1436:        server_host_key = dsa_key_from_blob(server_host_key_blob, sbloblen);
1.59      markus   1437:        if (server_host_key == NULL)
                   1438:                fatal("cannot decode server_host_key_blob");
                   1439:
1.70    ! markus   1440:        check_host_key(host, hostaddr, server_host_key,
        !          1441:            options.user_hostfile2, options.system_hostfile2);
1.59      markus   1442:
                   1443:        /* DH paramter f, server public DH key */
                   1444:        dh_server_pub = BN_new();
                   1445:        if (dh_server_pub == NULL)
                   1446:                fatal("dh_server_pub == NULL");
                   1447:        packet_get_bignum2(dh_server_pub, &dlen);
                   1448:
                   1449: #ifdef DEBUG_KEXDH
                   1450:        fprintf(stderr, "\ndh_server_pub= ");
                   1451:        bignum_print(dh_server_pub);
                   1452:        fprintf(stderr, "\n");
                   1453:        debug("bits %d", BN_num_bits(dh_server_pub));
                   1454: #endif
                   1455:
                   1456:        /* signed H */
                   1457:        signature = packet_get_string(&slen);
1.67      markus   1458:        packet_done();
1.63      markus   1459:
                   1460:        if (!dh_pub_is_valid(dh, dh_server_pub))
                   1461:                packet_disconnect("bad server public DH value");
1.59      markus   1462:
                   1463:        klen = DH_size(dh);
                   1464:        kbuf = xmalloc(klen);
                   1465:        kout = DH_compute_key(kbuf, dh_server_pub, dh);
                   1466: #ifdef DEBUG_KEXDH
                   1467:        debug("shared secret: len %d/%d", klen, kout);
1.68      markus   1468:        fprintf(stderr, "shared secret == ");
                   1469:        for (i = 0; i< kout; i++)
                   1470:                fprintf(stderr, "%02x", (kbuf[i])&0xff);
                   1471:        fprintf(stderr, "\n");
1.59      markus   1472: #endif
1.68      markus   1473:        shared_secret = BN_new();
1.59      markus   1474:
1.68      markus   1475:        BN_bin2bn(kbuf, kout, shared_secret);
1.59      markus   1476:        memset(kbuf, 0, klen);
                   1477:        xfree(kbuf);
                   1478:
                   1479:        /* calc and verify H */
                   1480:        hash = kex_hash(
                   1481:            client_version_string,
                   1482:            server_version_string,
                   1483:            buffer_ptr(client_kexinit), buffer_len(client_kexinit),
                   1484:            buffer_ptr(server_kexinit), buffer_len(server_kexinit),
                   1485:            server_host_key_blob, sbloblen,
                   1486:            dh->pub_key,
                   1487:            dh_server_pub,
                   1488:            shared_secret
                   1489:        );
1.60      markus   1490:        buffer_free(client_kexinit);
                   1491:        buffer_free(server_kexinit);
1.59      markus   1492:        xfree(client_kexinit);
                   1493:        xfree(server_kexinit);
                   1494: #ifdef DEBUG_KEXDH
1.68      markus   1495:        fprintf(stderr, "hash == ");
                   1496:        for (i = 0; i< 20; i++)
                   1497:                fprintf(stderr, "%02x", (hash[i])&0xff);
                   1498:        fprintf(stderr, "\n");
1.59      markus   1499: #endif
1.70    ! markus   1500:        if (dsa_verify(server_host_key, (unsigned char *)signature, slen, hash, 20) != 1)
        !          1501:                fatal("dsa_verify failed for server_host_key");
1.59      markus   1502:        key_free(server_host_key);
                   1503:
                   1504:        kex_derive_keys(kex, hash, shared_secret);
                   1505:        packet_set_kex(kex);
                   1506:
                   1507:        /* have keys, free DH */
                   1508:        DH_free(dh);
                   1509:
1.70    ! markus   1510:        /* save session id */
        !          1511:        session_id2_len = 20;
        !          1512:        session_id2 = xmalloc(session_id2_len);
        !          1513:        memcpy(session_id2, hash, session_id2_len);
        !          1514:
1.59      markus   1515:        debug("Wait SSH2_MSG_NEWKEYS.");
                   1516:        packet_read_expect(&payload_len, SSH2_MSG_NEWKEYS);
1.67      markus   1517:        packet_done();
1.59      markus   1518:        debug("GOT SSH2_MSG_NEWKEYS.");
                   1519:
                   1520:        debug("send SSH2_MSG_NEWKEYS.");
                   1521:        packet_start(SSH2_MSG_NEWKEYS);
                   1522:        packet_send();
                   1523:        packet_write_wait();
                   1524:        debug("done: send SSH2_MSG_NEWKEYS.");
                   1525:
1.62      markus   1526: #ifdef DEBUG_KEXDH
1.59      markus   1527:        /* send 1st encrypted/maced/compressed message */
                   1528:        packet_start(SSH2_MSG_IGNORE);
                   1529:        packet_put_cstring("markus");
                   1530:        packet_send();
                   1531:        packet_write_wait();
1.62      markus   1532: #endif
1.59      markus   1533:        debug("done: KEX2.");
                   1534: }
                   1535: /*
                   1536:  * Authenticate user
                   1537:  */
1.70    ! markus   1538: int
        !          1539: ssh2_try_passwd(const char *server_user, const char *host, const char *service)
        !          1540: {
        !          1541:        char prompt[80];
        !          1542:        char *password;
        !          1543:
        !          1544:        snprintf(prompt, sizeof(prompt), "%.30s@%.40s's password: ",
        !          1545:            server_user, host);
        !          1546:        password = read_passphrase(prompt, 0);
        !          1547:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
        !          1548:        packet_put_cstring(server_user);
        !          1549:        packet_put_cstring(service);
        !          1550:        packet_put_cstring("password");
        !          1551:        packet_put_char(0);
        !          1552:        packet_put_cstring(password);
        !          1553:        memset(password, 0, strlen(password));
        !          1554:        xfree(password);
        !          1555:        packet_send();
        !          1556:        packet_write_wait();
        !          1557:        return 1;
        !          1558: }
        !          1559:
        !          1560: int
        !          1561: ssh2_try_pubkey(char *filename,
        !          1562:     const char *server_user, const char *host, const char *service)
        !          1563: {
        !          1564:        Buffer b;
        !          1565:        Key *k;
        !          1566:        unsigned char *blob, *signature;
        !          1567:        int bloblen, slen;
        !          1568:
        !          1569:        debug("try pubkey: %s", filename);
        !          1570:
        !          1571:        k = key_new(KEY_DSA);
        !          1572:        if (!load_private_key(filename, "", k, NULL)) {
        !          1573:                int success = 0;
        !          1574:                char *passphrase;
        !          1575:                char prompt[300];
        !          1576:                 snprintf(prompt, sizeof prompt,
        !          1577:                     "Enter passphrase for DSA key '%.100s': ",
        !          1578:                      filename);
        !          1579:                passphrase = read_passphrase(prompt, 0);
        !          1580:                success = load_private_key(filename, passphrase, k, NULL);
        !          1581:                memset(passphrase, 0, strlen(passphrase));
        !          1582:                xfree(passphrase);
        !          1583:                if (!success)
        !          1584:                        return 0;
        !          1585:        }
        !          1586:        dsa_make_key_blob(k, &blob, &bloblen);
        !          1587:
        !          1588:        /* data to be signed */
        !          1589:        buffer_init(&b);
        !          1590:        buffer_append(&b, session_id2, session_id2_len);
        !          1591:        buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
        !          1592:        buffer_put_cstring(&b, server_user);
        !          1593:        buffer_put_cstring(&b, service);
        !          1594:        buffer_put_cstring(&b, "publickey");
        !          1595:        buffer_put_char(&b, 1);
        !          1596:        buffer_put_cstring(&b, KEX_DSS);
        !          1597:        buffer_put_string(&b, blob, bloblen);
        !          1598:
        !          1599:        /* generate signature */
        !          1600:        dsa_sign(k, &signature, &slen, buffer_ptr(&b), buffer_len(&b));
        !          1601:        key_free(k);
        !          1602: #ifdef DEBUG_DSS
        !          1603:        buffer_dump(&b);
        !          1604: #endif
        !          1605:        /* append signature */
        !          1606:        buffer_put_string(&b, signature, slen);
        !          1607:        xfree(signature);
        !          1608:
        !          1609:        /* skip session id and packet type */
        !          1610:        if (buffer_len(&b) < session_id2_len + 1)
        !          1611:                fatal("ssh2_try_pubkey: internal error");
        !          1612:        buffer_consume(&b, session_id2_len + 1);
        !          1613:
        !          1614:        /* put remaining data from buffer into packet */
        !          1615:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
        !          1616:        packet_put_raw(buffer_ptr(&b), buffer_len(&b));
        !          1617:        buffer_free(&b);
        !          1618:
        !          1619:        /* send */
        !          1620:        packet_send();
        !          1621:        packet_write_wait();
        !          1622:        return 1;
        !          1623: }
        !          1624:
1.59      markus   1625: void
1.70    ! markus   1626: ssh_userauth2(const char *server_user, char *host)
1.59      markus   1627: {
                   1628:        int type;
                   1629:        int plen;
1.70    ! markus   1630:        int sent;
1.59      markus   1631:        unsigned int dlen;
                   1632:        int partial;
1.70    ! markus   1633:        int i = 0;
1.59      markus   1634:        char *auths;
1.67      markus   1635:        char *service = "ssh-connection";               /* service name */
1.59      markus   1636:
                   1637:        debug("send SSH2_MSG_SERVICE_REQUEST");
                   1638:        packet_start(SSH2_MSG_SERVICE_REQUEST);
                   1639:        packet_put_cstring("ssh-userauth");
                   1640:        packet_send();
                   1641:        packet_write_wait();
                   1642:
                   1643:        type = packet_read(&plen);
                   1644:        if (type != SSH2_MSG_SERVICE_ACCEPT) {
                   1645:                fatal("denied SSH2_MSG_SERVICE_ACCEPT: %d", type);
                   1646:        }
1.67      markus   1647:        if (packet_remaining() > 0) {
                   1648:                char *reply = packet_get_string(&plen);
                   1649:                debug("service_accept: %s", reply);
                   1650:                xfree(reply);
                   1651:        } else {
                   1652:                /* payload empty for ssh-2.0.13 ?? */
                   1653:                log("buggy server: service_accept w/o service");
                   1654:        }
                   1655:        packet_done();
1.59      markus   1656:        debug("got SSH2_MSG_SERVICE_ACCEPT");
                   1657:
                   1658:        /* INITIAL request for auth */
                   1659:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
                   1660:        packet_put_cstring(server_user);
                   1661:        packet_put_cstring(service);
                   1662:        packet_put_cstring("none");
                   1663:        packet_send();
                   1664:        packet_write_wait();
                   1665:
                   1666:        for (;;) {
1.70    ! markus   1667:                sent = 0;
1.59      markus   1668:                type = packet_read(&plen);
                   1669:                if (type == SSH2_MSG_USERAUTH_SUCCESS)
                   1670:                        break;
                   1671:                if (type != SSH2_MSG_USERAUTH_FAILURE)
                   1672:                        fatal("access denied: %d", type);
                   1673:                /* SSH2_MSG_USERAUTH_FAILURE means: try again */
                   1674:                auths = packet_get_string(&dlen);
                   1675:                debug("authentications that can continue: %s", auths);
                   1676:                partial = packet_get_char();
1.67      markus   1677:                packet_done();
1.59      markus   1678:                if (partial)
                   1679:                        debug("partial success");
1.70    ! markus   1680:                if (strstr(auths, "publickey") != NULL) {
        !          1681:                        while (i < options.num_identity_files2) {
        !          1682:                                sent = ssh2_try_pubkey(
        !          1683:                                    options.identity_files2[i++],
        !          1684:                                    server_user, host, service);
        !          1685:                                if (sent)
        !          1686:                                        break;
        !          1687:                        }
        !          1688:                }
        !          1689:                if (!sent) {
        !          1690:                        if (strstr(auths, "password") != NULL) {
        !          1691:                                sent = ssh2_try_passwd(server_user, host, service);
        !          1692:                        } else {
        !          1693:                                fatal("passwd auth not supported: %s", auths);
        !          1694:                        }
        !          1695:                        if (!sent)
        !          1696:                                fatal("no more auths: %s", auths);
        !          1697:                }
1.59      markus   1698:                xfree(auths);
                   1699:        }
1.67      markus   1700:        packet_done();
1.59      markus   1701:        debug("ssh-userauth2 successfull");
                   1702: }
                   1703:
                   1704: /*
1.51      markus   1705:  * SSH1 key exchange
1.46      markus   1706:  */
                   1707: void
1.51      markus   1708: ssh_kex(char *host, struct sockaddr *hostaddr)
1.46      markus   1709: {
1.51      markus   1710:        int i;
1.46      markus   1711:        BIGNUM *key;
                   1712:        RSA *host_key;
                   1713:        RSA *public_key;
1.70    ! markus   1714:        Key k;
1.46      markus   1715:        int bits, rbits;
1.59      markus   1716:        int ssh_cipher_default = SSH_CIPHER_3DES;
1.46      markus   1717:        unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1.51      markus   1718:        unsigned char cookie[8];
                   1719:        unsigned int supported_ciphers;
1.46      markus   1720:        unsigned int server_flags, client_flags;
                   1721:        int payload_len, clen, sum_len = 0;
                   1722:        u_int32_t rand = 0;
                   1723:
                   1724:        debug("Waiting for server public key.");
                   1725:
                   1726:        /* Wait for a public key packet from the server. */
                   1727:        packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
                   1728:
1.51      markus   1729:        /* Get cookie from the packet. */
1.46      markus   1730:        for (i = 0; i < 8; i++)
1.51      markus   1731:                cookie[i] = packet_get_char();
1.46      markus   1732:
                   1733:        /* Get the public key. */
                   1734:        public_key = RSA_new();
                   1735:        bits = packet_get_int();/* bits */
                   1736:        public_key->e = BN_new();
                   1737:        packet_get_bignum(public_key->e, &clen);
                   1738:        sum_len += clen;
                   1739:        public_key->n = BN_new();
                   1740:        packet_get_bignum(public_key->n, &clen);
                   1741:        sum_len += clen;
                   1742:
                   1743:        rbits = BN_num_bits(public_key->n);
                   1744:        if (bits != rbits) {
                   1745:                log("Warning: Server lies about size of server public key: "
                   1746:                    "actual size is %d bits vs. announced %d.", rbits, bits);
                   1747:                log("Warning: This may be due to an old implementation of ssh.");
                   1748:        }
                   1749:        /* Get the host key. */
                   1750:        host_key = RSA_new();
                   1751:        bits = packet_get_int();/* bits */
                   1752:        host_key->e = BN_new();
                   1753:        packet_get_bignum(host_key->e, &clen);
                   1754:        sum_len += clen;
                   1755:        host_key->n = BN_new();
                   1756:        packet_get_bignum(host_key->n, &clen);
                   1757:        sum_len += clen;
                   1758:
                   1759:        rbits = BN_num_bits(host_key->n);
                   1760:        if (bits != rbits) {
                   1761:                log("Warning: Server lies about size of server host key: "
                   1762:                    "actual size is %d bits vs. announced %d.", rbits, bits);
                   1763:                log("Warning: This may be due to an old implementation of ssh.");
                   1764:        }
                   1765:
                   1766:        /* Get protocol flags. */
                   1767:        server_flags = packet_get_int();
                   1768:        packet_set_protocol_flags(server_flags);
                   1769:
                   1770:        supported_ciphers = packet_get_int();
                   1771:        supported_authentications = packet_get_int();
                   1772:
                   1773:        debug("Received server public key (%d bits) and host key (%d bits).",
                   1774:              BN_num_bits(public_key->n), BN_num_bits(host_key->n));
                   1775:
                   1776:        packet_integrity_check(payload_len,
                   1777:                               8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
                   1778:                               SSH_SMSG_PUBLIC_KEY);
1.70    ! markus   1779:        k.type = KEY_RSA;
        !          1780:        k.rsa = host_key;
        !          1781:        check_host_key(host, hostaddr, &k,
        !          1782:            options.user_hostfile, options.system_hostfile);
1.46      markus   1783:
                   1784:        client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
                   1785:
1.51      markus   1786:        compute_session_id(session_id, cookie, host_key->n, public_key->n);
1.38      markus   1787:
                   1788:        /* Generate a session key. */
                   1789:        arc4random_stir();
                   1790:
1.40      markus   1791:        /*
                   1792:         * Generate an encryption key for the session.   The key is a 256 bit
                   1793:         * random number, interpreted as a 32-byte key, with the least
                   1794:         * significant 8 bits being the first byte of the key.
                   1795:         */
1.38      markus   1796:        for (i = 0; i < 32; i++) {
                   1797:                if (i % 4 == 0)
                   1798:                        rand = arc4random();
                   1799:                session_key[i] = rand & 0xff;
                   1800:                rand >>= 8;
                   1801:        }
                   1802:
1.40      markus   1803:        /*
                   1804:         * According to the protocol spec, the first byte of the session key
                   1805:         * is the highest byte of the integer.  The session key is xored with
                   1806:         * the first 16 bytes of the session id.
                   1807:         */
1.38      markus   1808:        key = BN_new();
                   1809:        BN_set_word(key, 0);
                   1810:        for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
                   1811:                BN_lshift(key, key, 8);
                   1812:                if (i < 16)
                   1813:                        BN_add_word(key, session_key[i] ^ session_id[i]);
                   1814:                else
                   1815:                        BN_add_word(key, session_key[i]);
                   1816:        }
                   1817:
1.40      markus   1818:        /*
                   1819:         * Encrypt the integer using the public key and host key of the
                   1820:         * server (key with smaller modulus first).
                   1821:         */
1.38      markus   1822:        if (BN_cmp(public_key->n, host_key->n) < 0) {
                   1823:                /* Public key has smaller modulus. */
                   1824:                if (BN_num_bits(host_key->n) <
                   1825:                    BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
                   1826:                        fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
                   1827:                              "SSH_KEY_BITS_RESERVED %d",
                   1828:                              BN_num_bits(host_key->n),
                   1829:                              BN_num_bits(public_key->n),
                   1830:                              SSH_KEY_BITS_RESERVED);
                   1831:                }
                   1832:                rsa_public_encrypt(key, key, public_key);
                   1833:                rsa_public_encrypt(key, key, host_key);
                   1834:        } else {
                   1835:                /* Host key has smaller modulus (or they are equal). */
                   1836:                if (BN_num_bits(public_key->n) <
                   1837:                    BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) {
                   1838:                        fatal("respond_to_rsa_challenge: public_key %d < host_key %d + "
                   1839:                              "SSH_KEY_BITS_RESERVED %d",
                   1840:                              BN_num_bits(public_key->n),
                   1841:                              BN_num_bits(host_key->n),
                   1842:                              SSH_KEY_BITS_RESERVED);
                   1843:                }
                   1844:                rsa_public_encrypt(key, key, host_key);
                   1845:                rsa_public_encrypt(key, key, public_key);
                   1846:        }
                   1847:
1.52      markus   1848:        /* Destroy the public keys since we no longer need them. */
                   1849:        RSA_free(public_key);
                   1850:        RSA_free(host_key);
                   1851:
1.38      markus   1852:        if (options.cipher == SSH_CIPHER_NOT_SET) {
1.61      markus   1853:                if (cipher_mask1() & supported_ciphers & (1 << ssh_cipher_default))
1.38      markus   1854:                        options.cipher = ssh_cipher_default;
                   1855:                else {
                   1856:                        debug("Cipher %s not supported, using %.100s instead.",
                   1857:                              cipher_name(ssh_cipher_default),
                   1858:                              cipher_name(SSH_FALLBACK_CIPHER));
                   1859:                        options.cipher = SSH_FALLBACK_CIPHER;
                   1860:                }
                   1861:        }
                   1862:        /* Check that the selected cipher is supported. */
                   1863:        if (!(supported_ciphers & (1 << options.cipher)))
                   1864:                fatal("Selected cipher type %.100s not supported by server.",
                   1865:                      cipher_name(options.cipher));
                   1866:
                   1867:        debug("Encryption type: %.100s", cipher_name(options.cipher));
                   1868:
                   1869:        /* Send the encrypted session key to the server. */
                   1870:        packet_start(SSH_CMSG_SESSION_KEY);
                   1871:        packet_put_char(options.cipher);
                   1872:
1.51      markus   1873:        /* Send the cookie back to the server. */
1.38      markus   1874:        for (i = 0; i < 8; i++)
1.51      markus   1875:                packet_put_char(cookie[i]);
1.38      markus   1876:
1.52      markus   1877:        /* Send and destroy the encrypted encryption key integer. */
1.38      markus   1878:        packet_put_bignum(key);
1.52      markus   1879:        BN_clear_free(key);
1.38      markus   1880:
                   1881:        /* Send protocol flags. */
1.46      markus   1882:        packet_put_int(client_flags);
1.38      markus   1883:
                   1884:        /* Send the packet now. */
                   1885:        packet_send();
                   1886:        packet_write_wait();
                   1887:
                   1888:        debug("Sent encrypted session key.");
                   1889:
                   1890:        /* Set the encryption key. */
                   1891:        packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
                   1892:
                   1893:        /* We will no longer need the session key here.  Destroy any extra copies. */
                   1894:        memset(session_key, 0, sizeof(session_key));
                   1895:
1.40      markus   1896:        /*
                   1897:         * Expect a success message from the server.  Note that this message
                   1898:         * will be received in encrypted form.
                   1899:         */
1.38      markus   1900:        packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
                   1901:
                   1902:        debug("Received encrypted confirmation.");
1.51      markus   1903: }
                   1904:
                   1905: /*
                   1906:  * Authenticate user
                   1907:  */
                   1908: void
1.70    ! markus   1909: ssh_userauth(
        !          1910:     const char* local_user,
        !          1911:     const char* server_user,
        !          1912:     char *host,
        !          1913:     int host_key_valid, RSA *own_host_key)
1.51      markus   1914: {
                   1915:        int i, type;
                   1916:        int payload_len;
                   1917:
1.70    ! markus   1918:        if (supported_authentications == 0)
        !          1919:                fatal("ssh_userauth: server supports no auth methods");
1.38      markus   1920:
                   1921:        /* Send the name of the user to log in as on the server. */
                   1922:        packet_start(SSH_CMSG_USER);
                   1923:        packet_put_string(server_user, strlen(server_user));
1.16      dugsong  1924:        packet_send();
                   1925:        packet_write_wait();
1.38      markus   1926:
1.40      markus   1927:        /*
                   1928:         * The server should respond with success if no authentication is
                   1929:         * needed (the user has no password).  Otherwise the server responds
                   1930:         * with failure.
                   1931:         */
1.16      dugsong  1932:        type = packet_read(&payload_len);
1.38      markus   1933:
                   1934:        /* check whether the connection was accepted without authentication. */
1.16      dugsong  1935:        if (type == SSH_SMSG_SUCCESS)
1.38      markus   1936:                return;
1.16      dugsong  1937:        if (type != SSH_SMSG_FAILURE)
1.38      markus   1938:                packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
                   1939:                                  type);
                   1940:
                   1941: #ifdef AFS
                   1942:        /* Try Kerberos tgt passing if the server supports it. */
                   1943:        if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
                   1944:            options.kerberos_tgt_passing) {
                   1945:                if (options.cipher == SSH_CIPHER_NONE)
                   1946:                        log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
                   1947:                (void) send_kerberos_tgt();
                   1948:        }
                   1949:        /* Try AFS token passing if the server supports it. */
                   1950:        if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
                   1951:            options.afs_token_passing && k_hasafs()) {
                   1952:                if (options.cipher == SSH_CIPHER_NONE)
                   1953:                        log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
                   1954:                send_afs_tokens();
                   1955:        }
                   1956: #endif /* AFS */
                   1957:
                   1958: #ifdef KRB4
                   1959:        if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
                   1960:            options.kerberos_authentication) {
                   1961:                debug("Trying Kerberos authentication.");
                   1962:                if (try_kerberos_authentication()) {
                   1963:                        /* The server should respond with success or failure. */
                   1964:                        type = packet_read(&payload_len);
                   1965:                        if (type == SSH_SMSG_SUCCESS)
                   1966:                                return;
                   1967:                        if (type != SSH_SMSG_FAILURE)
                   1968:                                packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
                   1969:                }
                   1970:        }
                   1971: #endif /* KRB4 */
                   1972:
1.40      markus   1973:        /*
                   1974:         * Use rhosts authentication if running in privileged socket and we
                   1975:         * do not wish to remain anonymous.
                   1976:         */
1.38      markus   1977:        if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
                   1978:            options.rhosts_authentication) {
                   1979:                debug("Trying rhosts authentication.");
                   1980:                packet_start(SSH_CMSG_AUTH_RHOSTS);
                   1981:                packet_put_string(local_user, strlen(local_user));
                   1982:                packet_send();
                   1983:                packet_write_wait();
                   1984:
                   1985:                /* The server should respond with success or failure. */
                   1986:                type = packet_read(&payload_len);
                   1987:                if (type == SSH_SMSG_SUCCESS)
                   1988:                        return;
                   1989:                if (type != SSH_SMSG_FAILURE)
                   1990:                        packet_disconnect("Protocol error: got %d in response to rhosts auth",
                   1991:                                          type);
                   1992:        }
1.40      markus   1993:        /*
                   1994:         * Try .rhosts or /etc/hosts.equiv authentication with RSA host
                   1995:         * authentication.
                   1996:         */
1.38      markus   1997:        if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
                   1998:            options.rhosts_rsa_authentication && host_key_valid) {
                   1999:                if (try_rhosts_rsa_authentication(local_user, own_host_key))
                   2000:                        return;
                   2001:        }
                   2002:        /* Try RSA authentication if the server supports it. */
                   2003:        if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
                   2004:            options.rsa_authentication) {
1.40      markus   2005:                /*
                   2006:                 * Try RSA authentication using the authentication agent. The
                   2007:                 * agent is tried first because no passphrase is needed for
                   2008:                 * it, whereas identity files may require passphrases.
                   2009:                 */
1.38      markus   2010:                if (try_agent_authentication())
                   2011:                        return;
                   2012:
                   2013:                /* Try RSA authentication for each identity. */
                   2014:                for (i = 0; i < options.num_identity_files; i++)
1.43      markus   2015:                        if (try_rsa_authentication(options.identity_files[i]))
1.38      markus   2016:                                return;
                   2017:        }
                   2018:        /* Try skey authentication if the server supports it. */
                   2019:        if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
                   2020:            options.skey_authentication && !options.batch_mode) {
1.43      markus   2021:                if (try_skey_authentication())
                   2022:                        return;
1.38      markus   2023:        }
                   2024:        /* Try password authentication if the server supports it. */
                   2025:        if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
                   2026:            options.password_authentication && !options.batch_mode) {
                   2027:                char prompt[80];
1.45      deraadt  2028:
1.43      markus   2029:                snprintf(prompt, sizeof(prompt), "%.30s@%.40s's password: ",
1.45      deraadt  2030:                    server_user, host);
1.43      markus   2031:                if (try_password_authentication(prompt))
                   2032:                        return;
1.38      markus   2033:        }
                   2034:        /* All authentication methods have failed.  Exit with an error message. */
                   2035:        fatal("Permission denied.");
                   2036:        /* NOTREACHED */
1.51      markus   2037: }
1.70    ! markus   2038:
1.51      markus   2039: /*
                   2040:  * Starts a dialog with the server, and authenticates the current user on the
                   2041:  * server.  This does not need any extra privileges.  The basic connection
                   2042:  * to the server must already have been established before this is called.
                   2043:  * If login fails, this function prints an error and never returns.
                   2044:  * This function does not require super-user privileges.
                   2045:  */
                   2046: void
                   2047: ssh_login(int host_key_valid, RSA *own_host_key, const char *orighost,
                   2048:     struct sockaddr *hostaddr, uid_t original_real_uid)
                   2049: {
1.70    ! markus   2050:        struct passwd *pw;
1.51      markus   2051:        char *host, *cp;
1.70    ! markus   2052:        char *server_user, *local_user;
        !          2053:
        !          2054:        /* Get local user name.  Use it as server user if no user name was given. */
        !          2055:        pw = getpwuid(original_real_uid);
        !          2056:        if (!pw)
        !          2057:                fatal("User id %d not found from user database.", original_real_uid);
        !          2058:        local_user = xstrdup(pw->pw_name);
        !          2059:        server_user = options.user ? options.user : local_user;
1.51      markus   2060:
                   2061:        /* Convert the user-supplied hostname into all lowercase. */
                   2062:        host = xstrdup(orighost);
                   2063:        for (cp = host; *cp; cp++)
                   2064:                if (isupper(*cp))
                   2065:                        *cp = tolower(*cp);
                   2066:
                   2067:        /* Exchange protocol version identification strings with the server. */
                   2068:        ssh_exchange_identification();
                   2069:
                   2070:        /* Put the connection into non-blocking mode. */
                   2071:        packet_set_nonblocking();
                   2072:
                   2073:        /* key exchange */
                   2074:        /* authenticate user */
1.59      markus   2075:        if (compat20) {
                   2076:                ssh_kex2(host, hostaddr);
1.70    ! markus   2077:                ssh_userauth2(server_user, host);
1.59      markus   2078:        } else {
                   2079:                ssh_kex(host, hostaddr);
1.70    ! markus   2080:                ssh_userauth(local_user, server_user, host, host_key_valid, own_host_key);
1.59      markus   2081:        }
1.1       deraadt  2082: }