[BACK]Return to sshconnect2.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/sshconnect2.c, Revision 1.35

1.1       markus      1: /*
                      2:  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
                      3:  *
                      4:  * Redistribution and use in source and binary forms, with or without
                      5:  * modification, are permitted provided that the following conditions
                      6:  * are met:
                      7:  * 1. Redistributions of source code must retain the above copyright
                      8:  *    notice, this list of conditions and the following disclaimer.
                      9:  * 2. Redistributions in binary form must reproduce the above copyright
                     10:  *    notice, this list of conditions and the following disclaimer in the
                     11:  *    documentation and/or other materials provided with the distribution.
                     12:  *
                     13:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     14:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     15:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     16:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     17:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     18:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     19:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     20:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     21:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     22:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                     23:  */
                     24:
                     25: #include "includes.h"
1.35    ! markus     26: RCSID("$OpenBSD: sshconnect2.c,v 1.34 2000/12/27 12:34:50 markus Exp $");
1.1       markus     27:
                     28: #include <openssl/bn.h>
                     29: #include <openssl/rsa.h>
                     30: #include <openssl/dsa.h>
                     31: #include <openssl/md5.h>
                     32: #include <openssl/dh.h>
                     33: #include <openssl/hmac.h>
                     34:
                     35: #include "ssh.h"
                     36: #include "xmalloc.h"
                     37: #include "rsa.h"
                     38: #include "buffer.h"
                     39: #include "packet.h"
                     40: #include "uidswap.h"
                     41: #include "compat.h"
                     42: #include "readconf.h"
                     43: #include "bufaux.h"
                     44: #include "ssh2.h"
                     45: #include "kex.h"
                     46: #include "myproposal.h"
                     47: #include "key.h"
                     48: #include "sshconnect.h"
                     49: #include "authfile.h"
1.23      markus     50: #include "cli.h"
1.20      markus     51: #include "dispatch.h"
1.17      markus     52: #include "authfd.h"
1.1       markus     53:
1.22      provos     54: void ssh_dh1_client(Kex *, char *, struct sockaddr *, Buffer *, Buffer *);
                     55: void ssh_dhgex_client(Kex *, char *, struct sockaddr *, Buffer *, Buffer *);
                     56:
1.1       markus     57: /* import */
                     58: extern char *client_version_string;
                     59: extern char *server_version_string;
                     60: extern Options options;
                     61:
                     62: /*
                     63:  * SSH2 key exchange
                     64:  */
                     65:
1.32      markus     66: u_char *session_id2 = NULL;
1.1       markus     67: int session_id2_len = 0;
                     68:
                     69: void
1.22      provos     70: ssh_kex2(char *host, struct sockaddr *hostaddr)
                     71: {
                     72:        int i, plen;
                     73:        Kex *kex;
                     74:        Buffer *client_kexinit, *server_kexinit;
                     75:        char *sprop[PROPOSAL_MAX];
                     76:
1.29      markus     77:        if (options.ciphers == (char *)-1) {
                     78:                log("No valid ciphers for protocol version 2 given, using defaults.");
                     79:                options.ciphers = NULL;
1.24      markus     80:        }
1.22      provos     81:        if (options.ciphers != NULL) {
                     82:                myproposal[PROPOSAL_ENC_ALGS_CTOS] =
                     83:                myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
                     84:        }
                     85:        if (options.compression) {
                     86:                myproposal[PROPOSAL_COMP_ALGS_CTOS] = "zlib";
                     87:                myproposal[PROPOSAL_COMP_ALGS_STOC] = "zlib";
                     88:        } else {
                     89:                myproposal[PROPOSAL_COMP_ALGS_CTOS] = "none";
                     90:                myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
                     91:        }
                     92:
                     93:        /* buffers with raw kexinit messages */
                     94:        server_kexinit = xmalloc(sizeof(*server_kexinit));
                     95:        buffer_init(server_kexinit);
                     96:        client_kexinit = kex_init(myproposal);
                     97:
                     98:        /* algorithm negotiation */
                     99:        kex_exchange_kexinit(client_kexinit, server_kexinit, sprop);
                    100:        kex = kex_choose_conf(myproposal, sprop, 0);
                    101:        for (i = 0; i < PROPOSAL_MAX; i++)
                    102:                xfree(sprop[i]);
                    103:
                    104:        /* server authentication and session key agreement */
                    105:        switch(kex->kex_type) {
                    106:        case DH_GRP1_SHA1:
                    107:                ssh_dh1_client(kex, host, hostaddr,
                    108:                               client_kexinit, server_kexinit);
                    109:                break;
                    110:        case DH_GEX_SHA1:
                    111:                ssh_dhgex_client(kex, host, hostaddr, client_kexinit,
                    112:                                 server_kexinit);
                    113:                break;
                    114:        default:
                    115:                fatal("Unsupported key exchange %d", kex->kex_type);
                    116:        }
                    117:
                    118:        buffer_free(client_kexinit);
                    119:        buffer_free(server_kexinit);
                    120:        xfree(client_kexinit);
                    121:        xfree(server_kexinit);
                    122:
                    123:        debug("Wait SSH2_MSG_NEWKEYS.");
                    124:        packet_read_expect(&plen, SSH2_MSG_NEWKEYS);
                    125:        packet_done();
                    126:        debug("GOT SSH2_MSG_NEWKEYS.");
                    127:
                    128:        debug("send SSH2_MSG_NEWKEYS.");
                    129:        packet_start(SSH2_MSG_NEWKEYS);
                    130:        packet_send();
                    131:        packet_write_wait();
                    132:        debug("done: send SSH2_MSG_NEWKEYS.");
                    133:
                    134: #ifdef DEBUG_KEXDH
                    135:        /* send 1st encrypted/maced/compressed message */
                    136:        packet_start(SSH2_MSG_IGNORE);
                    137:        packet_put_cstring("markus");
                    138:        packet_send();
                    139:        packet_write_wait();
                    140: #endif
                    141:        debug("done: KEX2.");
                    142: }
                    143:
                    144: /* diffie-hellman-group1-sha1 */
                    145:
                    146: void
                    147: ssh_dh1_client(Kex *kex, char *host, struct sockaddr *hostaddr,
                    148:               Buffer *client_kexinit, Buffer *server_kexinit)
