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

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