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

1.246   ! djm         1: /* $OpenBSD: sshconnect2.c,v 1.245 2016/05/24 04:43:45 dtucker Exp $ */
1.1       markus      2: /*
                      3:  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
1.170     djm         4:  * Copyright (c) 2008 Damien Miller.  All rights reserved.
1.1       markus      5:  *
                      6:  * Redistribution and use in source and binary forms, with or without
                      7:  * modification, are permitted provided that the following conditions
                      8:  * are met:
                      9:  * 1. Redistributions of source code must retain the above copyright
                     10:  *    notice, this list of conditions and the following disclaimer.
                     11:  * 2. Redistributions in binary form must reproduce the above copyright
                     12:  *    notice, this list of conditions and the following disclaimer in the
                     13:  *    documentation and/or other materials provided with the distribution.
                     14:  *
                     15:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     16:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     17:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     18:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     19:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     20:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     21:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     22:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     23:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     24:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                     25:  */
                     26:
1.145     stevesk    27: #include <sys/types.h>
1.160     deraadt    28: #include <sys/socket.h>
1.145     stevesk    29: #include <sys/wait.h>
1.144     stevesk    30: #include <sys/queue.h>
1.146     stevesk    31: #include <sys/stat.h>
1.156     stevesk    32:
                     33: #include <errno.h>
1.174     dtucker    34: #include <fcntl.h>
1.164     jolan      35: #include <netdb.h>
1.159     stevesk    36: #include <stdio.h>
1.158     stevesk    37: #include <string.h>
1.160     deraadt    38: #include <signal.h>
                     39: #include <pwd.h>
1.157     stevesk    40: #include <unistd.h>
1.166     djm        41: #include <vis.h>
1.1       markus     42:
1.160     deraadt    43: #include "xmalloc.h"
1.1       markus     44: #include "ssh.h"
1.37      markus     45: #include "ssh2.h"
1.1       markus     46: #include "buffer.h"
                     47: #include "packet.h"
                     48: #include "compat.h"
1.37      markus     49: #include "cipher.h"
1.160     deraadt    50: #include "key.h"
1.1       markus     51: #include "kex.h"
                     52: #include "myproposal.h"
                     53: #include "sshconnect.h"
                     54: #include "authfile.h"
1.57      provos     55: #include "dh.h"
1.17      markus     56: #include "authfd.h"
1.37      markus     57: #include "log.h"
1.210     millert    58: #include "misc.h"
1.37      markus     59: #include "readconf.h"
1.53      markus     60: #include "match.h"
1.61      markus     61: #include "dispatch.h"
1.68      markus     62: #include "canohost.h"
1.100     markus     63: #include "msg.h"
                     64: #include "pathnames.h"
1.154     markus     65: #include "uidswap.h"
1.186     djm        66: #include "hostfile.h"
1.214     djm        67: #include "ssherr.h"
1.246   ! djm        68: #include "utf8.h"
1.22      provos     69:
1.121     markus     70: #ifdef GSSAPI
                     71: #include "ssh-gss.h"
                     72: #endif
                     73:
1.1       markus     74: /* import */
                     75: extern char *client_version_string;
                     76: extern char *server_version_string;
                     77: extern Options options;
                     78:
                     79: /*
                     80:  * SSH2 key exchange
                     81:  */
                     82:
1.32      markus     83: u_char *session_id2 = NULL;
1.120     markus     84: u_int session_id2_len = 0;
1.1       markus     85:
1.61      markus     86: char *xxx_host;
                     87: struct sockaddr *xxx_hostaddr;
                     88:
1.76      itojun     89: static int
1.219     markus     90: verify_host_key_callback(Key *hostkey, struct ssh *ssh)
1.61      markus     91: {
1.75      markus     92:        if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
1.83      markus     93:                fatal("Host key verification failed.");
1.61      markus     94:        return 0;
                     95: }
                     96:
1.186     djm        97: static char *
                     98: order_hostkeyalgs(char *host, struct sockaddr *hostaddr, u_short port)
                     99: {
                    100:        char *oavail, *avail, *first, *last, *alg, *hostname, *ret;
                    101:        size_t maxlen;
                    102:        struct hostkeys *hostkeys;
                    103:        int ktype;
1.188     djm       104:        u_int i;
1.186     djm       105:
                    106:        /* Find all hostkeys for this hostname */
                    107:        get_hostfile_hostname_ipaddr(host, hostaddr, port, &hostname, NULL);
                    108:        hostkeys = init_hostkeys();
1.188     djm       109:        for (i = 0; i < options.num_user_hostfiles; i++)
                    110:                load_hostkeys(hostkeys, hostname, options.user_hostfiles[i]);
                    111:        for (i = 0; i < options.num_system_hostfiles; i++)
                    112:                load_hostkeys(hostkeys, hostname, options.system_hostfiles[i]);
1.186     djm       113:
                    114:        oavail = avail = xstrdup(KEX_DEFAULT_PK_ALG);
                    115:        maxlen = strlen(avail) + 1;
                    116:        first = xmalloc(maxlen);
                    117:        last = xmalloc(maxlen);
                    118:        *first = *last = '\0';
                    119:
                    120: #define ALG_APPEND(to, from) \
                    121:        do { \
                    122:                if (*to != '\0') \
                    123:                        strlcat(to, ",", maxlen); \
                    124:                strlcat(to, from, maxlen); \
                    125:        } while (0)
                    126:
                    127:        while ((alg = strsep(&avail, ",")) && *alg != '\0') {
1.214     djm       128:                if ((ktype = sshkey_type_from_name(alg)) == KEY_UNSPEC)
1.186     djm       129:                        fatal("%s: unknown alg %s", __func__, alg);
                    130:                if (lookup_key_in_hostkeys_by_type(hostkeys,
1.214     djm       131:                    sshkey_type_plain(ktype), NULL))
1.186     djm       132:                        ALG_APPEND(first, alg);
                    133:                else
                    134:                        ALG_APPEND(last, alg);
                    135:        }
                    136: #undef ALG_APPEND
1.216     djm       137:        xasprintf(&ret, "%s%s%s", first,
                    138:            (*first == '\0' || *last == '\0') ? "" : ",", last);
1.186     djm       139:        if (*first != '\0')
                    140:                debug3("%s: prefer hostkeyalgs: %s", __func__, first);
                    141:
1.197     djm       142:        free(first);
                    143:        free(last);
                    144:        free(hostname);
                    145:        free(oavail);
1.186     djm       146:        free_hostkeys(hostkeys);
                    147:
                    148:        return ret;
                    149: }
                    150:
1.1       markus    151: void
1.186     djm       152: ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
1.22      provos    153: {
1.205     markus    154:        char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
1.231     markus    155:        char *s;
1.219     markus    156:        struct kex *kex;
1.221     markus    157:        int r;
1.61      markus    158:
                    159:        xxx_host = host;
                    160:        xxx_hostaddr = hostaddr;
1.22      provos    161:
1.231     markus    162:        if ((s = kex_names_cat(options.kex_algorithms, "ext-info-c")) == NULL)
                    163:                fatal("%s: kex_names_cat", __func__);
                    164:        myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(s);
1.60      stevesk   165:        myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1.226     djm       166:            compat_cipher_proposal(options.ciphers);
1.60      stevesk   167:        myproposal[PROPOSAL_ENC_ALGS_STOC] =
1.226     djm       168:            compat_cipher_proposal(options.ciphers);
1.245     dtucker   169:        myproposal[PROPOSAL_COMP_ALGS_CTOS] =
                    170:            myproposal[PROPOSAL_COMP_ALGS_STOC] = options.compression ?
                    171:            "zlib@openssh.com,zlib,none" : "none,zlib@openssh.com,zlib";
1.226     djm       172:        myproposal[PROPOSAL_MAC_ALGS_CTOS] =
                    173:            myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
                    174:        if (options.hostkeyalgorithms != NULL) {
                    175:                if (kex_assemble_names(KEX_DEFAULT_PK_ALG,
                    176:                    &options.hostkeyalgorithms) != 0)
                    177:                        fatal("%s: kex_assemble_namelist", __func__);
1.88      deraadt   178:                myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
1.200     djm       179:                    compat_pkalg_proposal(options.hostkeyalgorithms);
1.226     djm       180:        } else {
1.225     markus    181:                /* Enforce default */
                    182:                options.hostkeyalgorithms = xstrdup(KEX_DEFAULT_PK_ALG);
1.186     djm       183:                /* Prefer algorithms that we already have keys for */
                    184:                myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
1.200     djm       185:                    compat_pkalg_proposal(
                    186:                    order_hostkeyalgs(host, hostaddr, port));
1.186     djm       187:        }
1.115     markus    188:
1.196     dtucker   189:        if (options.rekey_limit || options.rekey_interval)
                    190:                packet_set_rekey_limits((u_int32_t)options.rekey_limit,
                    191:                    (time_t)options.rekey_interval);
1.22      provos    192:
1.65      markus    193:        /* start key exchange */
1.221     markus    194:        if ((r = kex_setup(active_state, myproposal)) != 0)
                    195:                fatal("kex_setup: %s", ssh_err(r));
1.219     markus    196:        kex = active_state->kex;
1.207     markus    197: #ifdef WITH_OPENSSL
1.111     markus    198:        kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
1.138     djm       199:        kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
1.243     djm       200:        kex->kex[KEX_DH_GRP14_SHA256] = kexdh_client;
                    201:        kex->kex[KEX_DH_GRP16_SHA512] = kexdh_client;
                    202:        kex->kex[KEX_DH_GRP18_SHA512] = kexdh_client;
1.111     markus    203:        kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
1.147     djm       204:        kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
1.184     djm       205:        kex->kex[KEX_ECDH_SHA2] = kexecdh_client;
1.207     markus    206: #endif
1.199     markus    207:        kex->kex[KEX_C25519_SHA256] = kexc25519_client;
1.61      markus    208:        kex->client_version_string=client_version_string;
                    209:        kex->server_version_string=server_version_string;
1.75      markus    210:        kex->verify_host_key=&verify_host_key_callback;
1.22      provos    211:
1.219     markus    212:        dispatch_run(DISPATCH_BLOCK, &kex->done, active_state);
1.173     andreas   213:
1.231     markus    214:        /* remove ext-info from the KEX proposals for rekeying */
                    215:        myproposal[PROPOSAL_KEX_ALGS] =
                    216:            compat_kex_proposal(options.kex_algorithms);
                    217:        if ((r = kex_prop2buf(kex->my, myproposal)) != 0)
                    218:                fatal("kex_prop2buf: %s", ssh_err(r));
1.62      markus    219:
                    220:        session_id2 = kex->session_id;
                    221:        session_id2_len = kex->session_id_len;
1.22      provos    222:
                    223: #ifdef DEBUG_KEXDH
                    224:        /* send 1st encrypted/maced/compressed message */
                    225:        packet_start(SSH2_MSG_IGNORE);
                    226:        packet_put_cstring("markus");
                    227:        packet_send();
                    228:        packet_write_wait();
                    229: #endif
1.1       markus    230: }
1.11      markus    231:
1.1       markus    232: /*
                    233:  * Authenticate user
                    234:  */