1.1       markus    149: {
1.19      markus    150: #ifdef DEBUG_KEXDH
                    151:        int i;
                    152: #endif
1.11      markus    153:        int plen, dlen;
1.32      markus    154:        u_int klen, kout;
1.1       markus    155:        char *signature = NULL;
1.32      markus    156:        u_int slen;
1.1       markus    157:        char *server_host_key_blob = NULL;
                    158:        Key *server_host_key;
1.32      markus    159:        u_int sbloblen;
1.1       markus    160:        DH *dh;
                    161:        BIGNUM *dh_server_pub = 0;
                    162:        BIGNUM *shared_secret = 0;
1.32      markus    163:        u_char *kbuf;
                    164:        u_char *hash;
1.1       markus    165:
                    166:        debug("Sending SSH2_MSG_KEXDH_INIT.");
                    167:        /* generate and send 'e', client DH public key */
                    168:        dh = dh_new_group1();
1.31      provos    169:        dh_gen_key(dh);
1.1       markus    170:        packet_start(SSH2_MSG_KEXDH_INIT);
                    171:        packet_put_bignum2(dh->pub_key);
                    172:        packet_send();
                    173:        packet_write_wait();
                    174:
                    175: #ifdef DEBUG_KEXDH
                    176:        fprintf(stderr, "\np= ");
1.19      markus    177:        BN_print_fp(stderr, dh->p);
1.1       markus    178:        fprintf(stderr, "\ng= ");
1.19      markus    179:        BN_print_fp(stderr, dh->g);
1.1       markus    180:        fprintf(stderr, "\npub= ");
1.19      markus    181:        BN_print_fp(stderr, dh->pub_key);
1.1       markus    182:        fprintf(stderr, "\n");
                    183:        DHparams_print_fp(stderr, dh);
                    184: #endif
                    185:
                    186:        debug("Wait SSH2_MSG_KEXDH_REPLY.");
                    187:
1.11      markus    188:        packet_read_expect(&plen, SSH2_MSG_KEXDH_REPLY);
1.1       markus    189:
                    190:        debug("Got SSH2_MSG_KEXDH_REPLY.");
                    191:
                    192:        /* key, cert */
                    193:        server_host_key_blob = packet_get_string(&sbloblen);
1.28      markus    194:        server_host_key = key_from_blob(server_host_key_blob, sbloblen);
1.1       markus    195:        if (server_host_key == NULL)
                    196:                fatal("cannot decode server_host_key_blob");
                    197:
                    198:        check_host_key(host, hostaddr, server_host_key,
1.22      provos    199:                       options.user_hostfile2, options.system_hostfile2);
1.1       markus    200:
                    201:        /* DH paramter f, server public DH key */
                    202:        dh_server_pub = BN_new();
                    203:        if (dh_server_pub == NULL)
                    204:                fatal("dh_server_pub == NULL");
                    205:        packet_get_bignum2(dh_server_pub, &dlen);
                    206:
                    207: #ifdef DEBUG_KEXDH
                    208:        fprintf(stderr, "\ndh_server_pub= ");
1.19      markus    209:        BN_print_fp(stderr, dh_server_pub);
1.1       markus    210:        fprintf(stderr, "\n");
                    211:        debug("bits %d", BN_num_bits(dh_server_pub));
                    212: #endif
                    213:
                    214:        /* signed H */
                    215:        signature = packet_get_string(&slen);
                    216:        packet_done();
                    217:
                    218:        if (!dh_pub_is_valid(dh, dh_server_pub))
                    219:                packet_disconnect("bad server public DH value");
                    220:
                    221:        klen = DH_size(dh);
                    222:        kbuf = xmalloc(klen);
                    223:        kout = DH_compute_key(kbuf, dh_server_pub, dh);
                    224: #ifdef DEBUG_KEXDH
                    225:        debug("shared secret: len %d/%d", klen, kout);
                    226:        fprintf(stderr, "shared secret == ");
                    227:        for (i = 0; i< kout; i++)
                    228:                fprintf(stderr, "%02x", (kbuf[i])&0xff);
                    229:        fprintf(stderr, "\n");
                    230: #endif
                    231:        shared_secret = BN_new();
                    232:
                    233:        BN_bin2bn(kbuf, kout, shared_secret);
                    234:        memset(kbuf, 0, klen);
                    235:        xfree(kbuf);
                    236:
                    237:        /* calc and verify H */
                    238:        hash = kex_hash(
                    239:            client_version_string,
                    240:            server_version_string,
                    241:            buffer_ptr(client_kexinit), buffer_len(client_kexinit),
                    242:            buffer_ptr(server_kexinit), buffer_len(server_kexinit),
                    243:            server_host_key_blob, sbloblen,
                    244:            dh->pub_key,
                    245:            dh_server_pub,
                    246:            shared_secret
                    247:        );
1.3       markus    248:        xfree(server_host_key_blob);
1.11      markus    249:        DH_free(dh);
1.1       markus    250: #ifdef DEBUG_KEXDH
                    251:        fprintf(stderr, "hash == ");
                    252:        for (i = 0; i< 20; i++)
                    253:                fprintf(stderr, "%02x", (hash[i])&0xff);
                    254:        fprintf(stderr, "\n");
                    255: #endif
1.32      markus    256:        if (key_verify(server_host_key, (u_char *)signature, slen, hash, 20) != 1)
1.28      markus    257:                fatal("key_verify failed for server_host_key");
1.1       markus    258:        key_free(server_host_key);
                    259:
                    260:        kex_derive_keys(kex, hash, shared_secret);
                    261:        packet_set_kex(kex);
                    262:
                    263:        /* save session id */
                    264:        session_id2_len = 20;
                    265:        session_id2 = xmalloc(session_id2_len);
                    266:        memcpy(session_id2, hash, session_id2_len);
1.11      markus    267: }
                    268:
1.22      provos    269: /* diffie-hellman-group-exchange-sha1 */
                    270:
                    271: /*
                    272:  * Estimates the group order for a Diffie-Hellman group that has an
                    273:  * attack complexity approximately the same as O(2**bits).  Estimate
                    274:  * with:  O(exp(1.9223 * (ln q)^(1/3) (ln ln q)^(2/3)))
                    275:  */
                    276:
                    277: int
                    278: dh_estimate(int bits)
                    279: {
                    280:
                    281:        if (bits < 64)
                    282:                return (512);   /* O(2**63) */
                    283:        if (bits < 128)
                    284:                return (1024);  /* O(2**86) */
                    285:        if (bits < 192)
                    286:                return (2048);  /* O(2**116) */
                    287:        return (4096);          /* O(2**156) */
                    288: }
                    289:
1.11      markus    290: void
1.22      provos    291: ssh_dhgex_client(Kex *kex, char *host, struct sockaddr *hostaddr,
                    292:                 Buffer *client_kexinit, Buffer *server_kexinit)
1.11      markus    293: {
1.22      provos    294: #ifdef DEBUG_KEXDH
                    295:        int i;
                    296: #endif
                    297:        int plen, dlen;
1.32      markus    298:        u_int klen, kout;
1.22      provos    299:        char *signature = NULL;
1.32      markus    300:        u_int slen, nbits;
1.22      provos    301:        char *server_host_key_blob = NULL;
                    302:        Key *server_host_key;
1.32      markus    303:        u_int sbloblen;
1.22      provos    304:        DH *dh;
                    305:        BIGNUM *dh_server_pub = 0;
                    306:        BIGNUM *shared_secret = 0;
                    307:        BIGNUM *p = 0, *g = 0;
1.32      markus    308:        u_char *kbuf;
                    309:        u_char *hash;
1.22      provos    310:
1.24      markus    311:        nbits = dh_estimate(kex->enc[MODE_OUT].cipher->key_len * 8);
1.22      provos    312:
                    313:        debug("Sending SSH2_MSG_KEX_DH_GEX_REQUEST.");
                    314:        packet_start(SSH2_MSG_KEX_DH_GEX_REQUEST);
                    315:        packet_put_int(nbits);
                    316:        packet_send();
                    317:        packet_write_wait();
1.11      markus    318:
1.22      provos    319: #ifdef DEBUG_KEXDH
                    320:        fprintf(stderr, "\nnbits = %d", nbits);
                    321: #endif
1.11      markus    322:
1.22      provos    323:        debug("Wait SSH2_MSG_KEX_DH_GEX_GROUP.");
1.11      markus    324:
1.22      provos    325:        packet_read_expect(&plen, SSH2_MSG_KEX_DH_GEX_GROUP);
1.11      markus    326:
1.22      provos    327:        debug("Got SSH2_MSG_KEX_DH_GEX_GROUP.");
1.11      markus    328:
1.22      provos    329:        if ((p = BN_new()) == NULL)
                    330:                fatal("BN_new");
                    331:        packet_get_bignum2(p, &dlen);
                    332:        if ((g = BN_new()) == NULL)
                    333:                fatal("BN_new");
                    334:        packet_get_bignum2(g, &dlen);
                    335:        if ((dh = dh_new_group(g, p)) == NULL)
                    336:                fatal("dh_new_group");
1.31      provos    337:
                    338:        dh_gen_key(dh);
1.1       markus    339:
1.22      provos    340: #ifdef DEBUG_KEXDH
                    341:        fprintf(stderr, "\np= ");
                    342:        BN_print_fp(stderr, dh->p);
                    343:        fprintf(stderr, "\ng= ");
                    344:        BN_print_fp(stderr, dh->g);
                    345:        fprintf(stderr, "\npub= ");
                    346:        BN_print_fp(stderr, dh->pub_key);
                    347:        fprintf(stderr, "\n");
                    348:        DHparams_print_fp(stderr, dh);
                    349: #endif
1.1       markus    350:
1.22      provos    351:        debug("Sending SSH2_MSG_KEX_DH_GEX_INIT.");
                    352:        /* generate and send 'e', client DH public key */
                    353:        packet_start(SSH2_MSG_KEX_DH_GEX_INIT);
                    354:        packet_put_bignum2(dh->pub_key);
1.1       markus    355:        packet_send();
                    356:        packet_write_wait();
                    357:
1.22      provos    358:        debug("Wait SSH2_MSG_KEX_DH_GEX_REPLY.");
                    359:
                    360:        packet_read_expect(&plen, SSH2_MSG_KEX_DH_GEX_REPLY);
                    361:
                    362:        debug("Got SSH2_MSG_KEXDH_REPLY.");
                    363:
                    364:        /* key, cert */
                    365:        server_host_key_blob = packet_get_string(&sbloblen);
1.28      markus    366:        server_host_key = key_from_blob(server_host_key_blob, sbloblen);
1.22      provos    367:        if (server_host_key == NULL)
                    368:                fatal("cannot decode server_host_key_blob");
                    369:
                    370:        check_host_key(host, hostaddr, server_host_key,
                    371:                       options.user_hostfile2, options.system_hostfile2);
                    372:
                    373:        /* DH paramter f, server public DH key */
                    374:        dh_server_pub = BN_new();
                    375:        if (dh_server_pub == NULL)
                    376:                fatal("dh_server_pub == NULL");
                    377:        packet_get_bignum2(dh_server_pub, &dlen);
                    378:
                    379: #ifdef DEBUG_KEXDH
                    380:        fprintf(stderr, "\ndh_server_pub= ");
                    381:        BN_print_fp(stderr, dh_server_pub);
                    382:        fprintf(stderr, "\n");
                    383:        debug("bits %d", BN_num_bits(dh_server_pub));
                    384: #endif
                    385:
                    386:        /* signed H */
                    387:        signature = packet_get_string(&slen);
                    388:        packet_done();
                    389:
                    390:        if (!dh_pub_is_valid(dh, dh_server_pub))
                    391:                packet_disconnect("bad server public DH value");
                    392:
                    393:        klen = DH_size(dh);
                    394:        kbuf = xmalloc(klen);
                    395:        kout = DH_compute_key(kbuf, dh_server_pub, dh);
                    396: #ifdef DEBUG_KEXDH
                    397:        debug("shared secret: len %d/%d", klen, kout);
                    398:        fprintf(stderr, "shared secret == ");
                    399:        for (i = 0; i< kout; i++)
                    400:                fprintf(stderr, "%02x", (kbuf[i])&0xff);
                    401:        fprintf(stderr, "\n");
                    402: #endif
                    403:        shared_secret = BN_new();
                    404:
                    405:        BN_bin2bn(kbuf, kout, shared_secret);
                    406:        memset(kbuf, 0, klen);
                    407:        xfree(kbuf);
                    408:
                    409:        /* calc and verify H */
                    410:        hash = kex_hash_gex(
                    411:            client_version_string,
                    412:            server_version_string,
                    413:            buffer_ptr(client_kexinit), buffer_len(client_kexinit),
                    414:            buffer_ptr(server_kexinit), buffer_len(server_kexinit),
                    415:            server_host_key_blob, sbloblen,
                    416:            nbits, dh->p, dh->g,
                    417:            dh->pub_key,
                    418:            dh_server_pub,
                    419:            shared_secret
                    420:        );
                    421:        xfree(server_host_key_blob);
                    422:        DH_free(dh);
1.1       markus    423: #ifdef DEBUG_KEXDH
1.22      provos    424:        fprintf(stderr, "hash == ");
                    425:        for (i = 0; i< 20; i++)
                    426:                fprintf(stderr, "%02x", (hash[i])&0xff);
                    427:        fprintf(stderr, "\n");
1.1       markus    428: #endif
1.32      markus    429:        if (key_verify(server_host_key, (u_char *)signature, slen, hash, 20) != 1)
1.28      markus    430:                fatal("key_verify failed for server_host_key");
1.22      provos    431:        key_free(server_host_key);
                    432:
                    433:        kex_derive_keys(kex, hash, shared_secret);
                    434:        packet_set_kex(kex);
                    435:
                    436:        /* save session id */
                    437:        session_id2_len = 20;
                    438:        session_id2 = xmalloc(session_id2_len);
                    439:        memcpy(session_id2, hash, session_id2_len);
1.1       markus    440: }
1.11      markus    441:
1.1       markus    442: /*
                    443:  * Authenticate user
                    444:  */
1.20      markus    445:
                    446: typedef struct Authctxt Authctxt;
                    447: typedef struct Authmethod Authmethod;
                    448:
                    449: typedef int sign_cb_fn(
                    450:     Authctxt *authctxt, Key *key,
1.32      markus    451:     u_char **sigp, int *lenp, u_char *data, int datalen);
1.20      markus    452:
                    453: struct Authctxt {
                    454:        const char *server_user;
                    455:        const char *host;
                    456:        const char *service;
                    457:        AuthenticationConnection *agent;
1.23      markus    458:        Authmethod *method;
1.20      markus    459:        int success;
                    460: };
                    461: struct Authmethod {
                    462:        char    *name;          /* string to compare against server's list */
                    463:        int     (*userauth)(Authctxt *authctxt);
                    464:        int     *enabled;       /* flag in option struct that enables method */
                    465:        int     *batch_flag;    /* flag in option struct that disables method */
                    466: };
                    467:
                    468: void   input_userauth_success(int type, int plen, void *ctxt);
                    469: void   input_userauth_failure(int type, int plen, void *ctxt);
1.35    ! markus    470: void   input_userauth_banner(int type, int plen, void *ctxt);
1.20      markus    471: void   input_userauth_error(int type, int plen, void *ctxt);
1.23      markus    472: void   input_userauth_info_req(int type, int plen, void *ctxt);
                    473:
                    474: int    userauth_none(Authctxt *authctxt);
1.20      markus    475: int    userauth_pubkey(Authctxt *authctxt);
                    476: int    userauth_passwd(Authctxt *authctxt);
1.23      markus    477: int    userauth_kbdint(Authctxt *authctxt);
1.20      markus    478:
1.33      markus    479: void   authmethod_clear(void);
1.23      markus    480: Authmethod *authmethod_get(char *authlist);
                    481: Authmethod *authmethod_lookup(const char *name);
1.20      markus    482:
                    483: Authmethod authmethods[] = {
                    484:        {"publickey",
                    485:                userauth_pubkey,
1.28      markus    486:                &options.pubkey_authentication,
1.20      markus    487:                NULL},
                    488:        {"password",
                    489:                userauth_passwd,
                    490:                &options.password_authentication,
                    491:                &options.batch_mode},
1.23      markus    492:        {"keyboard-interactive",
                    493:                userauth_kbdint,
                    494:                &options.kbd_interactive_authentication,
                    495:                &options.batch_mode},
                    496:        {"none",
                    497:                userauth_none,
                    498:                NULL,
                    499:                NULL},
1.20      markus    500:        {NULL, NULL, NULL, NULL}
                    501: };
                    502:
                    503: void
                    504: ssh_userauth2(const char *server_user, char *host)
                    505: {
                    506:        Authctxt authctxt;
                    507:        int type;
                    508:        int plen;
                    509:
                    510:        debug("send SSH2_MSG_SERVICE_REQUEST");
                    511:        packet_start(SSH2_MSG_SERVICE_REQUEST);
                    512:        packet_put_cstring("ssh-userauth");
                    513:        packet_send();
                    514:        packet_write_wait();
                    515:        type = packet_read(&plen);
                    516:        if (type != SSH2_MSG_SERVICE_ACCEPT) {
                    517:                fatal("denied SSH2_MSG_SERVICE_ACCEPT: %d", type);
                    518:        }
                    519:        if (packet_remaining() > 0) {
                    520:                char *reply = packet_get_string(&plen);
                    521:                debug("service_accept: %s", reply);
                    522:                xfree(reply);
                    523:                packet_done();
                    524:        } else {
                    525:                debug("buggy server: service_accept w/o service");
                    526:        }
                    527:        packet_done();
                    528:        debug("got SSH2_MSG_SERVICE_ACCEPT");
                    529:
                    530:        /* setup authentication context */
                    531:        authctxt.agent = ssh_get_authentication_connection();
                    532:        authctxt.server_user = server_user;
                    533:        authctxt.host = host;
                    534:        authctxt.service = "ssh-connection";            /* service name */
                    535:        authctxt.success = 0;
1.23      markus    536:        authctxt.method = authmethod_lookup("none");
                    537:        if (authctxt.method == NULL)
                    538:                fatal("ssh_userauth2: internal error: cannot send userauth none request");
                    539:        authmethod_clear();
1.20      markus    540:
                    541:        /* initial userauth request */
1.23      markus    542:        userauth_none(&authctxt);
1.20      markus    543:
                    544:        dispatch_init(&input_userauth_error);
                    545:        dispatch_set(SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
                    546:        dispatch_set(SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
1.35    ! markus    547:        dispatch_set(SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
1.20      markus    548:        dispatch_run(DISPATCH_BLOCK, &authctxt.success, &authctxt);     /* loop until success */
                    549:
                    550:        if (authctxt.agent != NULL)
                    551:                ssh_close_authentication_connection(authctxt.agent);
                    552:
1.34      markus    553:        debug("ssh-userauth2 successful: method %s", authctxt.method->name);
1.20      markus    554: }
                    555: void
                    556: input_userauth_error(int type, int plen, void *ctxt)
                    557: {
1.35    ! markus    558:        fatal("input_userauth_error: bad message during authentication: "
        !           559:           "type %d", type);
        !           560: }
        !           561: void
        !           562: input_userauth_banner(int type, int plen, void *ctxt)
        !           563: {
        !           564:        char *msg, *lang;
        !           565:        debug3("input_userauth_banner");
        !           566:        msg = packet_get_string(NULL);
        !           567:        lang = packet_get_string(NULL);
        !           568:        fprintf(stderr, "%s", msg);
        !           569:        xfree(msg);
        !           570:        xfree(lang);
1.20      markus    571: }
                    572: void
                    573: input_userauth_success(int type, int plen, void *ctxt)
                    574: {
                    575:        Authctxt *authctxt = ctxt;
                    576:        if (authctxt == NULL)
                    577:                fatal("input_userauth_success: no authentication context");
                    578:        authctxt->success = 1;                  /* break out */
                    579: }
                    580: void
                    581: input_userauth_failure(int type, int plen, void *ctxt)
                    582: {
                    583:        Authmethod *method = NULL;
                    584:        Authctxt *authctxt = ctxt;
                    585:        char *authlist = NULL;
                    586:        int partial;
                    587:
                    588:        if (authctxt == NULL)
                    589:                fatal("input_userauth_failure: no authentication context");
                    590:
1.23      markus    591:        authlist = packet_get_string(NULL);
1.20      markus    592:        partial = packet_get_char();
                    593:        packet_done();
                    594:
                    595:        if (partial != 0)
                    596:                debug("partial success");
                    597:        debug("authentications that can continue: %s", authlist);
                    598:
                    599:        for (;;) {
                    600:                method = authmethod_get(authlist);
                    601:                if (method == NULL)
                    602:                         fatal("Unable to find an authentication method");
1.23      markus    603:                authctxt->method = method;
1.20      markus    604:                if (method->userauth(authctxt) != 0) {
1.23      markus    605:                        debug2("we sent a %s packet, wait for reply", method->name);
1.20      markus    606:                        break;
                    607:                } else {
                    608:                        debug2("we did not send a packet, disable method");
                    609:                        method->enabled = NULL;
                    610:                }
                    611:        }
                    612:        xfree(authlist);
                    613: }
                    614:
1.1       markus    615: int
1.23      markus    616: userauth_none(Authctxt *authctxt)
                    617: {
                    618:        /* initial userauth request */
                    619:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
                    620:        packet_put_cstring(authctxt->server_user);
                    621:        packet_put_cstring(authctxt->service);
                    622:        packet_put_cstring(authctxt->method->name);
                    623:        packet_send();
                    624:        packet_write_wait();
                    625:        return 1;
                    626: }
                    627:
                    628: int
1.20      markus    629: userauth_passwd(Authctxt *authctxt)
1.1       markus    630: {
1.6       markus    631:        static int attempt = 0;
1.1       markus    632:        char prompt[80];
                    633:        char *password;
1.6       markus    634:
1.13      todd      635:        if (attempt++ >= options.number_of_password_prompts)
1.6       markus    636:                return 0;
1.13      todd      637:
                    638:        if(attempt != 1)
                    639:                error("Permission denied, please try again.");
1.1       markus    640:
                    641:        snprintf(prompt, sizeof(prompt), "%.30s@%.40s's password: ",
1.20      markus    642:            authctxt->server_user, authctxt->host);
1.1       markus    643:        password = read_passphrase(prompt, 0);
                    644:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
1.20      markus    645:        packet_put_cstring(authctxt->server_user);
                    646:        packet_put_cstring(authctxt->service);
1.23      markus    647:        packet_put_cstring(authctxt->method->name);
1.1       markus    648:        packet_put_char(0);
                    649:        packet_put_cstring(password);
                    650:        memset(password, 0, strlen(password));
                    651:        xfree(password);
                    652:        packet_send();
                    653:        packet_write_wait();
                    654:        return 1;
                    655: }
                    656:
1.17      markus    657: int
1.20      markus    658: sign_and_send_pubkey(Authctxt *authctxt, Key *k, sign_cb_fn *sign_callback)
1.1       markus    659: {
                    660:        Buffer b;
1.32      markus    661:        u_char *blob, *signature;
1.1       markus    662:        int bloblen, slen;
1.14      markus    663:        int skip = 0;
1.17      markus    664:        int ret = -1;
1.23      markus    665:        int have_sig = 1;
1.1       markus    666:
1.30      markus    667:        debug3("sign_and_send_pubkey");
1.28      markus    668:        if (key_to_blob(k, &blob, &bloblen) == 0) {
                    669:                /* we cannot handle this key */
1.30      markus    670:                debug3("sign_and_send_pubkey: cannot handle key");
1.28      markus    671:                return 0;
                    672:        }
1.1       markus    673:        /* data to be signed */
                    674:        buffer_init(&b);
1.26      markus    675:        if (datafellows & SSH_OLD_SESSIONID) {
                    676:                buffer_append(&b, session_id2, session_id2_len);
                    677:                skip = session_id2_len;
                    678:        } else {
1.14      markus    679:                buffer_put_string(&b, session_id2, session_id2_len);
                    680:                skip = buffer_len(&b);
                    681:        }
1.1       markus    682:        buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1.20      markus    683:        buffer_put_cstring(&b, authctxt->server_user);
1.10      markus    684:        buffer_put_cstring(&b,
1.30      markus    685:            datafellows & SSH_BUG_PKSERVICE ?
1.10      markus    686:            "ssh-userauth" :
1.20      markus    687:            authctxt->service);
1.30      markus    688:        if (datafellows & SSH_BUG_PKAUTH) {
                    689:                buffer_put_char(&b, have_sig);
                    690:        } else {
                    691:                buffer_put_cstring(&b, authctxt->method->name);
                    692:                buffer_put_char(&b, have_sig);
                    693:                buffer_put_cstring(&b, key_ssh_name(k));
                    694:        }
1.1       markus    695:        buffer_put_string(&b, blob, bloblen);
                    696:
                    697:        /* generate signature */
1.20      markus    698:        ret = (*sign_callback)(authctxt, k, &signature, &slen, buffer_ptr(&b), buffer_len(&b));
1.17      markus    699:        if (ret == -1) {
                    700:                xfree(blob);
                    701:                buffer_free(&b);
                    702:                return 0;
                    703:        }
1.28      markus    704: #ifdef DEBUG_PK
1.1       markus    705:        buffer_dump(&b);
                    706: #endif
1.30      markus    707:        if (datafellows & SSH_BUG_PKSERVICE) {
1.10      markus    708:                buffer_clear(&b);
                    709:                buffer_append(&b, session_id2, session_id2_len);
                    710:                buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1.20      markus    711:                buffer_put_cstring(&b, authctxt->server_user);
                    712:                buffer_put_cstring(&b, authctxt->service);
1.23      markus    713:                buffer_put_cstring(&b, authctxt->method->name);
                    714:                buffer_put_char(&b, have_sig);
1.30      markus    715:                if (!(datafellows & SSH_BUG_PKAUTH))
                    716:                        buffer_put_cstring(&b, key_ssh_name(k));
1.10      markus    717:                buffer_put_string(&b, blob, bloblen);
                    718:        }
                    719:        xfree(blob);
1.1       markus    720:        /* append signature */
                    721:        buffer_put_string(&b, signature, slen);
                    722:        xfree(signature);
                    723:
                    724:        /* skip session id and packet type */
1.14      markus    725:        if (buffer_len(&b) < skip + 1)
1.20      markus    726:                fatal("userauth_pubkey: internal error");
1.14      markus    727:        buffer_consume(&b, skip + 1);
1.1       markus    728:
                    729:        /* put remaining data from buffer into packet */
                    730:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
                    731:        packet_put_raw(buffer_ptr(&b), buffer_len(&b));
                    732:        buffer_free(&b);
                    733:
                    734:        /* send */
                    735:        packet_send();
                    736:        packet_write_wait();
1.17      markus    737:
                    738:        return 1;
1.16      markus    739: }
                    740:
1.20      markus    741: /* sign callback */
1.32      markus    742: int key_sign_cb(Authctxt *authctxt, Key *key, u_char **sigp, int *lenp,
                    743:     u_char *data, int datalen)
1.20      markus    744: {
1.28      markus    745:        return key_sign(key, sigp, lenp, data, datalen);
1.20      markus    746: }
                    747:
1.16      markus    748: int
1.20      markus    749: userauth_pubkey_identity(Authctxt *authctxt, char *filename)
1.16      markus    750: {
                    751:        Key *k;
1.20      markus    752:        int i, ret, try_next;
1.16      markus    753:        struct stat st;
                    754:
                    755:        if (stat(filename, &st) != 0) {
                    756:                debug("key does not exist: %s", filename);
                    757:                return 0;
                    758:        }
                    759:        debug("try pubkey: %s", filename);
                    760:
1.28      markus    761:        k = key_new(KEY_UNSPEC);
1.16      markus    762:        if (!load_private_key(filename, "", k, NULL)) {
                    763:                int success = 0;
                    764:                char *passphrase;
                    765:                char prompt[300];
                    766:                snprintf(prompt, sizeof prompt,
1.28      markus    767:                     "Enter passphrase for key '%.100s': ", filename);
1.20      markus    768:                for (i = 0; i < options.number_of_password_prompts; i++) {
                    769:                        passphrase = read_passphrase(prompt, 0);
                    770:                        if (strcmp(passphrase, "") != 0) {
                    771:                                success = load_private_key(filename, passphrase, k, NULL);
                    772:                                try_next = 0;
                    773:                        } else {
                    774:                                debug2("no passphrase given, try next key");
                    775:                                try_next = 1;
                    776:                        }
                    777:                        memset(passphrase, 0, strlen(passphrase));
                    778:                        xfree(passphrase);
                    779:                        if (success || try_next)
                    780:                                break;
                    781:                        debug2("bad passphrase given, try again...");
                    782:                }
1.16      markus    783:                if (!success) {
                    784:                        key_free(k);
                    785:                        return 0;
                    786:                }
                    787:        }
1.28      markus    788:        ret = sign_and_send_pubkey(authctxt, k, key_sign_cb);
1.17      markus    789:        key_free(k);
                    790:        return ret;
                    791: }
                    792:
1.20      markus    793: /* sign callback */
1.32      markus    794: int agent_sign_cb(Authctxt *authctxt, Key *key, u_char **sigp, int *lenp,
                    795:     u_char *data, int datalen)
1.17      markus    796: {
1.20      markus    797:        return ssh_agent_sign(authctxt->agent, key, sigp, lenp, data, datalen);
1.17      markus    798: }
                    799:
                    800: int
1.20      markus    801: userauth_pubkey_agent(Authctxt *authctxt)
1.17      markus    802: {
                    803:        static int called = 0;
1.28      markus    804:        int ret = 0;
1.17      markus    805:        char *comment;
                    806:        Key *k;
                    807:
                    808:        if (called == 0) {
1.28      markus    809:                if (ssh_get_num_identities(authctxt->agent, 2) == 0)
                    810:                        debug2("userauth_pubkey_agent: no keys at all");
1.20      markus    811:                called = 1;
1.17      markus    812:        }
1.28      markus    813:        k = ssh_get_next_identity(authctxt->agent, &comment, 2);
1.20      markus    814:        if (k == NULL) {
1.28      markus    815:                debug2("userauth_pubkey_agent: no more keys");
                    816:        } else {
                    817:                debug("userauth_pubkey_agent: trying agent key %s", comment);
                    818:                xfree(comment);
                    819:                ret = sign_and_send_pubkey(authctxt, k, agent_sign_cb);
                    820:                key_free(k);
1.20      markus    821:        }
1.28      markus    822:        if (ret == 0)
                    823:                debug2("userauth_pubkey_agent: no message sent");
1.17      markus    824:        return ret;
1.1       markus    825: }
                    826:
1.20      markus    827: int
                    828: userauth_pubkey(Authctxt *authctxt)
                    829: {
                    830:        static int idx = 0;
                    831:        int sent = 0;
                    832:
1.28      markus    833:        if (authctxt->agent != NULL) {
                    834:                do {
                    835:                        sent = userauth_pubkey_agent(authctxt);
                    836:                } while(!sent && authctxt->agent->howmany > 0);
                    837:        }
                    838:        while (!sent && idx < options.num_identity_files) {
                    839:                if (options.identity_files_type[idx] != KEY_RSA1)
                    840:                        sent = userauth_pubkey_identity(authctxt,
                    841:                            options.identity_files[idx]);
                    842:                idx++;
                    843:        }
1.20      markus    844:        return sent;
                    845: }
                    846:
1.23      markus    847: /*
                    848:  * Send userauth request message specifying keyboard-interactive method.
                    849:  */
                    850: int
                    851: userauth_kbdint(Authctxt *authctxt)
                    852: {
                    853:        static int attempt = 0;
                    854:
                    855:        if (attempt++ >= options.number_of_password_prompts)
                    856:                return 0;
                    857:
                    858:        debug2("userauth_kbdint");
                    859:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
                    860:        packet_put_cstring(authctxt->server_user);
                    861:        packet_put_cstring(authctxt->service);
                    862:        packet_put_cstring(authctxt->method->name);
                    863:        packet_put_cstring("");                                 /* lang */
                    864:        packet_put_cstring(options.kbd_interactive_devices ?
                    865:            options.kbd_interactive_devices : "");
                    866:        packet_send();
                    867:        packet_write_wait();
                    868:
                    869:        dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
                    870:        return 1;
                    871: }
                    872:
                    873: /*
                    874:  * parse SSH2_MSG_USERAUTH_INFO_REQUEST, prompt user and send
                    875:  * SSH2_MSG_USERAUTH_INFO_RESPONSE
                    876:  */
                    877: void
                    878: input_userauth_info_req(int type, int plen, void *ctxt)
                    879: {
                    880:        Authctxt *authctxt = ctxt;
                    881:        char *name = NULL;
                    882:        char *inst = NULL;
                    883:        char *lang = NULL;
                    884:        char *prompt = NULL;
                    885:        char *response = NULL;
1.32      markus    886:        u_int num_prompts, i;
1.23      markus    887:        int echo = 0;
                    888:
                    889:        debug2("input_userauth_info_req");
                    890:
                    891:        if (authctxt == NULL)
                    892:                fatal("input_userauth_info_req: no authentication context");
                    893:
                    894:        name = packet_get_string(NULL);
                    895:        inst = packet_get_string(NULL);
                    896:        lang = packet_get_string(NULL);
                    897:
                    898:        if (strlen(name) > 0)
                    899:                cli_mesg(name);
                    900:        xfree(name);
                    901:
                    902:        if (strlen(inst) > 0)
                    903:                cli_mesg(inst);
                    904:        xfree(inst);
                    905:        xfree(lang);                            /* unused */
                    906:
                    907:        num_prompts = packet_get_int();
                    908:        /*
                    909:         * Begin to build info response packet based on prompts requested.
                    910:         * We commit to providing the correct number of responses, so if
                    911:         * further on we run into a problem that prevents this, we have to
                    912:         * be sure and clean this up and send a correct error response.
                    913:         */
                    914:        packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
                    915:        packet_put_int(num_prompts);
                    916:
                    917:        for (i = 0; i < num_prompts; i++) {
                    918:                prompt = packet_get_string(NULL);
                    919:                echo = packet_get_char();
                    920:
                    921:                response = cli_prompt(prompt, echo);
                    922:
                    923:                packet_put_cstring(response);
                    924:                memset(response, 0, strlen(response));
                    925:                xfree(response);
                    926:                xfree(prompt);
                    927:        }
                    928:        packet_done(); /* done with parsing incoming message. */
                    929:
                    930:        packet_send();
                    931:        packet_write_wait();
                    932: }
1.20      markus    933:
                    934: /* find auth method */
                    935:
                    936: #define        DELIM   ","
                    937:
                    938: static char *def_authlist = "publickey,password";
                    939: static char *authlist_current = NULL;   /* clean copy used for comparison */
                    940: static char *authname_current = NULL;   /* last used auth method */
                    941: static char *authlist_working = NULL;   /* copy that gets modified by strtok_r() */
                    942: static char *authlist_state = NULL;     /* state variable for strtok_r() */
                    943:
                    944: /*
                    945:  * Before starting to use a new authentication method list sent by the
                    946:  * server, reset internal variables.  This should also be called when
                    947:  * finished processing server list to free resources.
                    948:  */
1.1       markus    949: void
1.33      markus    950: authmethod_clear(void)
1.20      markus    951: {
                    952:        if (authlist_current != NULL) {
                    953:                xfree(authlist_current);
                    954:                authlist_current = NULL;
                    955:        }
                    956:        if (authlist_working != NULL) {
                    957:                xfree(authlist_working);
                    958:                authlist_working = NULL;
                    959:        }
                    960:        if (authname_current != NULL) {
                    961:                xfree(authname_current);
                    962:                authlist_state = NULL;
                    963:        }
                    964:        if (authlist_state != NULL)
                    965:                authlist_state = NULL;
                    966:        return;
                    967: }
                    968:
                    969: /*
                    970:  * given auth method name, if configurable options permit this method fill
                    971:  * in auth_ident field and return true, otherwise return false.
                    972:  */
                    973: int
                    974: authmethod_is_enabled(Authmethod *method)
                    975: {
                    976:        if (method == NULL)
                    977:                return 0;
                    978:        /* return false if options indicate this method is disabled */
                    979:        if  (method->enabled == NULL || *method->enabled == 0)
                    980:                return 0;
                    981:        /* return false if batch mode is enabled but method needs interactive mode */
                    982:        if  (method->batch_flag != NULL && *method->batch_flag != 0)
                    983:                return 0;
                    984:        return 1;
                    985: }
                    986:
                    987: Authmethod *
                    988: authmethod_lookup(const char *name)
1.1       markus    989: {
1.20      markus    990:        Authmethod *method = NULL;
                    991:        if (name != NULL)
                    992:                for (method = authmethods; method->name != NULL; method++)
                    993:                        if (strcmp(name, method->name) == 0)
                    994:                                return method;
                    995:        debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
                    996:        return NULL;
                    997: }
1.1       markus    998:
1.20      markus    999: /*
                   1000:  * Given the authentication method list sent by the server, return the
                   1001:  * next method we should try.  If the server initially sends a nil list,
                   1002:  * use a built-in default list.  If the server sends a nil list after
                   1003:  * previously sending a valid list, continue using the list originally
                   1004:  * sent.
                   1005:  */
1.1       markus   1006:
1.20      markus   1007: Authmethod *
                   1008: authmethod_get(char *authlist)
                   1009: {
1.27      provos   1010:        char *name = NULL, *authname_old;
1.20      markus   1011:        Authmethod *method = NULL;
                   1012:
                   1013:        /* Use a suitable default if we're passed a nil list.  */
                   1014:        if (authlist == NULL || strlen(authlist) == 0)
                   1015:                authlist = def_authlist;
                   1016:
                   1017:        if (authlist_current == NULL || strcmp(authlist, authlist_current) != 0) {
                   1018:                /* start over if passed a different list */
1.23      markus   1019:                debug3("start over, passed a different list");
1.20      markus   1020:                authmethod_clear();
                   1021:                authlist_current = xstrdup(authlist);
                   1022:                authlist_working = xstrdup(authlist);
                   1023:                name = strtok_r(authlist_working, DELIM, &authlist_state);
                   1024:        } else {
                   1025:                /*
                   1026:                 * try to use previously used authentication method
                   1027:                 * or continue to use previously passed list
                   1028:                 */
                   1029:                name = (authname_current != NULL) ?
                   1030:                    authname_current : strtok_r(NULL, DELIM, &authlist_state);
1.1       markus   1031:        }
1.20      markus   1032:
                   1033:        while (name != NULL) {
1.23      markus   1034:                debug3("authmethod_lookup %s", name);
1.20      markus   1035:                method = authmethod_lookup(name);
1.23      markus   1036:                if (method != NULL && authmethod_is_enabled(method)) {
                   1037:                        debug3("authmethod_is_enabled %s", name);
1.20      markus   1038:                        break;
1.23      markus   1039:                }
1.20      markus   1040:                name = strtok_r(NULL, DELIM, &authlist_state);
1.23      markus   1041:                method = NULL;
1.1       markus   1042:        }
                   1043:
1.27      provos   1044:        authname_old = authname_current;
1.23      markus   1045:        if (method != NULL) {
1.20      markus   1046:                debug("next auth method to try is %s", name);
                   1047:                authname_current = xstrdup(name);
                   1048:        } else {
                   1049:                debug("no more auth methods to try");
                   1050:                authname_current = NULL;
1.1       markus   1051:        }
1.27      provos   1052:
                   1053:        if (authname_old != NULL)
                   1054:                xfree(authname_old);
                   1055:
                   1056:        return (method);
1.1       markus   1057: }