1.20      markus    235:
1.214     djm       236: typedef struct cauthctxt Authctxt;
                    237: typedef struct cauthmethod Authmethod;
1.117     markus    238: typedef struct identity Identity;
                    239: typedef struct idlist Idlist;
1.20      markus    240:
1.117     markus    241: struct identity {
                    242:        TAILQ_ENTRY(identity) next;
1.214     djm       243:        int     agent_fd;               /* >=0 if agent supports key */
                    244:        struct sshkey   *key;           /* public/private key */
1.117     markus    245:        char    *filename;              /* comment for agent-only keys */
                    246:        int     tried;
                    247:        int     isprivate;              /* key points to the private key */
1.191     dtucker   248:        int     userprovided;
1.117     markus    249: };
                    250: TAILQ_HEAD(idlist, identity);
1.20      markus    251:
1.214     djm       252: struct cauthctxt {
1.20      markus    253:        const char *server_user;
1.68      markus    254:        const char *local_user;
1.20      markus    255:        const char *host;
                    256:        const char *service;
1.214     djm       257:        struct cauthmethod *method;
1.183     djm       258:        sig_atomic_t success;
1.51      markus    259:        char *authlist;
1.214     djm       260:        int attempt;
1.68      markus    261:        /* pubkey */
1.214     djm       262:        struct idlist keys;
                    263:        int agent_fd;
1.68      markus    264:        /* hostbased */
1.100     markus    265:        Sensitive *sensitive;
1.223     djm       266:        char *oktypes, *ktypes;
                    267:        const char *active_ktype;
1.82      markus    268:        /* kbd-interactive */
                    269:        int info_req_seen;
1.121     markus    270:        /* generic */
                    271:        void *methoddata;
1.20      markus    272: };
1.214     djm       273:
                    274: struct cauthmethod {
1.20      markus    275:        char    *name;          /* string to compare against server's list */
                    276:        int     (*userauth)(Authctxt *authctxt);
1.170     djm       277:        void    (*cleanup)(Authctxt *authctxt);
1.20      markus    278:        int     *enabled;       /* flag in option struct that enables method */
                    279:        int     *batch_flag;    /* flag in option struct that disables method */
                    280: };
                    281:
1.231     markus    282: int    input_userauth_service_accept(int, u_int32_t, void *);
                    283: int    input_userauth_ext_info(int, u_int32_t, void *);
1.218     markus    284: int    input_userauth_success(int, u_int32_t, void *);
                    285: int    input_userauth_success_unexpected(int, u_int32_t, void *);
                    286: int    input_userauth_failure(int, u_int32_t, void *);
                    287: int    input_userauth_banner(int, u_int32_t, void *);
                    288: int    input_userauth_error(int, u_int32_t, void *);
                    289: int    input_userauth_info_req(int, u_int32_t, void *);
                    290: int    input_userauth_pk_ok(int, u_int32_t, void *);
                    291: int    input_userauth_passwd_changereq(int, u_int32_t, void *);
1.86      itojun    292:
                    293: int    userauth_none(Authctxt *);
                    294: int    userauth_pubkey(Authctxt *);
                    295: int    userauth_passwd(Authctxt *);
                    296: int    userauth_kbdint(Authctxt *);
                    297: int    userauth_hostbased(Authctxt *);
1.20      markus    298:
1.121     markus    299: #ifdef GSSAPI
                    300: int    userauth_gssapi(Authctxt *authctxt);
1.218     markus    301: int    input_gssapi_response(int type, u_int32_t, void *);
                    302: int    input_gssapi_token(int type, u_int32_t, void *);
                    303: int    input_gssapi_hash(int type, u_int32_t, void *);
                    304: int    input_gssapi_error(int, u_int32_t, void *);
                    305: int    input_gssapi_errtok(int, u_int32_t, void *);
1.121     markus    306: #endif
                    307:
1.86      itojun    308: void   userauth(Authctxt *, char *);
1.51      markus    309:
1.117     markus    310: static int sign_and_send_pubkey(Authctxt *, Identity *);
                    311: static void pubkey_prepare(Authctxt *);
                    312: static void pubkey_cleanup(Authctxt *);
1.229     jcs       313: static Key *load_identity_file(Identity *);
1.76      itojun    314:
                    315: static Authmethod *authmethod_get(char *authlist);
                    316: static Authmethod *authmethod_lookup(const char *name);
                    317: static char *authmethods_get(void);
1.20      markus    318:
                    319: Authmethod authmethods[] = {
1.121     markus    320: #ifdef GSSAPI
1.132     markus    321:        {"gssapi-with-mic",
1.121     markus    322:                userauth_gssapi,
1.170     djm       323:                NULL,
1.121     markus    324:                &options.gss_authentication,
                    325:                NULL},
                    326: #endif
1.81      markus    327:        {"hostbased",
                    328:                userauth_hostbased,
1.170     djm       329:                NULL,
1.81      markus    330:                &options.hostbased_authentication,
                    331:                NULL},
1.20      markus    332:        {"publickey",
                    333:                userauth_pubkey,
1.170     djm       334:                NULL,
1.28      markus    335:                &options.pubkey_authentication,
1.20      markus    336:                NULL},
1.81      markus    337:        {"keyboard-interactive",
                    338:                userauth_kbdint,
1.170     djm       339:                NULL,
1.81      markus    340:                &options.kbd_interactive_authentication,
                    341:                &options.batch_mode},
1.20      markus    342:        {"password",
                    343:                userauth_passwd,
1.170     djm       344:                NULL,
1.20      markus    345:                &options.password_authentication,
1.23      markus    346:                &options.batch_mode},
                    347:        {"none",
                    348:                userauth_none,
                    349:                NULL,
1.170     djm       350:                NULL,
1.23      markus    351:                NULL},
1.170     djm       352:        {NULL, NULL, NULL, NULL, NULL}
1.20      markus    353: };
                    354:
                    355: void
1.68      markus    356: ssh_userauth2(const char *local_user, const char *server_user, char *host,
1.100     markus    357:     Sensitive *sensitive)
1.20      markus    358: {
1.231     markus    359:        struct ssh *ssh = active_state;
1.20      markus    360:        Authctxt authctxt;
1.231     markus    361:        int r;
1.39      markus    362:
1.73      markus    363:        if (options.challenge_response_authentication)
1.39      markus    364:                options.kbd_interactive_authentication = 1;
1.53      markus    365:        if (options.preferred_authentications == NULL)
                    366:                options.preferred_authentications = authmethods_get();
                    367:
1.20      markus    368:        /* setup authentication context */
1.82      markus    369:        memset(&authctxt, 0, sizeof(authctxt));
1.117     markus    370:        pubkey_prepare(&authctxt);
1.20      markus    371:        authctxt.server_user = server_user;
1.68      markus    372:        authctxt.local_user = local_user;
1.20      markus    373:        authctxt.host = host;
                    374:        authctxt.service = "ssh-connection";            /* service name */
                    375:        authctxt.success = 0;
1.23      markus    376:        authctxt.method = authmethod_lookup("none");
1.51      markus    377:        authctxt.authlist = NULL;
1.121     markus    378:        authctxt.methoddata = NULL;
1.100     markus    379:        authctxt.sensitive = sensitive;
1.223     djm       380:        authctxt.active_ktype = authctxt.oktypes = authctxt.ktypes = NULL;
1.82      markus    381:        authctxt.info_req_seen = 0;
1.215     djm       382:        authctxt.agent_fd = -1;
1.23      markus    383:        if (authctxt.method == NULL)
                    384:                fatal("ssh_userauth2: internal error: cannot send userauth none request");
1.20      markus    385:
1.231     markus    386:        if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_REQUEST)) != 0 ||
                    387:            (r = sshpkt_put_cstring(ssh, "ssh-userauth")) != 0 ||
                    388:            (r = sshpkt_send(ssh)) != 0)
                    389:                fatal("%s: %s", __func__, ssh_err(r));
                    390:
                    391:        ssh_dispatch_init(ssh, &input_userauth_error);
                    392:        ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_ext_info);
                    393:        ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_ACCEPT, &input_userauth_service_accept);
                    394:        ssh_dispatch_run(ssh, DISPATCH_BLOCK, &authctxt.success, &authctxt);    /* loop until success */
1.20      markus    395:
1.117     markus    396:        pubkey_cleanup(&authctxt);
1.231     markus    397:        ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
1.119     markus    398:
1.109     markus    399:        debug("Authentication succeeded (%s).", authctxt.method->name);
1.20      markus    400: }
1.119     markus    401:
1.231     markus    402: /* ARGSUSED */
                    403: int
                    404: input_userauth_service_accept(int type, u_int32_t seqnr, void *ctxt)
                    405: {
                    406:        Authctxt *authctxt = ctxt;
                    407:        struct ssh *ssh = active_state;
                    408:        int r;
                    409:
                    410:        if (ssh_packet_remaining(ssh) > 0) {
                    411:                char *reply;
                    412:
                    413:                if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0)
                    414:                        goto out;
                    415:                debug2("service_accept: %s", reply);
                    416:                free(reply);
                    417:        } else {
                    418:                debug2("buggy server: service_accept w/o service");
                    419:        }
                    420:        if ((r = sshpkt_get_end(ssh)) != 0)
                    421:                goto out;
                    422:        debug("SSH2_MSG_SERVICE_ACCEPT received");
                    423:
                    424:        /* initial userauth request */
                    425:        userauth_none(authctxt);
                    426:
                    427:        ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_error);
                    428:        ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
                    429:        ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
                    430:        ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
                    431:        r = 0;
                    432:  out:
                    433:        return r;
                    434: }
                    435:
                    436: /* ARGSUSED */
                    437: int
                    438: input_userauth_ext_info(int type, u_int32_t seqnr, void *ctxt)
                    439: {
                    440:        return kex_input_ext_info(type, seqnr, active_state);
                    441: }
                    442:
1.20      markus    443: void
1.51      markus    444: userauth(Authctxt *authctxt, char *authlist)
                    445: {
1.170     djm       446:        if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
                    447:                authctxt->method->cleanup(authctxt);
                    448:
1.197     djm       449:        free(authctxt->methoddata);
                    450:        authctxt->methoddata = NULL;
1.51      markus    451:        if (authlist == NULL) {
                    452:                authlist = authctxt->authlist;
                    453:        } else {
1.197     djm       454:                free(authctxt->authlist);
1.51      markus    455:                authctxt->authlist = authlist;
                    456:        }
                    457:        for (;;) {
                    458:                Authmethod *method = authmethod_get(authlist);
                    459:                if (method == NULL)
                    460:                        fatal("Permission denied (%s).", authlist);
                    461:                authctxt->method = method;
1.119     markus    462:
                    463:                /* reset the per method handler */
                    464:                dispatch_range(SSH2_MSG_USERAUTH_PER_METHOD_MIN,
                    465:                    SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
                    466:
                    467:                /* and try new method */
1.51      markus    468:                if (method->userauth(authctxt) != 0) {
                    469:                        debug2("we sent a %s packet, wait for reply", method->name);
                    470:                        break;
                    471:                } else {
                    472:                        debug2("we did not send a packet, disable method");
                    473:                        method->enabled = NULL;
                    474:                }
                    475:        }
                    476: }
1.105     deraadt   477:
1.169     djm       478: /* ARGSUSED */
1.218     markus    479: int
1.92      markus    480: input_userauth_error(int type, u_int32_t seq, void *ctxt)
1.20      markus    481: {
1.35      markus    482:        fatal("input_userauth_error: bad message during authentication: "
1.140     djm       483:            "type %d", type);
1.218     markus    484:        return 0;
1.35      markus    485: }
1.105     deraadt   486:
1.169     djm       487: /* ARGSUSED */
1.218     markus    488: int
1.92      markus    489: input_userauth_banner(int type, u_int32_t seq, void *ctxt)
1.35      markus    490: {
1.246   ! djm       491:        char *msg, *lang;
1.166     djm       492:        u_int len;
1.126     deraadt   493:
1.246   ! djm       494:        debug3("%s", __func__);
        !           495:        msg = packet_get_string(&len);
1.35      markus    496:        lang = packet_get_string(NULL);
1.246   ! djm       497:        if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO)
        !           498:                fmprintf(stderr, "%s", msg);
        !           499:        free(msg);
1.197     djm       500:        free(lang);
1.218     markus    501:        return 0;
1.20      markus    502: }
1.105     deraadt   503:
1.169     djm       504: /* ARGSUSED */
1.218     markus    505: int
1.92      markus    506: input_userauth_success(int type, u_int32_t seq, void *ctxt)
1.20      markus    507: {
                    508:        Authctxt *authctxt = ctxt;
1.172     djm       509:
1.20      markus    510:        if (authctxt == NULL)
                    511:                fatal("input_userauth_success: no authentication context");
1.197     djm       512:        free(authctxt->authlist);
                    513:        authctxt->authlist = NULL;
1.172     djm       514:        if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
                    515:                authctxt->method->cleanup(authctxt);
1.197     djm       516:        free(authctxt->methoddata);
                    517:        authctxt->methoddata = NULL;
1.20      markus    518:        authctxt->success = 1;                  /* break out */
1.218     markus    519:        return 0;
1.20      markus    520: }
1.105     deraadt   521:
1.218     markus    522: int
1.172     djm       523: input_userauth_success_unexpected(int type, u_int32_t seq, void *ctxt)
                    524: {
                    525:        Authctxt *authctxt = ctxt;
                    526:
                    527:        if (authctxt == NULL)
                    528:                fatal("%s: no authentication context", __func__);
                    529:
                    530:        fatal("Unexpected authentication success during %s.",
                    531:            authctxt->method->name);
1.218     markus    532:        return 0;
1.172     djm       533: }
                    534:
1.169     djm       535: /* ARGSUSED */
1.218     markus    536: int
1.92      markus    537: input_userauth_failure(int type, u_int32_t seq, void *ctxt)
1.20      markus    538: {
                    539:        Authctxt *authctxt = ctxt;
                    540:        char *authlist = NULL;
                    541:        int partial;
                    542:
                    543:        if (authctxt == NULL)
                    544:                fatal("input_userauth_failure: no authentication context");
                    545:
1.23      markus    546:        authlist = packet_get_string(NULL);
1.20      markus    547:        partial = packet_get_char();
1.90      markus    548:        packet_check_eom();
1.20      markus    549:
1.193     markus    550:        if (partial != 0) {
1.116     itojun    551:                logit("Authenticated with partial success.");
1.193     markus    552:                /* reset state */
                    553:                pubkey_cleanup(authctxt);
                    554:                pubkey_prepare(authctxt);
                    555:        }
1.109     markus    556:        debug("Authentications that can continue: %s", authlist);
1.20      markus    557:
1.51      markus    558:        userauth(authctxt, authlist);
1.218     markus    559:        return 0;
1.51      markus    560: }
1.169     djm       561:
                    562: /* ARGSUSED */
1.218     markus    563: int
1.92      markus    564: input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt)
1.51      markus    565: {
                    566:        Authctxt *authctxt = ctxt;
                    567:        Key *key = NULL;
1.117     markus    568:        Identity *id = NULL;
1.51      markus    569:        Buffer b;
1.96      markus    570:        int pktype, sent = 0;
                    571:        u_int alen, blen;
                    572:        char *pkalg, *fp;
                    573:        u_char *pkblob;
1.51      markus    574:
                    575:        if (authctxt == NULL)
                    576:                fatal("input_userauth_pk_ok: no authentication context");
                    577:        if (datafellows & SSH_BUG_PKOK) {
                    578:                /* this is similar to SSH_BUG_PKAUTH */
                    579:                debug2("input_userauth_pk_ok: SSH_BUG_PKOK");
                    580:                pkblob = packet_get_string(&blen);
                    581:                buffer_init(&b);
                    582:                buffer_append(&b, pkblob, blen);
                    583:                pkalg = buffer_get_string(&b, &alen);
                    584:                buffer_free(&b);
                    585:        } else {
                    586:                pkalg = packet_get_string(&alen);
                    587:                pkblob = packet_get_string(&blen);
                    588:        }
1.90      markus    589:        packet_check_eom();
1.51      markus    590:
1.117     markus    591:        debug("Server accepts key: pkalg %s blen %u", pkalg, blen);
1.51      markus    592:
1.117     markus    593:        if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
                    594:                debug("unknown pkalg %s", pkalg);
                    595:                goto done;
                    596:        }
                    597:        if ((key = key_from_blob(pkblob, blen)) == NULL) {
                    598:                debug("no key from blob. pkalg %s", pkalg);
                    599:                goto done;
                    600:        }
                    601:        if (key->type != pktype) {
                    602:                error("input_userauth_pk_ok: type mismatch "
                    603:                    "for decoded key (received %d, expected %d)",
                    604:                    key->type, pktype);
                    605:                goto done;
                    606:        }
1.222     djm       607:        if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
                    608:            SSH_FP_DEFAULT)) == NULL)
                    609:                goto done;
1.117     markus    610:        debug2("input_userauth_pk_ok: fp %s", fp);
1.197     djm       611:        free(fp);
1.117     markus    612:
1.127     markus    613:        /*
                    614:         * search keys in the reverse order, because last candidate has been
                    615:         * moved to the end of the queue.  this also avoids confusion by
                    616:         * duplicate keys
                    617:         */
1.136     henning   618:        TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
1.117     markus    619:                if (key_equal(key, id->key)) {
                    620:                        sent = sign_and_send_pubkey(authctxt, id);
1.51      markus    621:                        break;
                    622:                }
1.117     markus    623:        }
                    624: done:
1.51      markus    625:        if (key != NULL)
                    626:                key_free(key);
1.197     djm       627:        free(pkalg);
                    628:        free(pkblob);
1.51      markus    629:
1.106     deraadt   630:        /* try another method if we did not send a packet */
1.51      markus    631:        if (sent == 0)
                    632:                userauth(authctxt, NULL);
1.218     markus    633:        return 0;
1.20      markus    634: }
1.121     markus    635:
                    636: #ifdef GSSAPI
1.133     djm       637: int
1.121     markus    638: userauth_gssapi(Authctxt *authctxt)
                    639: {
                    640:        Gssctxt *gssctxt = NULL;
1.128     avsm      641:        static gss_OID_set gss_supported = NULL;
1.139     djm       642:        static u_int mech = 0;
1.121     markus    643:        OM_uint32 min;
                    644:        int ok = 0;
                    645:
                    646:        /* Try one GSSAPI method at a time, rather than sending them all at
                    647:         * once. */
                    648:
1.128     avsm      649:        if (gss_supported == NULL)
                    650:                gss_indicate_mechs(&min, &gss_supported);
1.121     markus    651:
                    652:        /* Check to see if the mechanism is usable before we offer it */
1.128     avsm      653:        while (mech < gss_supported->count && !ok) {
1.121     markus    654:                /* My DER encoding requires length<128 */
1.128     avsm      655:                if (gss_supported->elements[mech].length < 128 &&
1.161     djm       656:                    ssh_gssapi_check_mechanism(&gssctxt,
                    657:                    &gss_supported->elements[mech], authctxt->host)) {
1.121     markus    658:                        ok = 1; /* Mechanism works */
                    659:                } else {
                    660:                        mech++;
                    661:                }
                    662:        }
                    663:
1.161     djm       664:        if (!ok)
1.139     djm       665:                return 0;
1.121     markus    666:
                    667:        authctxt->methoddata=(void *)gssctxt;
                    668:
                    669:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
                    670:        packet_put_cstring(authctxt->server_user);
                    671:        packet_put_cstring(authctxt->service);
                    672:        packet_put_cstring(authctxt->method->name);
                    673:
                    674:        packet_put_int(1);
                    675:
1.129     markus    676:        packet_put_int((gss_supported->elements[mech].length) + 2);
                    677:        packet_put_char(SSH_GSS_OIDTYPE);
                    678:        packet_put_char(gss_supported->elements[mech].length);
                    679:        packet_put_raw(gss_supported->elements[mech].elements,
                    680:            gss_supported->elements[mech].length);
1.121     markus    681:
                    682:        packet_send();
                    683:
                    684:        dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
                    685:        dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
                    686:        dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
                    687:        dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
                    688:
                    689:        mech++; /* Move along to next candidate */
                    690:
                    691:        return 1;
                    692: }
                    693:
1.130     markus    694: static OM_uint32
                    695: process_gssapi_token(void *ctxt, gss_buffer_t recv_tok)
                    696: {
                    697:        Authctxt *authctxt = ctxt;
                    698:        Gssctxt *gssctxt = authctxt->methoddata;
                    699:        gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
1.142     djm       700:        gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
                    701:        gss_buffer_desc gssbuf;
1.132     markus    702:        OM_uint32 status, ms, flags;
                    703:        Buffer b;
1.133     djm       704:
1.130     markus    705:        status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
1.132     markus    706:            recv_tok, &send_tok, &flags);
1.130     markus    707:
                    708:        if (send_tok.length > 0) {
                    709:                if (GSS_ERROR(status))
                    710:                        packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK);
                    711:                else
                    712:                        packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
1.133     djm       713:
1.130     markus    714:                packet_put_string(send_tok.value, send_tok.length);
                    715:                packet_send();
                    716:                gss_release_buffer(&ms, &send_tok);
                    717:        }
1.133     djm       718:
1.130     markus    719:        if (status == GSS_S_COMPLETE) {
1.132     markus    720:                /* send either complete or MIC, depending on mechanism */
                    721:                if (!(flags & GSS_C_INTEG_FLAG)) {
                    722:                        packet_start(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE);
                    723:                        packet_send();
                    724:                } else {
                    725:                        ssh_gssapi_buildmic(&b, authctxt->server_user,
                    726:                            authctxt->service, "gssapi-with-mic");
                    727:
                    728:                        gssbuf.value = buffer_ptr(&b);
                    729:                        gssbuf.length = buffer_len(&b);
1.133     djm       730:
1.132     markus    731:                        status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
1.133     djm       732:
1.132     markus    733:                        if (!GSS_ERROR(status)) {
                    734:                                packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC);
                    735:                                packet_put_string(mic.value, mic.length);
1.133     djm       736:
1.132     markus    737:                                packet_send();
                    738:                        }
1.133     djm       739:
1.132     markus    740:                        buffer_free(&b);
                    741:                        gss_release_buffer(&ms, &mic);
1.133     djm       742:                }
1.130     markus    743:        }
1.133     djm       744:
1.130     markus    745:        return status;
                    746: }
                    747:
1.169     djm       748: /* ARGSUSED */
1.220     djm       749: int
1.121     markus    750: input_gssapi_response(int type, u_int32_t plen, void *ctxt)
                    751: {
                    752:        Authctxt *authctxt = ctxt;
                    753:        Gssctxt *gssctxt;
                    754:        int oidlen;
                    755:        char *oidv;
                    756:
                    757:        if (authctxt == NULL)
                    758:                fatal("input_gssapi_response: no authentication context");
                    759:        gssctxt = authctxt->methoddata;
                    760:
                    761:        /* Setup our OID */
                    762:        oidv = packet_get_string(&oidlen);
                    763:
1.129     markus    764:        if (oidlen <= 2 ||
                    765:            oidv[0] != SSH_GSS_OIDTYPE ||
                    766:            oidv[1] != oidlen - 2) {
1.197     djm       767:                free(oidv);
1.129     markus    768:                debug("Badly encoded mechanism OID received");
                    769:                userauth(authctxt, NULL);
1.220     djm       770:                return 0;
1.121     markus    771:        }
1.129     markus    772:
                    773:        if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
                    774:                fatal("Server returned different OID than expected");
1.121     markus    775:
                    776:        packet_check_eom();
                    777:
1.197     djm       778:        free(oidv);
1.121     markus    779:
1.130     markus    780:        if (GSS_ERROR(process_gssapi_token(ctxt, GSS_C_NO_BUFFER))) {
1.121     markus    781:                /* Start again with next method on list */
                    782:                debug("Trying to start again");
                    783:                userauth(authctxt, NULL);
1.220     djm       784:                return 0;
1.121     markus    785:        }
1.220     djm       786:        return 0;
1.121     markus    787: }
                    788:
1.169     djm       789: /* ARGSUSED */
1.220     djm       790: int
1.121     markus    791: input_gssapi_token(int type, u_int32_t plen, void *ctxt)
                    792: {
                    793:        Authctxt *authctxt = ctxt;
                    794:        gss_buffer_desc recv_tok;
1.130     markus    795:        OM_uint32 status;
1.121     markus    796:        u_int slen;
                    797:
                    798:        if (authctxt == NULL)
                    799:                fatal("input_gssapi_response: no authentication context");
                    800:
                    801:        recv_tok.value = packet_get_string(&slen);
                    802:        recv_tok.length = slen; /* safe typecast */
                    803:
                    804:        packet_check_eom();
                    805:
1.130     markus    806:        status = process_gssapi_token(ctxt, &recv_tok);
1.121     markus    807:
1.197     djm       808:        free(recv_tok.value);
1.121     markus    809:
                    810:        if (GSS_ERROR(status)) {
                    811:                /* Start again with the next method in the list */
                    812:                userauth(authctxt, NULL);
1.220     djm       813:                return 0;
1.121     markus    814:        }
1.220     djm       815:        return 0;
1.121     markus    816: }
                    817:
1.169     djm       818: /* ARGSUSED */
1.220     djm       819: int
1.121     markus    820: input_gssapi_errtok(int type, u_int32_t plen, void *ctxt)
                    821: {
                    822:        Authctxt *authctxt = ctxt;
                    823:        Gssctxt *gssctxt;
                    824:        gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
                    825:        gss_buffer_desc recv_tok;
1.194     djm       826:        OM_uint32 ms;
1.123     deraadt   827:        u_int len;
1.121     markus    828:
                    829:        if (authctxt == NULL)
                    830:                fatal("input_gssapi_response: no authentication context");
                    831:        gssctxt = authctxt->methoddata;
                    832:
1.123     deraadt   833:        recv_tok.value = packet_get_string(&len);
                    834:        recv_tok.length = len;
1.121     markus    835:
                    836:        packet_check_eom();
                    837:
                    838:        /* Stick it into GSSAPI and see what it says */
1.194     djm       839:        (void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
1.140     djm       840:            &recv_tok, &send_tok, NULL);
1.121     markus    841:
1.197     djm       842:        free(recv_tok.value);
1.121     markus    843:        gss_release_buffer(&ms, &send_tok);
                    844:
                    845:        /* Server will be returning a failed packet after this one */
1.220     djm       846:        return 0;
1.121     markus    847: }
                    848:
1.169     djm       849: /* ARGSUSED */
1.220     djm       850: int
1.121     markus    851: input_gssapi_error(int type, u_int32_t plen, void *ctxt)
                    852: {
                    853:        char *msg;
                    854:        char *lang;
                    855:
1.194     djm       856:        /* maj */(void)packet_get_int();
                    857:        /* min */(void)packet_get_int();
1.121     markus    858:        msg=packet_get_string(NULL);
                    859:        lang=packet_get_string(NULL);
                    860:
                    861:        packet_check_eom();
                    862:
1.143     stevesk   863:        debug("Server GSSAPI Error:\n%s", msg);
1.197     djm       864:        free(msg);
                    865:        free(lang);
1.220     djm       866:        return 0;
1.121     markus    867: }
                    868: #endif /* GSSAPI */
1.20      markus    869:
1.1       markus    870: int
1.23      markus    871: userauth_none(Authctxt *authctxt)
                    872: {
                    873:        /* initial userauth request */
                    874:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
                    875:        packet_put_cstring(authctxt->server_user);
                    876:        packet_put_cstring(authctxt->service);
                    877:        packet_put_cstring(authctxt->method->name);
                    878:        packet_send();
                    879:        return 1;
                    880: }
                    881:
                    882: int
1.20      markus    883: userauth_passwd(Authctxt *authctxt)
1.1       markus    884: {
1.6       markus    885:        static int attempt = 0;
1.99      markus    886:        char prompt[150];
1.1       markus    887:        char *password;
1.175     dtucker   888:        const char *host = options.host_key_alias ?  options.host_key_alias :
                    889:            authctxt->host;
1.6       markus    890:
1.13      todd      891:        if (attempt++ >= options.number_of_password_prompts)
1.6       markus    892:                return 0;
1.13      todd      893:
1.87      deraadt   894:        if (attempt != 1)
1.13      todd      895:                error("Permission denied, please try again.");
1.1       markus    896:
1.43      itojun    897:        snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
1.175     dtucker   898:            authctxt->server_user, host);
1.1       markus    899:        password = read_passphrase(prompt, 0);
                    900:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
1.20      markus    901:        packet_put_cstring(authctxt->server_user);
                    902:        packet_put_cstring(authctxt->service);
1.23      markus    903:        packet_put_cstring(authctxt->method->name);
1.1       markus    904:        packet_put_char(0);
1.49      markus    905:        packet_put_cstring(password);
1.204     djm       906:        explicit_bzero(password, strlen(password));
1.197     djm       907:        free(password);
1.85      markus    908:        packet_add_padding(64);
1.1       markus    909:        packet_send();
1.99      markus    910:
1.104     deraadt   911:        dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1.99      markus    912:            &input_userauth_passwd_changereq);
                    913:
1.1       markus    914:        return 1;
                    915: }
1.169     djm       916:
1.99      markus    917: /*
                    918:  * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
                    919:  */
1.169     djm       920: /* ARGSUSED */
1.218     markus    921: int
1.153     djm       922: input_userauth_passwd_changereq(int type, u_int32_t seqnr, void *ctxt)
1.99      markus    923: {
                    924:        Authctxt *authctxt = ctxt;
                    925:        char *info, *lang, *password = NULL, *retype = NULL;
                    926:        char prompt[150];
1.175     dtucker   927:        const char *host = options.host_key_alias ? options.host_key_alias :
                    928:            authctxt->host;
1.99      markus    929:
                    930:        debug2("input_userauth_passwd_changereq");
                    931:
                    932:        if (authctxt == NULL)
                    933:                fatal("input_userauth_passwd_changereq: "
                    934:                    "no authentication context");
                    935:
                    936:        info = packet_get_string(NULL);
                    937:        lang = packet_get_string(NULL);
                    938:        if (strlen(info) > 0)
1.116     itojun    939:                logit("%s", info);
1.197     djm       940:        free(info);
                    941:        free(lang);
1.99      markus    942:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
                    943:        packet_put_cstring(authctxt->server_user);
                    944:        packet_put_cstring(authctxt->service);
                    945:        packet_put_cstring(authctxt->method->name);
                    946:        packet_put_char(1);                     /* additional info */
1.104     deraadt   947:        snprintf(prompt, sizeof(prompt),
1.99      markus    948:            "Enter %.30s@%.128s's old password: ",
1.175     dtucker   949:            authctxt->server_user, host);
1.99      markus    950:        password = read_passphrase(prompt, 0);
                    951:        packet_put_cstring(password);
1.204     djm       952:        explicit_bzero(password, strlen(password));
1.197     djm       953:        free(password);
1.99      markus    954:        password = NULL;
                    955:        while (password == NULL) {
1.104     deraadt   956:                snprintf(prompt, sizeof(prompt),
1.99      markus    957:                    "Enter %.30s@%.128s's new password: ",
1.175     dtucker   958:                    authctxt->server_user, host);
1.99      markus    959:                password = read_passphrase(prompt, RP_ALLOW_EOF);
                    960:                if (password == NULL) {
                    961:                        /* bail out */
1.218     markus    962:                        return 0;
1.99      markus    963:                }
1.104     deraadt   964:                snprintf(prompt, sizeof(prompt),
1.99      markus    965:                    "Retype %.30s@%.128s's new password: ",
1.175     dtucker   966:                    authctxt->server_user, host);
1.99      markus    967:                retype = read_passphrase(prompt, 0);
                    968:                if (strcmp(password, retype) != 0) {
1.204     djm       969:                        explicit_bzero(password, strlen(password));
1.197     djm       970:                        free(password);
1.116     itojun    971:                        logit("Mismatch; try again, EOF to quit.");
1.99      markus    972:                        password = NULL;
                    973:                }
1.204     djm       974:                explicit_bzero(retype, strlen(retype));
1.197     djm       975:                free(retype);
1.99      markus    976:        }
                    977:        packet_put_cstring(password);
1.204     djm       978:        explicit_bzero(password, strlen(password));
1.197     djm       979:        free(password);
1.99      markus    980:        packet_add_padding(64);
                    981:        packet_send();
1.104     deraadt   982:
                    983:        dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1.99      markus    984:            &input_userauth_passwd_changereq);
1.218     markus    985:        return 0;
1.117     markus    986: }
                    987:
1.231     markus    988: static const char *
                    989: identity_sign_encode(struct identity *id)
                    990: {
                    991:        struct ssh *ssh = active_state;
                    992:
                    993:        if (id->key->type == KEY_RSA) {
                    994:                switch (ssh->kex->rsa_sha2) {
                    995:                case 256:
                    996:                        return "rsa-sha2-256";
                    997:                case 512:
                    998:                        return "rsa-sha2-512";
                    999:                }
                   1000:        }
                   1001:        return key_ssh_name(id->key);
                   1002: }
                   1003:
1.117     markus   1004: static int
1.214     djm      1005: identity_sign(struct identity *id, u_char **sigp, size_t *lenp,
                   1006:     const u_char *data, size_t datalen, u_int compat)
1.117     markus   1007: {
                   1008:        Key *prv;
                   1009:        int ret;
1.231     markus   1010:        const char *alg;
                   1011:
                   1012:        alg = identity_sign_encode(id);
1.99      markus   1013:
1.117     markus   1014:        /* the agent supports this key */
1.230     djm      1015:        if (id->agent_fd != -1)
1.214     djm      1016:                return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp,
1.231     markus   1017:                    data, datalen, alg, compat);
1.214     djm      1018:
1.117     markus   1019:        /*
                   1020:         * we have already loaded the private key or
                   1021:         * the private key is stored in external hardware
                   1022:         */
1.209     djm      1023:        if (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT))
1.231     markus   1024:                return (sshkey_sign(id->key, sigp, lenp, data, datalen, alg,
1.214     djm      1025:                    compat));
1.117     markus   1026:        /* load the private key from the file */
1.229     jcs      1027:        if ((prv = load_identity_file(id)) == NULL)
1.239     djm      1028:                return SSH_ERR_KEY_NOT_FOUND;
1.231     markus   1029:        ret = sshkey_sign(prv, sigp, lenp, data, datalen, alg, compat);
1.214     djm      1030:        sshkey_free(prv);
1.117     markus   1031:        return (ret);
1.51      markus   1032: }
                   1033:
1.76      itojun   1034: static int
1.117     markus   1035: sign_and_send_pubkey(Authctxt *authctxt, Identity *id)
1.1       markus   1036: {
                   1037:        Buffer b;
1.227     djm      1038:        Identity *private_id;
1.32      markus   1039:        u_char *blob, *signature;
1.214     djm      1040:        size_t slen;
1.227     djm      1041:        u_int bloblen, skip = 0;
                   1042:        int matched, ret = -1, have_sig = 1;
1.182     djm      1043:        char *fp;
1.1       markus   1044:
1.222     djm      1045:        if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
                   1046:            SSH_FP_DEFAULT)) == NULL)
                   1047:                return 0;
1.227     djm      1048:        debug3("%s: %s %s", __func__, key_type(id->key), fp);
1.197     djm      1049:        free(fp);
1.51      markus   1050:
1.117     markus   1051:        if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1.28      markus   1052:                /* we cannot handle this key */
1.30      markus   1053:                debug3("sign_and_send_pubkey: cannot handle key");
1.28      markus   1054:                return 0;
                   1055:        }
1.1       markus   1056:        /* data to be signed */
                   1057:        buffer_init(&b);
1.26      markus   1058:        if (datafellows & SSH_OLD_SESSIONID) {
                   1059:                buffer_append(&b, session_id2, session_id2_len);
1.41      stevesk  1060:                skip = session_id2_len;
1.26      markus   1061:        } else {
1.14      markus   1062:                buffer_put_string(&b, session_id2, session_id2_len);
                   1063:                skip = buffer_len(&b);
                   1064:        }
1.1       markus   1065:        buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1.20      markus   1066:        buffer_put_cstring(&b, authctxt->server_user);
1.10      markus   1067:        buffer_put_cstring(&b,
1.30      markus   1068:            datafellows & SSH_BUG_PKSERVICE ?
1.10      markus   1069:            "ssh-userauth" :
1.20      markus   1070:            authctxt->service);
1.30      markus   1071:        if (datafellows & SSH_BUG_PKAUTH) {
                   1072:                buffer_put_char(&b, have_sig);
                   1073:        } else {
                   1074:                buffer_put_cstring(&b, authctxt->method->name);
                   1075:                buffer_put_char(&b, have_sig);
1.231     markus   1076:                buffer_put_cstring(&b, identity_sign_encode(id));
1.30      markus   1077:        }
1.1       markus   1078:        buffer_put_string(&b, blob, bloblen);
                   1079:
1.227     djm      1080:        /*
                   1081:         * If the key is an certificate, try to find a matching private key
                   1082:         * and use it to complete the signature.
1.241     djm      1083:         * If no such private key exists, fall back to trying the certificate
                   1084:         * key itself in case it has a private half already loaded.
1.227     djm      1085:         */
                   1086:        if (key_is_cert(id->key)) {
                   1087:                matched = 0;
                   1088:                TAILQ_FOREACH(private_id, &authctxt->keys, next) {
                   1089:                        if (sshkey_equal_public(id->key, private_id->key) &&
                   1090:                            id->key->type != private_id->key->type) {
                   1091:                                id = private_id;
                   1092:                                matched = 1;
                   1093:                                break;
                   1094:                        }
                   1095:                }
                   1096:                if (matched) {
                   1097:                        debug2("%s: using private key \"%s\"%s for "
                   1098:                            "certificate", __func__, id->filename,
                   1099:                            id->agent_fd != -1 ? " from agent" : "");
                   1100:                } else {
1.240     djm      1101:                        debug("%s: no separate private key for certificate "
1.227     djm      1102:                            "\"%s\"", __func__, id->filename);
                   1103:                }
                   1104:        }
                   1105:
1.1       markus   1106:        /* generate signature */
1.117     markus   1107:        ret = identity_sign(id, &signature, &slen,
1.214     djm      1108:            buffer_ptr(&b), buffer_len(&b), datafellows);
                   1109:        if (ret != 0) {
1.239     djm      1110:                if (ret != SSH_ERR_KEY_NOT_FOUND)
                   1111:                        error("%s: signing failed: %s", __func__, ssh_err(ret));
1.197     djm      1112:                free(blob);
1.17      markus   1113:                buffer_free(&b);
                   1114:                return 0;
                   1115:        }
1.28      markus   1116: #ifdef DEBUG_PK
1.1       markus   1117:        buffer_dump(&b);
                   1118: #endif
1.30      markus   1119:        if (datafellows & SSH_BUG_PKSERVICE) {
1.10      markus   1120:                buffer_clear(&b);
                   1121:                buffer_append(&b, session_id2, session_id2_len);
1.51      markus   1122:                skip = session_id2_len;
1.10      markus   1123:                buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1.20      markus   1124:                buffer_put_cstring(&b, authctxt->server_user);
                   1125:                buffer_put_cstring(&b, authctxt->service);
1.23      markus   1126:                buffer_put_cstring(&b, authctxt->method->name);
                   1127:                buffer_put_char(&b, have_sig);
1.30      markus   1128:                if (!(datafellows & SSH_BUG_PKAUTH))
1.117     markus   1129:                        buffer_put_cstring(&b, key_ssh_name(id->key));
1.10      markus   1130:                buffer_put_string(&b, blob, bloblen);
                   1131:        }
1.197     djm      1132:        free(blob);
1.51      markus   1133:
1.1       markus   1134:        /* append signature */
                   1135:        buffer_put_string(&b, signature, slen);
1.197     djm      1136:        free(signature);
1.1       markus   1137:
                   1138:        /* skip session id and packet type */
1.14      markus   1139:        if (buffer_len(&b) < skip + 1)
1.20      markus   1140:                fatal("userauth_pubkey: internal error");
1.14      markus   1141:        buffer_consume(&b, skip + 1);
1.1       markus   1142:
                   1143:        /* put remaining data from buffer into packet */
                   1144:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
                   1145:        packet_put_raw(buffer_ptr(&b), buffer_len(&b));
                   1146:        buffer_free(&b);
                   1147:        packet_send();
1.17      markus   1148:
                   1149:        return 1;
1.16      markus   1150: }
                   1151:
1.76      itojun   1152: static int
1.117     markus   1153: send_pubkey_test(Authctxt *authctxt, Identity *id)
1.20      markus   1154: {
1.51      markus   1155:        u_char *blob;
1.97      markus   1156:        u_int bloblen, have_sig = 0;
1.20      markus   1157:
1.51      markus   1158:        debug3("send_pubkey_test");
1.16      markus   1159:
1.117     markus   1160:        if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1.51      markus   1161:                /* we cannot handle this key */
                   1162:                debug3("send_pubkey_test: cannot handle key");
1.16      markus   1163:                return 0;
                   1164:        }
1.51      markus   1165:        /* register callback for USERAUTH_PK_OK message */
                   1166:        dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
                   1167:
                   1168:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
                   1169:        packet_put_cstring(authctxt->server_user);
                   1170:        packet_put_cstring(authctxt->service);
                   1171:        packet_put_cstring(authctxt->method->name);
                   1172:        packet_put_char(have_sig);
                   1173:        if (!(datafellows & SSH_BUG_PKAUTH))
1.231     markus   1174:                packet_put_cstring(identity_sign_encode(id));
1.51      markus   1175:        packet_put_string(blob, bloblen);
1.197     djm      1176:        free(blob);
1.51      markus   1177:        packet_send();
                   1178:        return 1;
                   1179: }
                   1180:
1.76      itojun   1181: static Key *
1.229     jcs      1182: load_identity_file(Identity *id)
1.51      markus   1183: {
1.238     jsg      1184:        Key *private = NULL;
1.229     jcs      1185:        char prompt[300], *passphrase, *comment;
1.215     djm      1186:        int r, perm_ok = 0, quit = 0, i;
1.52      markus   1187:        struct stat st;
1.16      markus   1188:
1.229     jcs      1189:        if (stat(id->filename, &st) < 0) {
                   1190:                (id->userprovided ? logit : debug3)("no such identity: %s: %s",
                   1191:                    id->filename, strerror(errno));
1.52      markus   1192:                return NULL;
                   1193:        }
1.214     djm      1194:        snprintf(prompt, sizeof prompt,
1.229     jcs      1195:            "Enter passphrase for key '%.100s': ", id->filename);
1.214     djm      1196:        for (i = 0; i <= options.number_of_password_prompts; i++) {
                   1197:                if (i == 0)
                   1198:                        passphrase = "";
                   1199:                else {
1.20      markus   1200:                        passphrase = read_passphrase(prompt, 0);
1.214     djm      1201:                        if (*passphrase == '\0') {
1.20      markus   1202:                                debug2("no passphrase given, try next key");
1.214     djm      1203:                                free(passphrase);
                   1204:                                break;
                   1205:                        }
                   1206:                }
1.229     jcs      1207:                switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename,
                   1208:                    passphrase, &private, &comment, &perm_ok))) {
1.214     djm      1209:                case 0:
                   1210:                        break;
                   1211:                case SSH_ERR_KEY_WRONG_PASSPHRASE:
                   1212:                        if (options.batch_mode) {
                   1213:                                quit = 1;
                   1214:                                break;
                   1215:                        }
1.215     djm      1216:                        if (i != 0)
                   1217:                                debug2("bad passphrase given, try again...");
1.214     djm      1218:                        break;
                   1219:                case SSH_ERR_SYSTEM_ERROR:
                   1220:                        if (errno == ENOENT) {
                   1221:                                debug2("Load key \"%s\": %s",
1.229     jcs      1222:                                    id->filename, ssh_err(r));
1.51      markus   1223:                                quit = 1;
1.214     djm      1224:                                break;
1.20      markus   1225:                        }
1.214     djm      1226:                        /* FALLTHROUGH */
                   1227:                default:
1.229     jcs      1228:                        error("Load key \"%s\": %s", id->filename, ssh_err(r));
1.214     djm      1229:                        quit = 1;
                   1230:                        break;
                   1231:                }
1.230     djm      1232:                if (!quit && private != NULL && id->agent_fd == -1 &&
1.229     jcs      1233:                    !(id->key && id->isprivate))
                   1234:                        maybe_add_key_to_agent(id->filename, private, comment,
                   1235:                            passphrase);
1.214     djm      1236:                if (i > 0) {
1.204     djm      1237:                        explicit_bzero(passphrase, strlen(passphrase));
1.197     djm      1238:                        free(passphrase);
1.16      markus   1239:                }
1.232     mmcc     1240:                free(comment);
1.214     djm      1241:                if (private != NULL || quit)
                   1242:                        break;
1.16      markus   1243:        }
1.51      markus   1244:        return private;
                   1245: }
                   1246:
1.117     markus   1247: /*
                   1248:  * try keys in the following order:
1.227     djm      1249:  *     1. certificates listed in the config file
                   1250:  *     2. other input certificates
                   1251:  *     3. agent keys that are found in the config file
                   1252:  *     4. other agent keys
                   1253:  *     5. keys that are only listed in the config file
1.117     markus   1254:  */
                   1255: static void
                   1256: pubkey_prepare(Authctxt *authctxt)
1.51      markus   1257: {
1.214     djm      1258:        struct identity *id, *id2, *tmp;
                   1259:        struct idlist agent, files, *preferred;
                   1260:        struct sshkey *key;
1.230     djm      1261:        int agent_fd = -1, i, r, found;
1.214     djm      1262:        size_t j;
                   1263:        struct ssh_identitylist *idlist;
1.51      markus   1264:
1.117     markus   1265:        TAILQ_INIT(&agent);     /* keys from the agent */
                   1266:        TAILQ_INIT(&files);     /* keys from the config file */
                   1267:        preferred = &authctxt->keys;
                   1268:        TAILQ_INIT(preferred);  /* preferred order of keys */
                   1269:
1.190     djm      1270:        /* list of keys stored in the filesystem and PKCS#11 */
1.117     markus   1271:        for (i = 0; i < options.num_identity_files; i++) {
                   1272:                key = options.identity_keys[i];
                   1273:                if (key && key->type == KEY_RSA1)
1.180     djm      1274:                        continue;
                   1275:                if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER)
1.117     markus   1276:                        continue;
                   1277:                options.identity_keys[i] = NULL;
1.150     djm      1278:                id = xcalloc(1, sizeof(*id));
1.230     djm      1279:                id->agent_fd = -1;
1.117     markus   1280:                id->key = key;
                   1281:                id->filename = xstrdup(options.identity_files[i]);
1.192     dtucker  1282:                id->userprovided = options.identity_file_userprovided[i];
1.117     markus   1283:                TAILQ_INSERT_TAIL(&files, id, next);
1.190     djm      1284:        }
1.227     djm      1285:        /* list of certificates specified by user */
                   1286:        for (i = 0; i < options.num_certificate_files; i++) {
                   1287:                key = options.certificates[i];
                   1288:                if (!key_is_cert(key) || key->cert == NULL ||
                   1289:                    key->cert->type != SSH2_CERT_TYPE_USER)
                   1290:                        continue;
                   1291:                id = xcalloc(1, sizeof(*id));
1.230     djm      1292:                id->agent_fd = -1;
1.227     djm      1293:                id->key = key;
                   1294:                id->filename = xstrdup(options.certificate_files[i]);
                   1295:                id->userprovided = options.certificate_file_userprovided[i];
                   1296:                TAILQ_INSERT_TAIL(preferred, id, next);
1.117     markus   1297:        }
                   1298:        /* list of keys supported by the agent */
1.214     djm      1299:        if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
                   1300:                if (r != SSH_ERR_AGENT_NOT_PRESENT)
                   1301:                        debug("%s: ssh_get_authentication_socket: %s",
                   1302:                            __func__, ssh_err(r));
                   1303:        } else if ((r = ssh_fetch_identitylist(agent_fd, 2, &idlist)) != 0) {
                   1304:                if (r != SSH_ERR_AGENT_NO_IDENTITIES)
                   1305:                        debug("%s: ssh_fetch_identitylist: %s",
                   1306:                            __func__, ssh_err(r));
1.237     markus   1307:                close(agent_fd);
1.214     djm      1308:        } else {
                   1309:                for (j = 0; j < idlist->nkeys; j++) {
1.117     markus   1310:                        found = 0;
                   1311:                        TAILQ_FOREACH(id, &files, next) {
1.214     djm      1312:                                /*
                   1313:                                 * agent keys from the config file are
                   1314:                                 * preferred
                   1315:                                 */
                   1316:                                if (sshkey_equal(idlist->keys[j], id->key)) {
1.117     markus   1317:                                        TAILQ_REMOVE(&files, id, next);
                   1318:                                        TAILQ_INSERT_TAIL(preferred, id, next);
1.214     djm      1319:                                        id->agent_fd = agent_fd;
1.117     markus   1320:                                        found = 1;
                   1321:                                        break;
                   1322:                                }
                   1323:                        }
1.135     markus   1324:                        if (!found && !options.identities_only) {
1.150     djm      1325:                                id = xcalloc(1, sizeof(*id));
1.214     djm      1326:                                /* XXX "steals" key/comment from idlist */
                   1327:                                id->key = idlist->keys[j];
                   1328:                                id->filename = idlist->comments[j];
                   1329:                                idlist->keys[j] = NULL;
                   1330:                                idlist->comments[j] = NULL;
                   1331:                                id->agent_fd = agent_fd;
1.117     markus   1332:                                TAILQ_INSERT_TAIL(&agent, id, next);
                   1333:                        }
                   1334:                }
1.214     djm      1335:                ssh_free_identitylist(idlist);
1.117     markus   1336:                /* append remaining agent keys */
                   1337:                for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
                   1338:                        TAILQ_REMOVE(&agent, id, next);
                   1339:                        TAILQ_INSERT_TAIL(preferred, id, next);
                   1340:                }
1.214     djm      1341:                authctxt->agent_fd = agent_fd;
1.244     djm      1342:        }
                   1343:        /* Prefer PKCS11 keys that are explicitly listed */
                   1344:        TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
                   1345:                if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0)
                   1346:                        continue;
                   1347:                found = 0;
                   1348:                TAILQ_FOREACH(id2, &files, next) {
                   1349:                        if (id2->key == NULL ||
                   1350:                            (id2->key->flags & SSHKEY_FLAG_EXT) == 0)
                   1351:                                continue;
                   1352:                        if (sshkey_equal(id->key, id2->key)) {
                   1353:                                TAILQ_REMOVE(&files, id, next);
                   1354:                                TAILQ_INSERT_TAIL(preferred, id, next);
                   1355:                                found = 1;
                   1356:                                break;
                   1357:                        }
                   1358:                }
                   1359:                /* If IdentitiesOnly set and key not found then don't use it */
                   1360:                if (!found && options.identities_only) {
                   1361:                        TAILQ_REMOVE(&files, id, next);
                   1362:                        explicit_bzero(id, sizeof(*id));
                   1363:                        free(id);
                   1364:                }
1.117     markus   1365:        }
                   1366:        /* append remaining keys from the config file */
                   1367:        for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
                   1368:                TAILQ_REMOVE(&files, id, next);
                   1369:                TAILQ_INSERT_TAIL(preferred, id, next);
                   1370:        }
1.228     djm      1371:        /* finally, filter by PubkeyAcceptedKeyTypes */
                   1372:        TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
                   1373:                if (id->key != NULL &&
                   1374:                    match_pattern_list(sshkey_ssh_name(id->key),
                   1375:                    options.pubkey_key_types, 0) != 1) {
                   1376:                        debug("Skipping %s key %s - "
                   1377:                            "not in PubkeyAcceptedKeyTypes",
                   1378:                            sshkey_ssh_name(id->key), id->filename);
                   1379:                        TAILQ_REMOVE(preferred, id, next);
                   1380:                        sshkey_free(id->key);
                   1381:                        free(id->filename);
                   1382:                        memset(id, 0, sizeof(*id));
                   1383:                        continue;
                   1384:                }
1.230     djm      1385:                debug2("key: %s (%p)%s%s", id->filename, id->key,
                   1386:                    id->userprovided ? ", explicit" : "",
                   1387:                    id->agent_fd != -1 ? ", agent" : "");
1.117     markus   1388:        }
1.17      markus   1389: }
                   1390:
1.117     markus   1391: static void
                   1392: pubkey_cleanup(Authctxt *authctxt)
1.51      markus   1393: {
1.117     markus   1394:        Identity *id;
1.51      markus   1395:
1.214     djm      1396:        if (authctxt->agent_fd != -1)
                   1397:                ssh_close_authentication_socket(authctxt->agent_fd);
1.117     markus   1398:        for (id = TAILQ_FIRST(&authctxt->keys); id;
                   1399:            id = TAILQ_FIRST(&authctxt->keys)) {
                   1400:                TAILQ_REMOVE(&authctxt->keys, id, next);
1.235     mmcc     1401:                sshkey_free(id->key);
1.197     djm      1402:                free(id->filename);
                   1403:                free(id);
1.117     markus   1404:        }
1.1       markus   1405: }
                   1406:
1.225     markus   1407: static int
                   1408: try_identity(Identity *id)
                   1409: {
                   1410:        if (!id->key)
                   1411:                return (0);
                   1412:        if (key_type_plain(id->key->type) == KEY_RSA &&
                   1413:            (datafellows & SSH_BUG_RSASIGMD5) != 0) {
                   1414:                debug("Skipped %s key %s for RSA/MD5 server",
                   1415:                    key_type(id->key), id->filename);
                   1416:                return (0);
                   1417:        }
                   1418:        return (id->key->type != KEY_RSA1);
                   1419: }
                   1420:
1.20      markus   1421: int
                   1422: userauth_pubkey(Authctxt *authctxt)
                   1423: {
1.117     markus   1424:        Identity *id;
1.20      markus   1425:        int sent = 0;
                   1426:
1.117     markus   1427:        while ((id = TAILQ_FIRST(&authctxt->keys))) {
                   1428:                if (id->tried++)
                   1429:                        return (0);
1.127     markus   1430:                /* move key to the end of the queue */
1.117     markus   1431:                TAILQ_REMOVE(&authctxt->keys, id, next);
                   1432:                TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
                   1433:                /*
                   1434:                 * send a test message if we have the public key. for
                   1435:                 * encrypted keys we cannot do this and have to load the
                   1436:                 * private key instead
                   1437:                 */
1.200     djm      1438:                if (id->key != NULL) {
1.225     markus   1439:                        if (try_identity(id)) {
1.200     djm      1440:                                debug("Offering %s public key: %s",
                   1441:                                    key_type(id->key), id->filename);
                   1442:                                sent = send_pubkey_test(authctxt, id);
                   1443:                        }
                   1444:                } else {
1.117     markus   1445:                        debug("Trying private key: %s", id->filename);
1.229     jcs      1446:                        id->key = load_identity_file(id);
1.117     markus   1447:                        if (id->key != NULL) {
1.225     markus   1448:                                if (try_identity(id)) {
                   1449:                                        id->isprivate = 1;
1.200     djm      1450:                                        sent = sign_and_send_pubkey(
                   1451:                                            authctxt, id);
                   1452:                                }
1.117     markus   1453:                                key_free(id->key);
                   1454:                                id->key = NULL;
1.51      markus   1455:                        }
                   1456:                }
1.117     markus   1457:                if (sent)
                   1458:                        return (sent);
1.28      markus   1459:        }
1.117     markus   1460:        return (0);
1.20      markus   1461: }
                   1462:
1.23      markus   1463: /*
                   1464:  * Send userauth request message specifying keyboard-interactive method.
                   1465:  */
                   1466: int
                   1467: userauth_kbdint(Authctxt *authctxt)
                   1468: {
                   1469:        static int attempt = 0;
                   1470:
                   1471:        if (attempt++ >= options.number_of_password_prompts)
                   1472:                return 0;
1.82      markus   1473:        /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
                   1474:        if (attempt > 1 && !authctxt->info_req_seen) {
                   1475:                debug3("userauth_kbdint: disable: no info_req_seen");
                   1476:                dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
                   1477:                return 0;
                   1478:        }
1.23      markus   1479:
                   1480:        debug2("userauth_kbdint");
                   1481:        packet_start(SSH2_MSG_USERAUTH_REQUEST);
                   1482:        packet_put_cstring(authctxt->server_user);
                   1483:        packet_put_cstring(authctxt->service);
                   1484:        packet_put_cstring(authctxt->method->name);
                   1485:        packet_put_cstring("");                                 /* lang */
                   1486:        packet_put_cstring(options.kbd_interactive_devices ?
                   1487:            options.kbd_interactive_devices : "");
                   1488:        packet_send();
                   1489:
                   1490:        dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
                   1491:        return 1;
                   1492: }
                   1493:
                   1494: /*
1.46      markus   1495:  * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1.23      markus   1496:  */
1.218     markus   1497: int
1.92      markus   1498: input_userauth_info_req(int type, u_int32_t seq, void *ctxt)
1.23      markus   1499: {
                   1500:        Authctxt *authctxt = ctxt;
1.46      markus   1501:        char *name, *inst, *lang, *prompt, *response;
1.32      markus   1502:        u_int num_prompts, i;
1.23      markus   1503:        int echo = 0;
                   1504:
                   1505:        debug2("input_userauth_info_req");
                   1506:
                   1507:        if (authctxt == NULL)
                   1508:                fatal("input_userauth_info_req: no authentication context");
1.82      markus   1509:
                   1510:        authctxt->info_req_seen = 1;
1.23      markus   1511:
                   1512:        name = packet_get_string(NULL);
                   1513:        inst = packet_get_string(NULL);
                   1514:        lang = packet_get_string(NULL);
                   1515:        if (strlen(name) > 0)
1.116     itojun   1516:                logit("%s", name);
1.23      markus   1517:        if (strlen(inst) > 0)
1.116     itojun   1518:                logit("%s", inst);
1.197     djm      1519:        free(name);
                   1520:        free(inst);
                   1521:        free(lang);
1.23      markus   1522:
                   1523:        num_prompts = packet_get_int();
                   1524:        /*
                   1525:         * Begin to build info response packet based on prompts requested.
                   1526:         * We commit to providing the correct number of responses, so if
                   1527:         * further on we run into a problem that prevents this, we have to
                   1528:         * be sure and clean this up and send a correct error response.
                   1529:         */
                   1530:        packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
                   1531:        packet_put_int(num_prompts);
                   1532:
1.73      markus   1533:        debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1.23      markus   1534:        for (i = 0; i < num_prompts; i++) {
                   1535:                prompt = packet_get_string(NULL);
                   1536:                echo = packet_get_char();
                   1537:
1.77      markus   1538:                response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1.23      markus   1539:
1.49      markus   1540:                packet_put_cstring(response);
1.204     djm      1541:                explicit_bzero(response, strlen(response));
1.197     djm      1542:                free(response);
                   1543:                free(prompt);
1.23      markus   1544:        }
1.90      markus   1545:        packet_check_eom(); /* done with parsing incoming message. */
1.23      markus   1546:
1.85      markus   1547:        packet_add_padding(64);
1.23      markus   1548:        packet_send();
1.218     markus   1549:        return 0;
1.68      markus   1550: }
                   1551:
1.100     markus   1552: static int
1.223     djm      1553: ssh_keysign(struct sshkey *key, u_char **sigp, size_t *lenp,
                   1554:     const u_char *data, size_t datalen)
1.100     markus   1555: {
1.223     djm      1556:        struct sshbuf *b;
1.101     markus   1557:        struct stat st;
1.100     markus   1558:        pid_t pid;
1.223     djm      1559:        int i, r, to[2], from[2], status, sock = packet_get_connection_in();
                   1560:        u_char rversion = 0, version = 2;
                   1561:        void (*osigchld)(int);
1.100     markus   1562:
1.223     djm      1563:        *sigp = NULL;
                   1564:        *lenp = 0;
1.100     markus   1565:
1.101     markus   1566:        if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1.223     djm      1567:                error("%s: not installed: %s", __func__, strerror(errno));
                   1568:                return -1;
                   1569:        }
                   1570:        if (fflush(stdout) != 0) {
                   1571:                error("%s: fflush: %s", __func__, strerror(errno));
1.101     markus   1572:                return -1;
                   1573:        }
1.100     markus   1574:        if (pipe(to) < 0) {
1.223     djm      1575:                error("%s: pipe: %s", __func__, strerror(errno));
1.100     markus   1576:                return -1;
                   1577:        }
                   1578:        if (pipe(from) < 0) {
1.223     djm      1579:                error("%s: pipe: %s", __func__, strerror(errno));
1.100     markus   1580:                return -1;
                   1581:        }
                   1582:        if ((pid = fork()) < 0) {
1.223     djm      1583:                error("%s: fork: %s", __func__, strerror(errno));
1.100     markus   1584:                return -1;
                   1585:        }
1.223     djm      1586:        osigchld = signal(SIGCHLD, SIG_DFL);
1.100     markus   1587:        if (pid == 0) {
1.174     dtucker  1588:                /* keep the socket on exec */
1.223     djm      1589:                fcntl(sock, F_SETFD, 0);
1.155     markus   1590:                permanently_drop_suid(getuid());
1.100     markus   1591:                close(from[0]);
                   1592:                if (dup2(from[1], STDOUT_FILENO) < 0)
1.223     djm      1593:                        fatal("%s: dup2: %s", __func__, strerror(errno));
1.100     markus   1594:                close(to[1]);
                   1595:                if (dup2(to[0], STDIN_FILENO) < 0)
1.223     djm      1596:                        fatal("%s: dup2: %s", __func__, strerror(errno));
1.103     markus   1597:                close(from[1]);
                   1598:                close(to[0]);
1.223     djm      1599:                /* Close everything but stdio and the socket */
                   1600:                for (i = STDERR_FILENO + 1; i < sock; i++)
                   1601:                        close(i);
                   1602:                closefrom(sock + 1);
                   1603:                debug3("%s: [child] pid=%ld, exec %s",
                   1604:                    __func__, (long)getpid(), _PATH_SSH_KEY_SIGN);
1.233     mmcc     1605:                execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL);
1.223     djm      1606:                fatal("%s: exec(%s): %s", __func__, _PATH_SSH_KEY_SIGN,
1.100     markus   1607:                    strerror(errno));
                   1608:        }
                   1609:        close(from[1]);
                   1610:        close(to[0]);
                   1611:
1.223     djm      1612:        if ((b = sshbuf_new()) == NULL)
                   1613:                fatal("%s: sshbuf_new failed", __func__);
                   1614:        /* send # of sock, data to be signed */
                   1615:        if ((r = sshbuf_put_u32(b, sock) != 0) ||
                   1616:            (r = sshbuf_put_string(b, data, datalen)) != 0)
                   1617:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                   1618:        if (ssh_msg_send(to[1], version, b) == -1)
                   1619:                fatal("%s: couldn't send request", __func__);
                   1620:        sshbuf_reset(b);
                   1621:        r = ssh_msg_recv(from[0], b);
1.101     markus   1622:        close(from[0]);
                   1623:        close(to[1]);
1.223     djm      1624:        if (r < 0) {
                   1625:                error("%s: no reply", __func__);
                   1626:                goto fail;
                   1627:        }
1.101     markus   1628:
1.223     djm      1629:        errno = 0;
                   1630:        while (waitpid(pid, &status, 0) < 0) {
                   1631:                if (errno != EINTR) {
                   1632:                        error("%s: waitpid %ld: %s",
                   1633:                            __func__, (long)pid, strerror(errno));
                   1634:                        goto fail;
                   1635:                }
                   1636:        }
                   1637:        if (!WIFEXITED(status)) {
                   1638:                error("%s: exited abnormally", __func__);
                   1639:                goto fail;
                   1640:        }
                   1641:        if (WEXITSTATUS(status) != 0) {
                   1642:                error("%s: exited with status %d",
                   1643:                    __func__, WEXITSTATUS(status));
                   1644:                goto fail;
                   1645:        }
                   1646:        if ((r = sshbuf_get_u8(b, &rversion)) != 0) {
                   1647:                error("%s: buffer error: %s", __func__, ssh_err(r));
                   1648:                goto fail;
                   1649:        }
                   1650:        if (rversion != version) {
                   1651:                error("%s: bad version", __func__);
                   1652:                goto fail;
                   1653:        }
                   1654:        if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) {
                   1655:                error("%s: buffer error: %s", __func__, ssh_err(r));
                   1656:  fail:
                   1657:                signal(SIGCHLD, osigchld);
                   1658:                sshbuf_free(b);
1.100     markus   1659:                return -1;
                   1660:        }
1.223     djm      1661:        signal(SIGCHLD, osigchld);
                   1662:        sshbuf_free(b);
1.100     markus   1663:
                   1664:        return 0;
                   1665: }
                   1666:
1.68      markus   1667: int
                   1668: userauth_hostbased(Authctxt *authctxt)
                   1669: {
1.223     djm      1670:        struct ssh *ssh = active_state;
                   1671:        struct sshkey *private = NULL;
                   1672:        struct sshbuf *b = NULL;
1.72      markus   1673:        const char *service;
1.223     djm      1674:        u_char *sig = NULL, *keyblob = NULL;
                   1675:        char *fp = NULL, *chost = NULL, *lname = NULL;
                   1676:        size_t siglen = 0, keylen = 0;
                   1677:        int i, r, success = 0;
                   1678:
                   1679:        if (authctxt->ktypes == NULL) {
                   1680:                authctxt->oktypes = xstrdup(options.hostbased_key_types);
                   1681:                authctxt->ktypes = authctxt->oktypes;
                   1682:        }
1.213     djm      1683:
1.223     djm      1684:        /*
                   1685:         * Work through each listed type pattern in HostbasedKeyTypes,
                   1686:         * trying each hostkey that matches the type in turn.
                   1687:         */
                   1688:        for (;;) {
                   1689:                if (authctxt->active_ktype == NULL)
                   1690:                        authctxt->active_ktype = strsep(&authctxt->ktypes, ",");
                   1691:                if (authctxt->active_ktype == NULL ||
                   1692:                    *authctxt->active_ktype == '\0')
                   1693:                        break;
                   1694:                debug3("%s: trying key type %s", __func__,
                   1695:                    authctxt->active_ktype);
1.68      markus   1696:
1.223     djm      1697:                /* check for a useful key */
                   1698:                private = NULL;
                   1699:                for (i = 0; i < authctxt->sensitive->nkeys; i++) {
                   1700:                        if (authctxt->sensitive->keys[i] == NULL ||
                   1701:                            authctxt->sensitive->keys[i]->type == KEY_RSA1 ||
                   1702:                            authctxt->sensitive->keys[i]->type == KEY_UNSPEC)
                   1703:                                continue;
                   1704:                        if (match_pattern_list(
                   1705:                            sshkey_ssh_name(authctxt->sensitive->keys[i]),
1.224     djm      1706:                            authctxt->active_ktype, 0) != 1)
1.223     djm      1707:                                continue;
1.68      markus   1708:                        /* we take and free the key */
1.223     djm      1709:                        private = authctxt->sensitive->keys[i];
                   1710:                        authctxt->sensitive->keys[i] = NULL;
1.68      markus   1711:                        break;
                   1712:                }
1.223     djm      1713:                /* Found one */
                   1714:                if (private != NULL)
                   1715:                        break;
                   1716:                /* No more keys of this type; advance */
                   1717:                authctxt->active_ktype = NULL;
1.68      markus   1718:        }
1.223     djm      1719:        if (private == NULL) {
                   1720:                free(authctxt->oktypes);
                   1721:                authctxt->oktypes = authctxt->ktypes = NULL;
                   1722:                authctxt->active_ktype = NULL;
1.109     markus   1723:                debug("No more client hostkeys for hostbased authentication.");
1.223     djm      1724:                goto out;
1.68      markus   1725:        }
1.211     djm      1726:
1.223     djm      1727:        if ((fp = sshkey_fingerprint(private, options.fingerprint_hash,
                   1728:            SSH_FP_DEFAULT)) == NULL) {
                   1729:                error("%s: sshkey_fingerprint failed", __func__);
                   1730:                goto out;
1.68      markus   1731:        }
1.223     djm      1732:        debug("%s: trying hostkey %s %s",
                   1733:            __func__, sshkey_ssh_name(private), fp);
1.211     djm      1734:
1.84      markus   1735:        /* figure out a name for the client host */
1.223     djm      1736:        if ((lname = get_local_name(packet_get_connection_in())) == NULL) {
                   1737:                error("%s: cannot get local ipaddr/name", __func__);
                   1738:                goto out;
1.84      markus   1739:        }
1.223     djm      1740:
                   1741:        /* XXX sshbuf_put_stringf? */
                   1742:        xasprintf(&chost, "%s.", lname);
                   1743:        debug2("%s: chost %s", __func__, chost);
1.84      markus   1744:
1.72      markus   1745:        service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
                   1746:            authctxt->service;
1.223     djm      1747:
1.68      markus   1748:        /* construct data */
1.223     djm      1749:        if ((b = sshbuf_new()) == NULL) {
                   1750:                error("%s: sshbuf_new failed", __func__);
                   1751:                goto out;
                   1752:        }
                   1753:        if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) {
                   1754:                error("%s: sshkey_to_blob: %s", __func__, ssh_err(r));
                   1755:                goto out;
                   1756:        }
                   1757:        if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
                   1758:            (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
                   1759:            (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
                   1760:            (r = sshbuf_put_cstring(b, service)) != 0 ||
                   1761:            (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
                   1762:            (r = sshbuf_put_cstring(b, key_ssh_name(private))) != 0 ||
                   1763:            (r = sshbuf_put_string(b, keyblob, keylen)) != 0 ||
                   1764:            (r = sshbuf_put_cstring(b, chost)) != 0 ||
                   1765:            (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) {
                   1766:                error("%s: buffer error: %s", __func__, ssh_err(r));
                   1767:                goto out;
                   1768:        }
                   1769:
1.68      markus   1770: #ifdef DEBUG_PK
1.223     djm      1771:        sshbuf_dump(b, stderr);
1.68      markus   1772: #endif
1.223     djm      1773:        if (authctxt->sensitive->external_keysign)
                   1774:                r = ssh_keysign(private, &sig, &siglen,
                   1775:                    sshbuf_ptr(b), sshbuf_len(b));
                   1776:        else if ((r = sshkey_sign(private, &sig, &siglen,
1.231     markus   1777:            sshbuf_ptr(b), sshbuf_len(b), NULL, datafellows)) != 0)
1.223     djm      1778:                debug("%s: sshkey_sign: %s", __func__, ssh_err(r));
                   1779:        if (r != 0) {
                   1780:                error("sign using hostkey %s %s failed",
                   1781:                    sshkey_ssh_name(private), fp);
                   1782:                goto out;
                   1783:        }
                   1784:        if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
                   1785:            (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
                   1786:            (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
                   1787:            (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
                   1788:            (r = sshpkt_put_cstring(ssh, key_ssh_name(private))) != 0 ||
                   1789:            (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 ||
                   1790:            (r = sshpkt_put_cstring(ssh, chost)) != 0 ||
                   1791:            (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 ||
                   1792:            (r = sshpkt_put_string(ssh, sig, siglen)) != 0 ||
                   1793:            (r = sshpkt_send(ssh)) != 0) {
                   1794:                error("%s: packet error: %s", __func__, ssh_err(r));
                   1795:                goto out;
                   1796:        }
                   1797:        success = 1;
                   1798:
                   1799:  out:
                   1800:        if (sig != NULL) {
                   1801:                explicit_bzero(sig, siglen);
                   1802:                free(sig);
1.68      markus   1803:        }
1.223     djm      1804:        free(keyblob);
                   1805:        free(lname);
                   1806:        free(fp);
1.197     djm      1807:        free(chost);
1.223     djm      1808:        sshkey_free(private);
                   1809:        sshbuf_free(b);
1.68      markus   1810:
1.223     djm      1811:        return success;
1.23      markus   1812: }
1.170     djm      1813:
1.20      markus   1814: /* find auth method */
                   1815:
                   1816: /*
                   1817:  * given auth method name, if configurable options permit this method fill
                   1818:  * in auth_ident field and return true, otherwise return false.
                   1819:  */
1.76      itojun   1820: static int
1.20      markus   1821: authmethod_is_enabled(Authmethod *method)
                   1822: {
                   1823:        if (method == NULL)
                   1824:                return 0;
                   1825:        /* return false if options indicate this method is disabled */
                   1826:        if  (method->enabled == NULL || *method->enabled == 0)
                   1827:                return 0;
                   1828:        /* return false if batch mode is enabled but method needs interactive mode */
                   1829:        if  (method->batch_flag != NULL && *method->batch_flag != 0)
                   1830:                return 0;
                   1831:        return 1;
                   1832: }
                   1833:
1.76      itojun   1834: static Authmethod *
1.20      markus   1835: authmethod_lookup(const char *name)
1.1       markus   1836: {
1.20      markus   1837:        Authmethod *method = NULL;
                   1838:        if (name != NULL)
                   1839:                for (method = authmethods; method->name != NULL; method++)
                   1840:                        if (strcmp(name, method->name) == 0)
                   1841:                                return method;
                   1842:        debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
                   1843:        return NULL;
                   1844: }
1.1       markus   1845:
1.53      markus   1846: /* XXX internal state */
                   1847: static Authmethod *current = NULL;
                   1848: static char *supported = NULL;
                   1849: static char *preferred = NULL;
1.105     deraadt  1850:
1.20      markus   1851: /*
                   1852:  * Given the authentication method list sent by the server, return the
                   1853:  * next method we should try.  If the server initially sends a nil list,
1.67      markus   1854:  * use a built-in default list.
1.41      stevesk  1855:  */
1.76      itojun   1856: static Authmethod *
1.20      markus   1857: authmethod_get(char *authlist)
                   1858: {
1.53      markus   1859:        char *name = NULL;
1.97      markus   1860:        u_int next;
1.41      stevesk  1861:
1.20      markus   1862:        /* Use a suitable default if we're passed a nil list.  */
                   1863:        if (authlist == NULL || strlen(authlist) == 0)
1.53      markus   1864:                authlist = options.preferred_authentications;
1.20      markus   1865:
1.53      markus   1866:        if (supported == NULL || strcmp(authlist, supported) != 0) {
                   1867:                debug3("start over, passed a different list %s", authlist);
1.197     djm      1868:                free(supported);
1.53      markus   1869:                supported = xstrdup(authlist);
                   1870:                preferred = options.preferred_authentications;
                   1871:                debug3("preferred %s", preferred);
                   1872:                current = NULL;
                   1873:        } else if (current != NULL && authmethod_is_enabled(current))
                   1874:                return current;
1.20      markus   1875:
1.53      markus   1876:        for (;;) {
                   1877:                if ((name = match_list(preferred, supported, &next)) == NULL) {
1.109     markus   1878:                        debug("No more authentication methods to try.");
1.53      markus   1879:                        current = NULL;
                   1880:                        return NULL;
                   1881:                }
                   1882:                preferred += next;
1.23      markus   1883:                debug3("authmethod_lookup %s", name);
1.53      markus   1884:                debug3("remaining preferred: %s", preferred);
                   1885:                if ((current = authmethod_lookup(name)) != NULL &&
                   1886:                    authmethod_is_enabled(current)) {
1.23      markus   1887:                        debug3("authmethod_is_enabled %s", name);
1.109     markus   1888:                        debug("Next authentication method: %s", name);
1.197     djm      1889:                        free(name);
1.53      markus   1890:                        return current;
1.23      markus   1891:                }
1.198     dtucker  1892:                free(name);
1.1       markus   1893:        }
1.53      markus   1894: }
1.1       markus   1895:
1.79      stevesk  1896: static char *
1.53      markus   1897: authmethods_get(void)
                   1898: {
                   1899:        Authmethod *method = NULL;
1.93      markus   1900:        Buffer b;
                   1901:        char *list;
1.27      provos   1902:
1.93      markus   1903:        buffer_init(&b);
1.53      markus   1904:        for (method = authmethods; method->name != NULL; method++) {
                   1905:                if (authmethod_is_enabled(method)) {
1.93      markus   1906:                        if (buffer_len(&b) > 0)
                   1907:                                buffer_append(&b, ",", 1);
                   1908:                        buffer_append(&b, method->name, strlen(method->name));
1.53      markus   1909:                }
                   1910:        }
1.242     djm      1911:        if ((list = sshbuf_dup_string(&b)) == NULL)
                   1912:                fatal("%s: sshbuf_dup_string failed", __func__);
1.93      markus   1913:        buffer_free(&b);
                   1914:        return list;
1.1       markus   1915: }
1.170     djm      1916: