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

Annotation of src/usr.bin/ssh/ssh-agent.c, Revision 1.292.4.1

1.292.4.1! bluhm       1: /* $OpenBSD: ssh-agent.c,v 1.292 2022/09/17 10:11:29 djm Exp $ */
1.1       deraadt     2: /*
1.22      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
                      6:  * The authentication agent program.
1.33      markus      7:  *
1.35      deraadt     8:  * As far as I am concerned, the code I have written for this software
                      9:  * can be used freely for any purpose.  Any derived versions of this
                     10:  * software must be clearly marked as such, and if the derived work is
                     11:  * incompatible with the protocol description in the RFC file, it must be
                     12:  * called by a name other than "ssh" or "Secure Shell".
                     13:  *
1.56      markus     14:  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
1.35      deraadt    15:  *
                     16:  * Redistribution and use in source and binary forms, with or without
                     17:  * modification, are permitted provided that the following conditions
                     18:  * are met:
                     19:  * 1. Redistributions of source code must retain the above copyright
                     20:  *    notice, this list of conditions and the following disclaimer.
                     21:  * 2. Redistributions in binary form must reproduce the above copyright
                     22:  *    notice, this list of conditions and the following disclaimer in the
                     23:  *    documentation and/or other materials provided with the distribution.
                     24:  *
                     25:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     26:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     27:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     28:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     29:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     30:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     31:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     32:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     33:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     34:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.22      deraadt    35:  */
1.1       deraadt    36:
1.151     deraadt    37: #include <sys/types.h>
1.153     djm        38: #include <sys/time.h>
1.78      provos     39: #include <sys/queue.h>
1.127     stevesk    40: #include <sys/resource.h>
1.141     stevesk    41: #include <sys/socket.h>
1.189     djm        42: #include <sys/stat.h>
1.128     stevesk    43: #include <sys/un.h>
1.238     djm        44: #include <sys/wait.h>
1.126     stevesk    45:
1.185     markus     46: #ifdef WITH_OPENSSL
1.146     stevesk    47: #include <openssl/evp.h>
1.185     markus     48: #endif
1.146     stevesk    49:
1.143     stevesk    50: #include <errno.h>
1.142     stevesk    51: #include <fcntl.h>
1.126     stevesk    52: #include <paths.h>
1.223     djm        53: #include <poll.h>
1.129     stevesk    54: #include <signal.h>
1.149     stevesk    55: #include <stdlib.h>
1.150     stevesk    56: #include <stdio.h>
1.146     stevesk    57: #include <string.h>
1.248     naddy      58: #include <stdarg.h>
1.196     deraadt    59: #include <limits.h>
1.145     stevesk    60: #include <time.h>
1.144     stevesk    61: #include <unistd.h>
1.203     dtucker    62: #include <util.h>
1.194     markus     63:
1.151     deraadt    64: #include "xmalloc.h"
1.1       deraadt    65: #include "ssh.h"
1.258     djm        66: #include "ssh2.h"
1.194     markus     67: #include "sshbuf.h"
                     68: #include "sshkey.h"
1.32      markus     69: #include "authfd.h"
1.37      markus     70: #include "compat.h"
1.47      markus     71: #include "log.h"
1.107     markus     72: #include "misc.h"
1.182     markus     73: #include "digest.h"
1.194     markus     74: #include "ssherr.h"
1.215     djm        75: #include "match.h"
1.238     djm        76: #include "msg.h"
1.244     djm        77: #include "ssherr.h"
1.238     djm        78: #include "pathnames.h"
1.163     markus     79: #include "ssh-pkcs11.h"
1.251     djm        80: #include "sk-api.h"
1.281     djm        81: #include "myproposal.h"
1.59      markus     82:
1.262     djm        83: #ifndef DEFAULT_ALLOWED_PROVIDERS
                     84: # define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/local/lib*/*"
1.215     djm        85: #endif
                     86:
1.223     djm        87: /* Maximum accepted message length */
1.280     djm        88: #define AGENT_MAX_LEN          (256*1024)
1.233     djm        89: /* Maximum bytes to read from client socket */
1.280     djm        90: #define AGENT_RBUF_LEN         (4096)
                     91: /* Maximum number of recorded session IDs/hostkeys per connection */
                     92: #define AGENT_MAX_SESSION_IDS          16
                     93: /* Maximum size of session ID */
                     94: #define AGENT_MAX_SID_LEN              128
1.281     djm        95: /* Maximum number of destination constraints to accept on a key */
                     96: #define AGENT_MAX_DEST_CONSTRAINTS     1024
1.280     djm        97:
                     98: /* XXX store hostkey_sid in a refcounted tree */
1.223     djm        99:
1.73      stevesk   100: typedef enum {
1.275     djm       101:        AUTH_UNUSED = 0,
                    102:        AUTH_SOCKET = 1,
                    103:        AUTH_CONNECTION = 2,
1.73      stevesk   104: } sock_type;
                    105:
1.280     djm       106: struct hostkey_sid {
                    107:        struct sshkey *key;
                    108:        struct sshbuf *sid;
                    109:        int forwarded;
                    110: };
                    111:
1.274     djm       112: typedef struct socket_entry {
1.21      markus    113:        int fd;
1.73      stevesk   114:        sock_type type;
1.194     markus    115:        struct sshbuf *input;
                    116:        struct sshbuf *output;
                    117:        struct sshbuf *request;
1.280     djm       118:        size_t nsession_ids;
                    119:        struct hostkey_sid *session_ids;
1.1       deraadt   120: } SocketEntry;
                    121:
1.45      markus    122: u_int sockets_alloc = 0;
1.1       deraadt   123: SocketEntry *sockets = NULL;
                    124:
1.78      provos    125: typedef struct identity {
                    126:        TAILQ_ENTRY(identity) next;
1.194     markus    127:        struct sshkey *key;
1.21      markus    128:        char *comment;
1.163     markus    129:        char *provider;
1.174     dtucker   130:        time_t death;
1.107     markus    131:        u_int confirm;
1.238     djm       132:        char *sk_provider;
1.281     djm       133:        struct dest_constraint *dest_constraints;
                    134:        size_t ndest_constraints;
1.1       deraadt   135: } Identity;
                    136:
1.221     djm       137: struct idtable {
1.33      markus    138:        int nentries;
1.78      provos    139:        TAILQ_HEAD(idqueue, identity) idlist;
1.221     djm       140: };
1.33      markus    141:
1.221     djm       142: /* private key table */
                    143: struct idtable *idtab;
1.1       deraadt   144:
                    145: int max_fd = 0;
                    146:
1.11      markus    147: /* pid of shell == parent of agent */
1.29      deraadt   148: pid_t parent_pid = -1;
1.176     dtucker   149: time_t parent_alive_interval = 0;
1.10      markus    150:
1.187     djm       151: /* pid of process for which cleanup_socket is applicable */
                    152: pid_t cleanup_pid = 0;
                    153:
1.10      markus    154: /* pathname and directory for AUTH_SOCKET */
1.196     deraadt   155: char socket_name[PATH_MAX];
                    156: char socket_dir[PATH_MAX];
1.10      markus    157:
1.260     djm       158: /* Pattern-list of allowed PKCS#11/Security key paths */
                    159: static char *allowed_providers;
1.215     djm       160:
1.292.4.1! bluhm     161: /*
        !           162:  * Allows PKCS11 providers or SK keys that use non-internal providers to
        !           163:  * be added over a remote connection (identified by session-bind@openssh.com).
        !           164:  */
        !           165: static int remote_add_provider;
        !           166:
1.88      markus    167: /* locking */
1.203     dtucker   168: #define LOCK_SIZE      32
                    169: #define LOCK_SALT_SIZE 16
                    170: #define LOCK_ROUNDS    1
1.88      markus    171: int locked = 0;
1.213     djm       172: u_char lock_pwhash[LOCK_SIZE];
                    173: u_char lock_salt[LOCK_SALT_SIZE];
1.88      markus    174:
1.20      markus    175: extern char *__progname;
                    176:
1.174     dtucker   177: /* Default lifetime in seconds (0 == forever) */
1.268     dtucker   178: static int lifetime = 0;
1.106     marc      179:
1.192     djm       180: static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
                    181:
1.258     djm       182: /* Refuse signing of non-SSH messages for web-origin FIDO keys */
                    183: static int restrict_websafe = 1;
                    184:
1.55      itojun    185: static void
1.101     stevesk   186: close_socket(SocketEntry *e)
                    187: {
1.280     djm       188:        size_t i;
                    189:
1.101     stevesk   190:        close(e->fd);
1.194     markus    191:        sshbuf_free(e->input);
                    192:        sshbuf_free(e->output);
                    193:        sshbuf_free(e->request);
1.280     djm       194:        for (i = 0; i < e->nsession_ids; i++) {
                    195:                sshkey_free(e->session_ids[i].key);
                    196:                sshbuf_free(e->session_ids[i].sid);
                    197:        }
                    198:        free(e->session_ids);
1.269     djm       199:        memset(e, '\0', sizeof(*e));
                    200:        e->fd = -1;
                    201:        e->type = AUTH_UNUSED;
1.101     stevesk   202: }
                    203:
                    204: static void
1.33      markus    205: idtab_init(void)
1.1       deraadt   206: {
1.221     djm       207:        idtab = xcalloc(1, sizeof(*idtab));
                    208:        TAILQ_INIT(&idtab->idlist);
                    209:        idtab->nentries = 0;
1.33      markus    210: }
                    211:
1.89      markus    212: static void
1.281     djm       213: free_dest_constraint_hop(struct dest_constraint_hop *dch)
                    214: {
                    215:        u_int i;
                    216:
                    217:        if (dch == NULL)
                    218:                return;
                    219:        free(dch->user);
                    220:        free(dch->hostname);
                    221:        for (i = 0; i < dch->nkeys; i++)
                    222:                sshkey_free(dch->keys[i]);
                    223:        free(dch->keys);
                    224:        free(dch->key_is_ca);
                    225: }
                    226:
                    227: static void
                    228: free_dest_constraints(struct dest_constraint *dcs, size_t ndcs)
                    229: {
                    230:        size_t i;
                    231:
                    232:        for (i = 0; i < ndcs; i++) {
                    233:                free_dest_constraint_hop(&dcs[i].from);
                    234:                free_dest_constraint_hop(&dcs[i].to);
                    235:        }
                    236:        free(dcs);
                    237: }
                    238:
                    239: static void
1.89      markus    240: free_identity(Identity *id)
                    241: {
1.194     markus    242:        sshkey_free(id->key);
1.173     djm       243:        free(id->provider);
                    244:        free(id->comment);
1.238     djm       245:        free(id->sk_provider);
1.281     djm       246:        free_dest_constraints(id->dest_constraints, id->ndest_constraints);
1.173     djm       247:        free(id);
1.89      markus    248: }
                    249:
1.281     djm       250: /*
                    251:  * Match 'key' against the key/CA list in a destination constraint hop
                    252:  * Returns 0 on success or -1 otherwise.
                    253:  */
                    254: static int
                    255: match_key_hop(const char *tag, const struct sshkey *key,
                    256:     const struct dest_constraint_hop *dch)
                    257: {
                    258:        const char *reason = NULL;
1.286     dtucker   259:        const char *hostname = dch->hostname ? dch->hostname : "(ORIGIN)";
1.281     djm       260:        u_int i;
                    261:        char *fp;
                    262:
                    263:        if (key == NULL)
                    264:                return -1;
                    265:        /* XXX logspam */
                    266:        if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
                    267:            SSH_FP_DEFAULT)) == NULL)
                    268:                fatal_f("fingerprint failed");
                    269:        debug3_f("%s: entering hostname %s, requested key %s %s, %u keys avail",
1.286     dtucker   270:            tag, hostname, sshkey_type(key), fp, dch->nkeys);
1.281     djm       271:        free(fp);
                    272:        for (i = 0; i < dch->nkeys; i++) {
                    273:                if (dch->keys[i] == NULL)
                    274:                        return -1;
                    275:                /* XXX logspam */
                    276:                if ((fp = sshkey_fingerprint(dch->keys[i], SSH_FP_HASH_DEFAULT,
                    277:                    SSH_FP_DEFAULT)) == NULL)
                    278:                        fatal_f("fingerprint failed");
                    279:                debug3_f("%s: key %u: %s%s %s", tag, i,
                    280:                    dch->key_is_ca[i] ? "CA " : "",
                    281:                    sshkey_type(dch->keys[i]), fp);
                    282:                free(fp);
                    283:                if (!sshkey_is_cert(key)) {
                    284:                        /* plain key */
                    285:                        if (dch->key_is_ca[i] ||
                    286:                            !sshkey_equal(key, dch->keys[i]))
                    287:                                continue;
                    288:                        return 0;
                    289:                }
                    290:                /* certificate */
                    291:                if (!dch->key_is_ca[i])
                    292:                        continue;
                    293:                if (key->cert == NULL || key->cert->signature_key == NULL)
                    294:                        return -1; /* shouldn't happen */
                    295:                if (!sshkey_equal(key->cert->signature_key, dch->keys[i]))
                    296:                        continue;
1.286     dtucker   297:                if (sshkey_cert_check_host(key, hostname, 1,
1.281     djm       298:                    SSH_ALLOWED_CA_SIGALGS, &reason) != 0) {
                    299:                        debug_f("cert %s / hostname %s rejected: %s",
1.286     dtucker   300:                            key->cert->key_id, hostname, reason);
1.281     djm       301:                        continue;
                    302:                }
                    303:                return 0;
                    304:        }
                    305:        return -1;
                    306: }
                    307:
                    308: /* Check destination constraints on an identity against the hostkey/user */
                    309: static int
                    310: permitted_by_dest_constraints(const struct sshkey *fromkey,
                    311:     const struct sshkey *tokey, Identity *id, const char *user,
                    312:     const char **hostnamep)
                    313: {
                    314:        size_t i;
                    315:        struct dest_constraint *d;
                    316:
                    317:        if (hostnamep != NULL)
                    318:                *hostnamep = NULL;
                    319:        for (i = 0; i < id->ndest_constraints; i++) {
                    320:                d = id->dest_constraints + i;
                    321:                /* XXX remove logspam */
                    322:                debug2_f("constraint %zu %s%s%s (%u keys) > %s%s%s (%u keys)",
                    323:                    i, d->from.user ? d->from.user : "",
                    324:                    d->from.user ? "@" : "",
                    325:                    d->from.hostname ? d->from.hostname : "(ORIGIN)",
                    326:                    d->from.nkeys,
                    327:                    d->to.user ? d->to.user : "", d->to.user ? "@" : "",
                    328:                    d->to.hostname ? d->to.hostname : "(ANY)", d->to.nkeys);
                    329:
                    330:                /* Match 'from' key */
                    331:                if (fromkey == NULL) {
                    332:                        /* We are matching the first hop */
                    333:                        if (d->from.hostname != NULL || d->from.nkeys != 0)
                    334:                                continue;
                    335:                } else if (match_key_hop("from", fromkey, &d->from) != 0)
                    336:                        continue;
                    337:
                    338:                /* Match 'to' key */
                    339:                if (tokey != NULL && match_key_hop("to", tokey, &d->to) != 0)
                    340:                        continue;
                    341:
                    342:                /* Match user if specified */
                    343:                if (d->to.user != NULL && user != NULL &&
                    344:                    !match_pattern(user, d->to.user))
                    345:                        continue;
                    346:
                    347:                /* successfully matched this constraint */
                    348:                if (hostnamep != NULL)
                    349:                        *hostnamep = d->to.hostname;
                    350:                debug2_f("allowed for hostname %s",
                    351:                    d->to.hostname == NULL ? "*" : d->to.hostname);
                    352:                return 0;
                    353:        }
                    354:        /* no match */
                    355:        debug2_f("%s identity \"%s\" not permitted for this destination",
                    356:            sshkey_type(id->key), id->comment);
                    357:        return -1;
                    358: }
                    359:
                    360: /*
                    361:  * Check whether hostkeys on a SocketEntry and the optionally specified user
                    362:  * are permitted by the destination constraints on the Identity.
                    363:  * Returns 0 on success or -1 otherwise.
                    364:  */
                    365: static int
                    366: identity_permitted(Identity *id, SocketEntry *e, char *user,
                    367:     const char **forward_hostnamep, const char **last_hostnamep)
                    368: {
                    369:        size_t i;
                    370:        const char **hp;
                    371:        struct hostkey_sid *hks;
                    372:        const struct sshkey *fromkey = NULL;
                    373:        const char *test_user;
                    374:        char *fp1, *fp2;
                    375:
                    376:        /* XXX remove logspam */
                    377:        debug3_f("entering: key %s comment \"%s\", %zu socket bindings, "
                    378:            "%zu constraints", sshkey_type(id->key), id->comment,
                    379:            e->nsession_ids, id->ndest_constraints);
                    380:        if (id->ndest_constraints == 0)
                    381:                return 0; /* unconstrained */
                    382:        if (e->nsession_ids == 0)
                    383:                return 0; /* local use */
                    384:        /*
                    385:         * Walk through the hops recorded by session_id and try to find a
                    386:         * constraint that satisfies each.
                    387:         */
                    388:        for (i = 0; i < e->nsession_ids; i++) {
                    389:                hks = e->session_ids + i;
                    390:                if (hks->key == NULL)
                    391:                        fatal_f("internal error: no bound key");
                    392:                /* XXX remove logspam */
                    393:                fp1 = fp2 = NULL;
                    394:                if (fromkey != NULL &&
                    395:                    (fp1 = sshkey_fingerprint(fromkey, SSH_FP_HASH_DEFAULT,
                    396:                    SSH_FP_DEFAULT)) == NULL)
                    397:                        fatal_f("fingerprint failed");
                    398:                if ((fp2 = sshkey_fingerprint(hks->key, SSH_FP_HASH_DEFAULT,
                    399:                    SSH_FP_DEFAULT)) == NULL)
                    400:                        fatal_f("fingerprint failed");
                    401:                debug3_f("socketentry fd=%d, entry %zu %s, "
                    402:                    "from hostkey %s %s to user %s hostkey %s %s",
                    403:                    e->fd, i, hks->forwarded ? "FORWARD" : "AUTH",
                    404:                    fromkey ? sshkey_type(fromkey) : "(ORIGIN)",
                    405:                    fromkey ? fp1 : "", user ? user : "(ANY)",
                    406:                    sshkey_type(hks->key), fp2);
                    407:                free(fp1);
                    408:                free(fp2);
                    409:                /*
                    410:                 * Record the hostnames for the initial forwarding and
                    411:                 * the final destination.
                    412:                 */
                    413:                hp = NULL;
                    414:                if (i == e->nsession_ids - 1)
                    415:                        hp = last_hostnamep;
                    416:                else if (i == 0)
                    417:                        hp = forward_hostnamep;
                    418:                /* Special handling for final recorded binding */
                    419:                test_user = NULL;
                    420:                if (i == e->nsession_ids - 1) {
                    421:                        /* Can only check user at final hop */
                    422:                        test_user = user;
                    423:                        /*
                    424:                         * user is only presented for signature requests.
                    425:                         * If this is the case, make sure last binding is not
                    426:                         * for a forwarding.
                    427:                         */
                    428:                        if (hks->forwarded && user != NULL) {
                    429:                                error_f("tried to sign on forwarding hop");
                    430:                                return -1;
                    431:                        }
                    432:                } else if (!hks->forwarded) {
                    433:                        error_f("tried to forward though signing bind");
                    434:                        return -1;
                    435:                }
                    436:                if (permitted_by_dest_constraints(fromkey, hks->key, id,
                    437:                    test_user, hp) != 0)
                    438:                        return -1;
                    439:                fromkey = hks->key;
                    440:        }
                    441:        /*
                    442:         * Another special case: if the last bound session ID was for a
                    443:         * forwarding, and this function is not being called to check a sign
                    444:         * request (i.e. no 'user' supplied), then only permit the key if
                    445:         * there is a permission that would allow it to be used at another
                    446:         * destination. This hides keys that are allowed to be used to
1.284     jsg       447:         * authenticate *to* a host but not permitted for *use* beyond it.
1.281     djm       448:         */
                    449:        hks = &e->session_ids[e->nsession_ids - 1];
                    450:        if (hks->forwarded && user == NULL &&
                    451:            permitted_by_dest_constraints(hks->key, NULL, id,
                    452:            NULL, NULL) != 0) {
                    453:                debug3_f("key permitted at host but not after");
                    454:                return -1;
                    455:        }
                    456:
                    457:        /* success */
                    458:        return 0;
                    459: }
                    460:
1.33      markus    461: /* return matching private key for given public key */
1.78      provos    462: static Identity *
1.221     djm       463: lookup_identity(struct sshkey *key)
1.33      markus    464: {
1.78      provos    465:        Identity *id;
                    466:
1.221     djm       467:        TAILQ_FOREACH(id, &idtab->idlist, next) {
1.194     markus    468:                if (sshkey_equal(key, id->key))
1.78      provos    469:                        return (id);
1.33      markus    470:        }
1.78      provos    471:        return (NULL);
                    472: }
                    473:
1.107     markus    474: /* Check confirmation of keysign request */
                    475: static int
1.270     djm       476: confirm_key(Identity *id, const char *extra)
1.107     markus    477: {
1.122     djm       478:        char *p;
1.107     markus    479:        int ret = -1;
                    480:
1.194     markus    481:        p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
1.197     djm       482:        if (p != NULL &&
1.270     djm       483:            ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
                    484:            id->comment, p,
                    485:            extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
1.122     djm       486:                ret = 0;
1.173     djm       487:        free(p);
1.122     djm       488:
1.107     markus    489:        return (ret);
                    490: }
                    491:
1.194     markus    492: static void
                    493: send_status(SocketEntry *e, int success)
                    494: {
                    495:        int r;
                    496:
                    497:        if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
                    498:            (r = sshbuf_put_u8(e->output, success ?
                    499:            SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
1.266     djm       500:                fatal_fr(r, "compose");
1.194     markus    501: }
                    502:
1.33      markus    503: /* send list of supported public keys to 'client' */
1.55      itojun    504: static void
1.221     djm       505: process_request_identities(SocketEntry *e)
1.33      markus    506: {
1.96      deraadt   507:        Identity *id;
1.281     djm       508:        struct sshbuf *msg, *keys;
1.194     markus    509:        int r;
1.281     djm       510:        u_int nentries = 0;
1.1       deraadt   511:
1.269     djm       512:        debug2_f("entering");
                    513:
1.281     djm       514:        if ((msg = sshbuf_new()) == NULL || (keys = sshbuf_new()) == NULL)
1.266     djm       515:                fatal_f("sshbuf_new failed");
1.221     djm       516:        TAILQ_FOREACH(id, &idtab->idlist, next) {
1.281     djm       517:                /* identity not visible, don't include in response */
                    518:                if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
                    519:                        continue;
                    520:                if ((r = sshkey_puts_opts(id->key, keys,
1.278     djm       521:                    SSHKEY_SERIALIZE_INFO)) != 0 ||
1.281     djm       522:                    (r = sshbuf_put_cstring(keys, id->comment)) != 0) {
1.266     djm       523:                        error_fr(r, "compose key/comment");
1.220     djm       524:                        continue;
1.33      markus    525:                }
1.281     djm       526:                nentries++;
1.21      markus    527:        }
1.281     djm       528:        debug2_f("replying with %u allowed of %u available keys",
                    529:            nentries, idtab->nentries);
                    530:        if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
                    531:            (r = sshbuf_put_u32(msg, nentries)) != 0 ||
                    532:            (r = sshbuf_putb(msg, keys)) != 0)
                    533:                fatal_fr(r, "compose");
1.194     markus    534:        if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
1.266     djm       535:                fatal_fr(r, "enqueue");
1.194     markus    536:        sshbuf_free(msg);
1.281     djm       537:        sshbuf_free(keys);
1.1       deraadt   538: }
                    539:
1.33      markus    540:
1.208     markus    541: static char *
                    542: agent_decode_alg(struct sshkey *key, u_int flags)
                    543: {
                    544:        if (key->type == KEY_RSA) {
                    545:                if (flags & SSH_AGENT_RSA_SHA2_256)
                    546:                        return "rsa-sha2-256";
                    547:                else if (flags & SSH_AGENT_RSA_SHA2_512)
                    548:                        return "rsa-sha2-512";
1.235     djm       549:        } else if (key->type == KEY_RSA_CERT) {
                    550:                if (flags & SSH_AGENT_RSA_SHA2_256)
                    551:                        return "rsa-sha2-256-cert-v01@openssh.com";
                    552:                else if (flags & SSH_AGENT_RSA_SHA2_512)
                    553:                        return "rsa-sha2-512-cert-v01@openssh.com";
1.208     markus    554:        }
                    555:        return NULL;
                    556: }
                    557:
1.258     djm       558: /*
1.270     djm       559:  * Attempt to parse the contents of a buffer as a SSH publickey userauth
                    560:  * request, checking its contents for consistency and matching the embedded
                    561:  * key against the one that is being used for signing.
                    562:  * Note: does not modify msg buffer.
1.282     djm       563:  * Optionally extract the username, session ID and/or hostkey from the request.
1.258     djm       564:  */
                    565: static int
1.270     djm       566: parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
1.282     djm       567:     char **userp, struct sshbuf **sess_idp, struct sshkey **hostkeyp)
1.258     djm       568: {
1.270     djm       569:        struct sshbuf *b = NULL, *sess_id = NULL;
                    570:        char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
1.258     djm       571:        int r;
1.270     djm       572:        u_char t, sig_follows;
1.282     djm       573:        struct sshkey *mkey = NULL, *hostkey = NULL;
1.258     djm       574:
1.270     djm       575:        if (userp != NULL)
                    576:                *userp = NULL;
                    577:        if (sess_idp != NULL)
                    578:                *sess_idp = NULL;
1.282     djm       579:        if (hostkeyp != NULL)
                    580:                *hostkeyp = NULL;
1.270     djm       581:        if ((b = sshbuf_fromb(msg)) == NULL)
                    582:                fatal_f("sshbuf_fromb");
1.258     djm       583:
                    584:        /* SSH userauth request */
1.270     djm       585:        if ((r = sshbuf_froms(b, &sess_id)) != 0)
                    586:                goto out;
                    587:        if (sshbuf_len(sess_id) == 0) {
                    588:                r = SSH_ERR_INVALID_FORMAT;
                    589:                goto out;
                    590:        }
                    591:        if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
                    592:            (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
                    593:            (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
                    594:            (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
                    595:            (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
                    596:            (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
                    597:            (r = sshkey_froms(b, &mkey)) != 0) /* key */
                    598:                goto out;
                    599:        if (t != SSH2_MSG_USERAUTH_REQUEST ||
                    600:            sig_follows != 1 ||
                    601:            strcmp(service, "ssh-connection") != 0 ||
                    602:            !sshkey_equal(expected_key, mkey) ||
                    603:            sshkey_type_from_name(pkalg) != expected_key->type) {
                    604:                r = SSH_ERR_INVALID_FORMAT;
                    605:                goto out;
                    606:        }
1.282     djm       607:        if (strcmp(method, "publickey-hostbound-v00@openssh.com") == 0) {
                    608:                if ((r = sshkey_froms(b, &hostkey)) != 0)
                    609:                        goto out;
                    610:        } else if (strcmp(method, "publickey") != 0) {
1.270     djm       611:                r = SSH_ERR_INVALID_FORMAT;
                    612:                goto out;
                    613:        }
                    614:        if (sshbuf_len(b) != 0) {
                    615:                r = SSH_ERR_INVALID_FORMAT;
                    616:                goto out;
                    617:        }
                    618:        /* success */
                    619:        r = 0;
                    620:        debug3_f("well formed userauth");
                    621:        if (userp != NULL) {
                    622:                *userp = user;
                    623:                user = NULL;
                    624:        }
                    625:        if (sess_idp != NULL) {
                    626:                *sess_idp = sess_id;
                    627:                sess_id = NULL;
1.258     djm       628:        }
1.282     djm       629:        if (hostkeyp != NULL) {
                    630:                *hostkeyp = hostkey;
                    631:                hostkey = NULL;
                    632:        }
1.270     djm       633:  out:
                    634:        sshbuf_free(b);
                    635:        sshbuf_free(sess_id);
                    636:        free(user);
                    637:        free(service);
                    638:        free(method);
                    639:        free(pkalg);
1.258     djm       640:        sshkey_free(mkey);
1.282     djm       641:        sshkey_free(hostkey);
1.270     djm       642:        return r;
                    643: }
                    644:
                    645: /*
                    646:  * Attempt to parse the contents of a buffer as a SSHSIG signature request.
                    647:  * Note: does not modify buffer.
                    648:  */
                    649: static int
                    650: parse_sshsig_request(struct sshbuf *msg)
                    651: {
                    652:        int r;
                    653:        struct sshbuf *b;
                    654:
                    655:        if ((b = sshbuf_fromb(msg)) == NULL)
                    656:                fatal_f("sshbuf_fromb");
                    657:
                    658:        if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
                    659:            (r = sshbuf_consume(b, 6)) != 0 ||
                    660:            (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
                    661:            (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
                    662:            (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
                    663:            (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
                    664:                goto out;
                    665:        if (sshbuf_len(b) != 0) {
                    666:                r = SSH_ERR_INVALID_FORMAT;
                    667:                goto out;
                    668:        }
                    669:        /* success */
                    670:        r = 0;
                    671:  out:
1.258     djm       672:        sshbuf_free(b);
1.270     djm       673:        return r;
                    674: }
                    675:
                    676: /*
                    677:  * This function inspects a message to be signed by a FIDO key that has a
                    678:  * web-like application string (i.e. one that does not begin with "ssh:".
                    679:  * It checks that the message is one of those expected for SSH operations
                    680:  * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
                    681:  * for the web.
                    682:  */
                    683: static int
                    684: check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
                    685: {
1.282     djm       686:        if (parse_userauth_request(data, key, NULL, NULL, NULL) == 0) {
1.270     djm       687:                debug_f("signed data matches public key userauth request");
1.258     djm       688:                return 1;
                    689:        }
1.270     djm       690:        if (parse_sshsig_request(data) == 0) {
                    691:                debug_f("signed data matches SSHSIG signature request");
1.258     djm       692:                return 1;
1.270     djm       693:        }
1.258     djm       694:
1.270     djm       695:        /* XXX check CA signature operation */
1.258     djm       696:
                    697:        error("web-origin key attempting to sign non-SSH message");
                    698:        return 0;
                    699: }
                    700:
1.280     djm       701: static int
                    702: buf_equal(const struct sshbuf *a, const struct sshbuf *b)
                    703: {
                    704:        if (sshbuf_ptr(a) == NULL || sshbuf_ptr(b) == NULL)
                    705:                return SSH_ERR_INVALID_ARGUMENT;
                    706:        if (sshbuf_len(a) != sshbuf_len(b))
                    707:                return SSH_ERR_INVALID_FORMAT;
                    708:        if (timingsafe_bcmp(sshbuf_ptr(a), sshbuf_ptr(b), sshbuf_len(a)) != 0)
                    709:                return SSH_ERR_INVALID_FORMAT;
                    710:        return 0;
                    711: }
                    712:
1.33      markus    713: /* ssh2 only */
1.55      itojun    714: static void
1.33      markus    715: process_sign_request2(SocketEntry *e)
                    716: {
1.221     djm       717:        u_char *signature = NULL;
1.281     djm       718:        size_t slen = 0;
1.194     markus    719:        u_int compat = 0, flags;
1.287     djm       720:        int r, ok = -1, retried = 0;
                    721:        char *fp = NULL, *pin = NULL, *prompt = NULL;
                    722:        char *user = NULL, *sig_dest = NULL;
1.281     djm       723:        const char *fwd_host = NULL, *dest_host = NULL;
1.280     djm       724:        struct sshbuf *msg = NULL, *data = NULL, *sid = NULL;
1.283     djm       725:        struct sshkey *key = NULL, *hostkey = NULL;
1.195     djm       726:        struct identity *id;
1.251     djm       727:        struct notifier_ctx *notifier = NULL;
1.194     markus    728:
1.270     djm       729:        debug_f("entering");
                    730:
1.273     dtucker   731:        if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
1.266     djm       732:                fatal_f("sshbuf_new failed");
1.221     djm       733:        if ((r = sshkey_froms(e->request, &key)) != 0 ||
1.270     djm       734:            (r = sshbuf_get_stringb(e->request, data)) != 0 ||
1.225     djm       735:            (r = sshbuf_get_u32(e->request, &flags)) != 0) {
1.266     djm       736:                error_fr(r, "parse");
1.225     djm       737:                goto send;
                    738:        }
                    739:
1.221     djm       740:        if ((id = lookup_identity(key)) == NULL) {
1.266     djm       741:                verbose_f("%s key not found", sshkey_type(key));
1.195     djm       742:                goto send;
                    743:        }
1.281     djm       744:        if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
                    745:            SSH_FP_DEFAULT)) == NULL)
                    746:                fatal_f("fingerprint failed");
                    747:
                    748:        if (id->ndest_constraints != 0) {
                    749:                if (e->nsession_ids == 0) {
                    750:                        logit_f("refusing use of destination-constrained key "
                    751:                            "to sign on unbound connection");
                    752:                        goto send;
                    753:                }
1.283     djm       754:                if (parse_userauth_request(data, key, &user, &sid,
                    755:                    &hostkey) != 0) {
1.281     djm       756:                        logit_f("refusing use of destination-constrained key "
                    757:                           "to sign an unidentified signature");
                    758:                        goto send;
                    759:                }
                    760:                /* XXX logspam */
                    761:                debug_f("user=%s", user);
                    762:                if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0)
                    763:                        goto send;
                    764:                /* XXX display fwd_host/dest_host in askpass UI */
1.280     djm       765:                /*
1.281     djm       766:                 * Ensure that the session ID is the most recent one
                    767:                 * registered on the socket - it should have been bound by
                    768:                 * ssh immediately before userauth.
1.280     djm       769:                 */
1.281     djm       770:                if (buf_equal(sid,
                    771:                    e->session_ids[e->nsession_ids - 1].sid) != 0) {
                    772:                        error_f("unexpected session ID (%zu listed) on "
                    773:                            "signature request for target user %s with "
                    774:                            "key %s %s", e->nsession_ids, user,
                    775:                            sshkey_type(id->key), fp);
                    776:                        goto send;
1.280     djm       777:                }
1.283     djm       778:                /*
                    779:                 * Ensure that the hostkey embedded in the signature matches
                    780:                 * the one most recently bound to the socket. An exception is
                    781:                 * made for the initial forwarding hop.
                    782:                 */
                    783:                if (e->nsession_ids > 1 && hostkey == NULL) {
                    784:                        error_f("refusing use of destination-constrained key: "
                    785:                            "no hostkey recorded in signature for forwarded "
                    786:                            "connection");
                    787:                        goto send;
                    788:                }
                    789:                if (hostkey != NULL && !sshkey_equal(hostkey,
                    790:                    e->session_ids[e->nsession_ids - 1].key)) {
                    791:                        error_f("refusing use of destination-constrained key: "
                    792:                            "mismatch between hostkey in request and most "
                    793:                            "recently bound session");
                    794:                        goto send;
                    795:                }
1.281     djm       796:                xasprintf(&sig_dest, "public key authentication request for "
                    797:                    "user \"%s\" to listed host", user);
1.280     djm       798:        }
                    799:        if (id->confirm && confirm_key(id, sig_dest) != 0) {
1.266     djm       800:                verbose_f("user refused key");
1.195     djm       801:                goto send;
                    802:        }
1.258     djm       803:        if (sshkey_is_sk(id->key)) {
1.292     djm       804:                if (restrict_websafe &&
                    805:                    strncmp(id->key->sk_application, "ssh:", 4) != 0 &&
1.270     djm       806:                    !check_websafe_message_contents(key, data)) {
1.258     djm       807:                        /* error already logged */
                    808:                        goto send;
                    809:                }
1.290     djm       810:                if (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
1.258     djm       811:                        notifier = notify_start(0,
1.280     djm       812:                            "Confirm user presence for key %s %s%s%s",
                    813:                            sshkey_type(id->key), fp,
                    814:                            sig_dest == NULL ? "" : "\n",
                    815:                            sig_dest == NULL ? "" : sig_dest);
1.258     djm       816:                }
1.251     djm       817:        }
1.287     djm       818:  retry_pin:
1.251     djm       819:        if ((r = sshkey_sign(id->key, &signature, &slen,
1.270     djm       820:            sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
1.287     djm       821:            id->sk_provider, pin, compat)) != 0) {
                    822:                debug_fr(r, "sshkey_sign");
                    823:                if (pin == NULL && !retried && sshkey_is_sk(id->key) &&
                    824:                    r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1.289     djm       825:                        notify_complete(notifier, NULL);
                    826:                        notifier = NULL;
1.287     djm       827:                        /* XXX include sig_dest */
                    828:                        xasprintf(&prompt, "Enter PIN%sfor %s key %s: ",
                    829:                            (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ?
                    830:                            " and confirm user presence " : " ",
                    831:                            sshkey_type(id->key), fp);
                    832:                        pin = read_passphrase(prompt, RP_USE_ASKPASS);
                    833:                        retried = 1;
                    834:                        goto retry_pin;
                    835:                }
1.266     djm       836:                error_fr(r, "sshkey_sign");
1.251     djm       837:                goto send;
1.33      markus    838:        }
1.195     djm       839:        /* Success */
                    840:        ok = 0;
                    841:  send:
1.291     djm       842:        debug_f("good signature");
1.267     djm       843:        notify_complete(notifier, "User presence confirmed");
1.270     djm       844:
1.33      markus    845:        if (ok == 0) {
1.194     markus    846:                if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
                    847:                    (r = sshbuf_put_string(msg, signature, slen)) != 0)
1.266     djm       848:                        fatal_fr(r, "compose");
1.194     markus    849:        } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
1.266     djm       850:                fatal_fr(r, "compose failure");
1.194     markus    851:
                    852:        if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
1.266     djm       853:                fatal_fr(r, "enqueue");
1.194     markus    854:
1.280     djm       855:        sshbuf_free(sid);
1.270     djm       856:        sshbuf_free(data);
1.194     markus    857:        sshbuf_free(msg);
1.270     djm       858:        sshkey_free(key);
1.283     djm       859:        sshkey_free(hostkey);
1.270     djm       860:        free(fp);
1.173     djm       861:        free(signature);
1.280     djm       862:        free(sig_dest);
                    863:        free(user);
1.287     djm       864:        free(prompt);
                    865:        if (pin != NULL)
                    866:                freezero(pin, strlen(pin));
1.1       deraadt   867: }
                    868:
1.33      markus    869: /* shared */
1.55      itojun    870: static void
1.221     djm       871: process_remove_identity(SocketEntry *e)
1.1       deraadt   872: {
1.194     markus    873:        int r, success = 0;
                    874:        struct sshkey *key = NULL;
1.221     djm       875:        Identity *id;
1.21      markus    876:
1.269     djm       877:        debug2_f("entering");
1.221     djm       878:        if ((r = sshkey_froms(e->request, &key)) != 0) {
1.266     djm       879:                error_fr(r, "parse key");
1.221     djm       880:                goto done;
                    881:        }
                    882:        if ((id = lookup_identity(key)) == NULL) {
1.266     djm       883:                debug_f("key not found");
1.221     djm       884:                goto done;
                    885:        }
1.281     djm       886:        /* identity not visible, cannot be removed */
                    887:        if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
                    888:                goto done; /* error already logged */
1.221     djm       889:        /* We have this key, free it. */
                    890:        if (idtab->nentries < 1)
1.266     djm       891:                fatal_f("internal error: nentries %d", idtab->nentries);
1.221     djm       892:        TAILQ_REMOVE(&idtab->idlist, id, next);
                    893:        free_identity(id);
                    894:        idtab->nentries--;
                    895:        success = 1;
                    896:  done:
1.276     djm       897:        sshkey_free(key);
1.194     markus    898:        send_status(e, success);
1.1       deraadt   899: }
                    900:
1.55      itojun    901: static void
1.221     djm       902: process_remove_all_identities(SocketEntry *e)
1.1       deraadt   903: {
1.78      provos    904:        Identity *id;
1.21      markus    905:
1.269     djm       906:        debug2_f("entering");
1.21      markus    907:        /* Loop over all identities and clear the keys. */
1.221     djm       908:        for (id = TAILQ_FIRST(&idtab->idlist); id;
                    909:            id = TAILQ_FIRST(&idtab->idlist)) {
                    910:                TAILQ_REMOVE(&idtab->idlist, id, next);
1.78      provos    911:                free_identity(id);
1.21      markus    912:        }
                    913:
                    914:        /* Mark that there are no identities. */
1.221     djm       915:        idtab->nentries = 0;
1.21      markus    916:
                    917:        /* Send success. */
1.194     markus    918:        send_status(e, 1);
1.1       deraadt   919: }
                    920:
1.155     dtucker   921: /* removes expired keys and returns number of seconds until the next expiry */
1.174     dtucker   922: static time_t
1.89      markus    923: reaper(void)
                    924: {
1.175     dtucker   925:        time_t deadline = 0, now = monotime();
1.89      markus    926:        Identity *id, *nxt;
                    927:
1.221     djm       928:        for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
                    929:                nxt = TAILQ_NEXT(id, next);
                    930:                if (id->death == 0)
                    931:                        continue;
                    932:                if (now >= id->death) {
                    933:                        debug("expiring key '%s'", id->comment);
                    934:                        TAILQ_REMOVE(&idtab->idlist, id, next);
                    935:                        free_identity(id);
                    936:                        idtab->nentries--;
                    937:                } else
                    938:                        deadline = (deadline == 0) ? id->death :
                    939:                            MINIMUM(deadline, id->death);
1.89      markus    940:        }
1.155     dtucker   941:        if (deadline == 0 || deadline <= now)
                    942:                return 0;
                    943:        else
                    944:                return (deadline - now);
1.89      markus    945: }
                    946:
1.271     djm       947: static int
1.281     djm       948: parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch)
                    949: {
                    950:        u_char key_is_ca;
                    951:        size_t elen = 0;
                    952:        int r;
                    953:        struct sshkey *k = NULL;
                    954:        char *fp;
                    955:
                    956:        memset(dch, '\0', sizeof(*dch));
                    957:        if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 ||
                    958:            (r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 ||
                    959:            (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
                    960:                error_fr(r, "parse");
                    961:                goto out;
                    962:        }
                    963:        if (elen != 0) {
                    964:                error_f("unsupported extensions (len %zu)", elen);
                    965:                r = SSH_ERR_FEATURE_UNSUPPORTED;
                    966:                goto out;
                    967:        }
                    968:        if (*dch->hostname == '\0') {
                    969:                free(dch->hostname);
                    970:                dch->hostname = NULL;
                    971:        }
                    972:        if (*dch->user == '\0') {
                    973:                free(dch->user);
                    974:                dch->user = NULL;
                    975:        }
                    976:        while (sshbuf_len(b) != 0) {
                    977:                dch->keys = xrecallocarray(dch->keys, dch->nkeys,
                    978:                    dch->nkeys + 1, sizeof(*dch->keys));
                    979:                dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
                    980:                    dch->nkeys + 1, sizeof(*dch->key_is_ca));
                    981:                if ((r = sshkey_froms(b, &k)) != 0 ||
                    982:                    (r = sshbuf_get_u8(b, &key_is_ca)) != 0)
                    983:                        goto out;
                    984:                if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
                    985:                    SSH_FP_DEFAULT)) == NULL)
                    986:                        fatal_f("fingerprint failed");
                    987:                debug3_f("%s%s%s: adding %skey %s %s",
                    988:                    dch->user == NULL ? "" : dch->user,
                    989:                    dch->user == NULL ? "" : "@",
                    990:                    dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp);
                    991:                free(fp);
                    992:                dch->keys[dch->nkeys] = k;
                    993:                dch->key_is_ca[dch->nkeys] = key_is_ca != 0;
                    994:                dch->nkeys++;
                    995:                k = NULL; /* transferred */
                    996:        }
                    997:        /* success */
                    998:        r = 0;
                    999:  out:
                   1000:        sshkey_free(k);
                   1001:        return r;
                   1002: }
                   1003:
                   1004: static int
                   1005: parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc)
                   1006: {
                   1007:        struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL;
                   1008:        int r;
                   1009:        size_t elen = 0;
                   1010:
                   1011:        debug3_f("entering");
                   1012:
                   1013:        memset(dc, '\0', sizeof(*dc));
                   1014:        if ((r = sshbuf_froms(m, &b)) != 0 ||
                   1015:            (r = sshbuf_froms(b, &frombuf)) != 0 ||
                   1016:            (r = sshbuf_froms(b, &tobuf)) != 0 ||
                   1017:            (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
                   1018:                error_fr(r, "parse");
                   1019:                goto out;
                   1020:        }
                   1021:        if ((r = parse_dest_constraint_hop(frombuf, &dc->from) != 0) ||
                   1022:            (r = parse_dest_constraint_hop(tobuf, &dc->to) != 0))
                   1023:                goto out; /* already logged */
                   1024:        if (elen != 0) {
                   1025:                error_f("unsupported extensions (len %zu)", elen);
                   1026:                r = SSH_ERR_FEATURE_UNSUPPORTED;
                   1027:                goto out;
                   1028:        }
                   1029:        debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)",
                   1030:            dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
                   1031:            dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
                   1032:            dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
                   1033:        /* check consistency */
                   1034:        if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) ||
                   1035:            dc->from.user != NULL) {
                   1036:                error_f("inconsistent \"from\" specification");
                   1037:                r = SSH_ERR_INVALID_FORMAT;
                   1038:                goto out;
                   1039:        }
                   1040:        if (dc->to.hostname == NULL || dc->to.nkeys == 0) {
                   1041:                error_f("incomplete \"to\" specification");
                   1042:                r = SSH_ERR_INVALID_FORMAT;
                   1043:                goto out;
                   1044:        }
                   1045:        /* success */
                   1046:        r = 0;
                   1047:  out:
                   1048:        sshbuf_free(b);
                   1049:        sshbuf_free(frombuf);
                   1050:        sshbuf_free(tobuf);
                   1051:        return r;
                   1052: }
                   1053:
                   1054: static int
                   1055: parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp,
                   1056:     struct dest_constraint **dcsp, size_t *ndcsp)
1.277     djm      1057: {
                   1058:        char *ext_name = NULL;
                   1059:        int r;
1.281     djm      1060:        struct sshbuf *b = NULL;
1.277     djm      1061:
                   1062:        if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
                   1063:                error_fr(r, "parse constraint extension");
                   1064:                goto out;
                   1065:        }
                   1066:        debug_f("constraint ext %s", ext_name);
                   1067:        if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
                   1068:                if (sk_providerp == NULL) {
                   1069:                        error_f("%s not valid here", ext_name);
                   1070:                        r = SSH_ERR_INVALID_FORMAT;
                   1071:                        goto out;
                   1072:                }
                   1073:                if (*sk_providerp != NULL) {
                   1074:                        error_f("%s already set", ext_name);
                   1075:                        r = SSH_ERR_INVALID_FORMAT;
                   1076:                        goto out;
                   1077:                }
                   1078:                if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
                   1079:                        error_fr(r, "parse %s", ext_name);
                   1080:                        goto out;
                   1081:                }
1.281     djm      1082:        } else if (strcmp(ext_name,
                   1083:            "restrict-destination-v00@openssh.com") == 0) {
                   1084:                if (*dcsp != NULL) {
                   1085:                        error_f("%s already set", ext_name);
                   1086:                        goto out;
                   1087:                }
                   1088:                if ((r = sshbuf_froms(m, &b)) != 0) {
                   1089:                        error_fr(r, "parse %s outer", ext_name);
                   1090:                        goto out;
                   1091:                }
                   1092:                while (sshbuf_len(b) != 0) {
                   1093:                        if (*ndcsp >= AGENT_MAX_DEST_CONSTRAINTS) {
                   1094:                                error_f("too many %s constraints", ext_name);
                   1095:                                goto out;
                   1096:                        }
                   1097:                        *dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1,
                   1098:                            sizeof(**dcsp));
                   1099:                        if ((r = parse_dest_constraint(b,
                   1100:                            *dcsp + (*ndcsp)++)) != 0)
                   1101:                                goto out; /* error already logged */
                   1102:                }
1.277     djm      1103:        } else {
                   1104:                error_f("unsupported constraint \"%s\"", ext_name);
                   1105:                r = SSH_ERR_FEATURE_UNSUPPORTED;
                   1106:                goto out;
                   1107:        }
                   1108:        /* success */
                   1109:        r = 0;
                   1110:  out:
                   1111:        free(ext_name);
1.281     djm      1112:        sshbuf_free(b);
1.277     djm      1113:        return r;
                   1114: }
                   1115:
                   1116: static int
1.271     djm      1117: parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
1.281     djm      1118:     u_int *secondsp, int *confirmp, char **sk_providerp,
                   1119:     struct dest_constraint **dcsp, size_t *ndcsp)
1.1       deraadt  1120: {
1.194     markus   1121:        u_char ctype;
1.271     djm      1122:        int r;
                   1123:        u_int seconds, maxsign = 0;
1.33      markus   1124:
1.271     djm      1125:        while (sshbuf_len(m)) {
                   1126:                if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
1.266     djm      1127:                        error_fr(r, "parse constraint type");
1.277     djm      1128:                        goto out;
1.194     markus   1129:                }
                   1130:                switch (ctype) {
1.94      markus   1131:                case SSH_AGENT_CONSTRAIN_LIFETIME:
1.271     djm      1132:                        if (*deathp != 0) {
                   1133:                                error_f("lifetime already set");
1.277     djm      1134:                                r = SSH_ERR_INVALID_FORMAT;
                   1135:                                goto out;
1.271     djm      1136:                        }
                   1137:                        if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
1.266     djm      1138:                                error_fr(r, "parse lifetime constraint");
1.277     djm      1139:                                goto out;
1.194     markus   1140:                        }
1.271     djm      1141:                        *deathp = monotime() + seconds;
                   1142:                        *secondsp = seconds;
1.94      markus   1143:                        break;
1.107     markus   1144:                case SSH_AGENT_CONSTRAIN_CONFIRM:
1.271     djm      1145:                        if (*confirmp != 0) {
                   1146:                                error_f("confirm already set");
1.277     djm      1147:                                r = SSH_ERR_INVALID_FORMAT;
                   1148:                                goto out;
1.271     djm      1149:                        }
                   1150:                        *confirmp = 1;
1.107     markus   1151:                        break;
1.228     markus   1152:                case SSH_AGENT_CONSTRAIN_MAXSIGN:
1.271     djm      1153:                        if (k == NULL) {
                   1154:                                error_f("maxsign not valid here");
1.277     djm      1155:                                r = SSH_ERR_INVALID_FORMAT;
                   1156:                                goto out;
1.271     djm      1157:                        }
                   1158:                        if (maxsign != 0) {
                   1159:                                error_f("maxsign already set");
1.277     djm      1160:                                r = SSH_ERR_INVALID_FORMAT;
                   1161:                                goto out;
1.271     djm      1162:                        }
                   1163:                        if ((r = sshbuf_get_u32(m, &maxsign)) != 0) {
1.266     djm      1164:                                error_fr(r, "parse maxsign constraint");
1.277     djm      1165:                                goto out;
1.228     markus   1166:                        }
                   1167:                        if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
1.266     djm      1168:                                error_fr(r, "enable maxsign");
1.277     djm      1169:                                goto out;
1.228     markus   1170:                        }
                   1171:                        break;
1.238     djm      1172:                case SSH_AGENT_CONSTRAIN_EXTENSION:
1.277     djm      1173:                        if ((r = parse_key_constraint_extension(m,
1.281     djm      1174:                            sk_providerp, dcsp, ndcsp)) != 0)
1.277     djm      1175:                                goto out; /* error already logged */
1.238     djm      1176:                        break;
1.94      markus   1177:                default:
1.266     djm      1178:                        error_f("Unknown constraint %d", ctype);
1.277     djm      1179:                        r = SSH_ERR_FEATURE_UNSUPPORTED;
                   1180:                        goto out;
1.94      markus   1181:                }
                   1182:        }
1.271     djm      1183:        /* success */
1.277     djm      1184:        r = 0;
                   1185:  out:
                   1186:        return r;
1.271     djm      1187: }
                   1188:
                   1189: static void
                   1190: process_add_identity(SocketEntry *e)
                   1191: {
                   1192:        Identity *id;
                   1193:        int success = 0, confirm = 0;
1.272     dtucker  1194:        char *fp, *comment = NULL, *sk_provider = NULL;
1.271     djm      1195:        char canonical_provider[PATH_MAX];
                   1196:        time_t death = 0;
                   1197:        u_int seconds = 0;
1.281     djm      1198:        struct dest_constraint *dest_constraints = NULL;
                   1199:        size_t ndest_constraints = 0;
1.271     djm      1200:        struct sshkey *k = NULL;
                   1201:        int r = SSH_ERR_INTERNAL_ERROR;
                   1202:
                   1203:        debug2_f("entering");
                   1204:        if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
                   1205:            k == NULL ||
                   1206:            (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
                   1207:                error_fr(r, "parse");
                   1208:                goto out;
                   1209:        }
                   1210:        if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
1.281     djm      1211:            &sk_provider, &dest_constraints, &ndest_constraints) != 0) {
1.271     djm      1212:                error_f("failed to parse constraints");
                   1213:                sshbuf_reset(e->request);
                   1214:                goto out;
                   1215:        }
                   1216:
1.238     djm      1217:        if (sk_provider != NULL) {
1.240     markus   1218:                if (!sshkey_is_sk(k)) {
1.255     naddy    1219:                        error("Cannot add provider: %s is not an "
                   1220:                            "authenticator-hosted key", sshkey_type(k));
1.271     djm      1221:                        goto out;
1.238     djm      1222:                }
1.254     djm      1223:                if (strcasecmp(sk_provider, "internal") == 0) {
1.266     djm      1224:                        debug_f("internal provider");
1.254     djm      1225:                } else {
1.292.4.1! bluhm    1226:                        if (e->nsession_ids != 0 && !remote_add_provider) {
        !          1227:                                verbose("failed add of SK provider \"%.100s\": "
        !          1228:                                    "remote addition of providers is disabled",
        !          1229:                                    sk_provider);
        !          1230:                                goto out;
        !          1231:                        }
1.254     djm      1232:                        if (realpath(sk_provider, canonical_provider) == NULL) {
                   1233:                                verbose("failed provider \"%.100s\": "
                   1234:                                    "realpath: %s", sk_provider,
                   1235:                                    strerror(errno));
1.271     djm      1236:                                goto out;
1.254     djm      1237:                        }
1.238     djm      1238:                        free(sk_provider);
1.254     djm      1239:                        sk_provider = xstrdup(canonical_provider);
                   1240:                        if (match_pattern_list(sk_provider,
1.260     djm      1241:                            allowed_providers, 0) != 1) {
1.254     djm      1242:                                error("Refusing add key: "
1.260     djm      1243:                                    "provider %s not allowed", sk_provider);
1.271     djm      1244:                                goto out;
1.254     djm      1245:                        }
1.238     djm      1246:                }
1.242     markus   1247:        }
                   1248:        if ((r = sshkey_shield_private(k)) != 0) {
1.266     djm      1249:                error_fr(r, "shield private");
1.271     djm      1250:                goto out;
1.238     djm      1251:        }
1.106     marc     1252:        if (lifetime && !death)
1.175     dtucker  1253:                death = monotime() + lifetime;
1.221     djm      1254:        if ((id = lookup_identity(k)) == NULL) {
1.163     markus   1255:                id = xcalloc(1, sizeof(Identity));
1.221     djm      1256:                TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1.33      markus   1257:                /* Increment the number of identities. */
1.221     djm      1258:                idtab->nentries++;
1.33      markus   1259:        } else {
1.281     djm      1260:                /* identity not visible, do not update */
                   1261:                if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
                   1262:                        goto out; /* error already logged */
1.228     markus   1263:                /* key state might have been updated */
                   1264:                sshkey_free(id->key);
1.173     djm      1265:                free(id->comment);
1.238     djm      1266:                free(id->sk_provider);
1.281     djm      1267:                free_dest_constraints(id->dest_constraints,
                   1268:                    id->ndest_constraints);
1.33      markus   1269:        }
1.271     djm      1270:        /* success */
1.228     markus   1271:        id->key = k;
1.157     canacar  1272:        id->comment = comment;
                   1273:        id->death = death;
                   1274:        id->confirm = confirm;
1.238     djm      1275:        id->sk_provider = sk_provider;
1.281     djm      1276:        id->dest_constraints = dest_constraints;
                   1277:        id->ndest_constraints = ndest_constraints;
1.238     djm      1278:
                   1279:        if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
                   1280:            SSH_FP_DEFAULT)) == NULL)
1.266     djm      1281:                fatal_f("sshkey_fingerprint failed");
                   1282:        debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
1.281     djm      1283:            "(provider: %s) (destination constraints: %zu)",
                   1284:            sshkey_ssh_name(k), fp, comment, seconds, confirm,
                   1285:            sk_provider == NULL ? "none" : sk_provider, ndest_constraints);
1.238     djm      1286:        free(fp);
1.271     djm      1287:        /* transferred */
                   1288:        k = NULL;
                   1289:        comment = NULL;
                   1290:        sk_provider = NULL;
1.281     djm      1291:        dest_constraints = NULL;
                   1292:        ndest_constraints = 0;
1.271     djm      1293:        success = 1;
                   1294:  out:
                   1295:        free(sk_provider);
                   1296:        free(comment);
                   1297:        sshkey_free(k);
1.281     djm      1298:        free_dest_constraints(dest_constraints, ndest_constraints);
1.194     markus   1299:        send_status(e, success);
1.1       deraadt  1300: }
                   1301:
1.88      markus   1302: /* XXX todo: encrypt sensitive data with passphrase */
                   1303: static void
                   1304: process_lock_agent(SocketEntry *e, int lock)
                   1305: {
1.203     dtucker  1306:        int r, success = 0, delay;
1.213     djm      1307:        char *passwd;
                   1308:        u_char passwdhash[LOCK_SIZE];
1.203     dtucker  1309:        static u_int fail_count = 0;
                   1310:        size_t pwlen;
                   1311:
1.269     djm      1312:        debug2_f("entering");
1.226     djm      1313:        /*
                   1314:         * This is deliberately fatal: the user has requested that we lock,
                   1315:         * but we can't parse their request properly. The only safe thing to
                   1316:         * do is abort.
                   1317:         */
1.203     dtucker  1318:        if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
1.266     djm      1319:                fatal_fr(r, "parse");
1.203     dtucker  1320:        if (pwlen == 0) {
                   1321:                debug("empty password not supported");
                   1322:        } else if (locked && !lock) {
                   1323:                if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
                   1324:                    passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
                   1325:                        fatal("bcrypt_pbkdf");
1.213     djm      1326:                if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
1.203     dtucker  1327:                        debug("agent unlocked");
                   1328:                        locked = 0;
                   1329:                        fail_count = 0;
1.213     djm      1330:                        explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
1.203     dtucker  1331:                        success = 1;
                   1332:                } else {
                   1333:                        /* delay in 0.1s increments up to 10s */
                   1334:                        if (fail_count < 100)
                   1335:                                fail_count++;
                   1336:                        delay = 100000 * fail_count;
                   1337:                        debug("unlock failed, delaying %0.1lf seconds",
                   1338:                            (double)delay/1000000);
                   1339:                        usleep(delay);
                   1340:                }
                   1341:                explicit_bzero(passwdhash, sizeof(passwdhash));
1.88      markus   1342:        } else if (!locked && lock) {
1.203     dtucker  1343:                debug("agent locked");
1.88      markus   1344:                locked = 1;
1.203     dtucker  1345:                arc4random_buf(lock_salt, sizeof(lock_salt));
                   1346:                if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1.213     djm      1347:                    lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
1.203     dtucker  1348:                        fatal("bcrypt_pbkdf");
1.88      markus   1349:                success = 1;
                   1350:        }
1.256     jsg      1351:        freezero(passwd, pwlen);
1.194     markus   1352:        send_status(e, success);
1.88      markus   1353: }
                   1354:
                   1355: static void
1.221     djm      1356: no_identities(SocketEntry *e)
1.88      markus   1357: {
1.194     markus   1358:        struct sshbuf *msg;
                   1359:        int r;
1.88      markus   1360:
1.194     markus   1361:        if ((msg = sshbuf_new()) == NULL)
1.266     djm      1362:                fatal_f("sshbuf_new failed");
1.221     djm      1363:        if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
1.194     markus   1364:            (r = sshbuf_put_u32(msg, 0)) != 0 ||
                   1365:            (r = sshbuf_put_stringb(e->output, msg)) != 0)
1.266     djm      1366:                fatal_fr(r, "compose");
1.194     markus   1367:        sshbuf_free(msg);
1.88      markus   1368: }
1.59      markus   1369:
1.163     markus   1370: #ifdef ENABLE_PKCS11
1.59      markus   1371: static void
1.158     djm      1372: process_add_smartcard_key(SocketEntry *e)
1.59      markus   1373: {
1.226     djm      1374:        char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1.253     djm      1375:        char **comments = NULL;
1.221     djm      1376:        int r, i, count = 0, success = 0, confirm = 0;
1.271     djm      1377:        u_int seconds = 0;
1.174     dtucker  1378:        time_t death = 0;
1.194     markus   1379:        struct sshkey **keys = NULL, *k;
1.84      markus   1380:        Identity *id;
1.281     djm      1381:        struct dest_constraint *dest_constraints = NULL;
                   1382:        size_t ndest_constraints = 0;
1.75      deraadt  1383:
1.269     djm      1384:        debug2_f("entering");
1.194     markus   1385:        if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1.226     djm      1386:            (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1.266     djm      1387:                error_fr(r, "parse");
1.226     djm      1388:                goto send;
                   1389:        }
1.271     djm      1390:        if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
1.281     djm      1391:            NULL, &dest_constraints, &ndest_constraints) != 0) {
1.271     djm      1392:                error_f("failed to parse constraints");
                   1393:                goto send;
1.110     djm      1394:        }
1.292.4.1! bluhm    1395:        if (e->nsession_ids != 0 && !remote_add_provider) {
        !          1396:                verbose("failed PKCS#11 add of \"%.100s\": remote addition of "
        !          1397:                    "providers is disabled", provider);
        !          1398:                goto send;
        !          1399:        }
1.215     djm      1400:        if (realpath(provider, canonical_provider) == NULL) {
                   1401:                verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
                   1402:                    provider, strerror(errno));
                   1403:                goto send;
                   1404:        }
1.260     djm      1405:        if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
1.215     djm      1406:                verbose("refusing PKCS#11 add of \"%.100s\": "
1.260     djm      1407:                    "provider not allowed", canonical_provider);
1.215     djm      1408:                goto send;
                   1409:        }
1.266     djm      1410:        debug_f("add %.100s", canonical_provider);
1.110     djm      1411:        if (lifetime && !death)
1.175     dtucker  1412:                death = monotime() + lifetime;
1.110     djm      1413:
1.253     djm      1414:        count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
1.163     markus   1415:        for (i = 0; i < count; i++) {
1.84      markus   1416:                k = keys[i];
1.221     djm      1417:                if (lookup_identity(k) == NULL) {
1.163     markus   1418:                        id = xcalloc(1, sizeof(Identity));
1.84      markus   1419:                        id->key = k;
1.253     djm      1420:                        keys[i] = NULL; /* transferred */
1.215     djm      1421:                        id->provider = xstrdup(canonical_provider);
1.253     djm      1422:                        if (*comments[i] != '\0') {
                   1423:                                id->comment = comments[i];
                   1424:                                comments[i] = NULL; /* transferred */
                   1425:                        } else {
                   1426:                                id->comment = xstrdup(canonical_provider);
                   1427:                        }
1.110     djm      1428:                        id->death = death;
                   1429:                        id->confirm = confirm;
1.281     djm      1430:                        id->dest_constraints = dest_constraints;
                   1431:                        id->ndest_constraints = ndest_constraints;
                   1432:                        dest_constraints = NULL; /* transferred */
                   1433:                        ndest_constraints = 0;
1.221     djm      1434:                        TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
                   1435:                        idtab->nentries++;
1.84      markus   1436:                        success = 1;
                   1437:                }
1.271     djm      1438:                /* XXX update constraints for existing keys */
1.253     djm      1439:                sshkey_free(keys[i]);
                   1440:                free(comments[i]);
1.59      markus   1441:        }
                   1442: send:
1.173     djm      1443:        free(pin);
                   1444:        free(provider);
                   1445:        free(keys);
1.253     djm      1446:        free(comments);
1.281     djm      1447:        free_dest_constraints(dest_constraints, ndest_constraints);
1.194     markus   1448:        send_status(e, success);
1.59      markus   1449: }
                   1450:
                   1451: static void
                   1452: process_remove_smartcard_key(SocketEntry *e)
                   1453: {
1.217     djm      1454:        char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1.221     djm      1455:        int r, success = 0;
1.163     markus   1456:        Identity *id, *nxt;
1.59      markus   1457:
1.269     djm      1458:        debug2_f("entering");
1.194     markus   1459:        if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1.226     djm      1460:            (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1.266     djm      1461:                error_fr(r, "parse");
1.226     djm      1462:                goto send;
                   1463:        }
1.173     djm      1464:        free(pin);
1.59      markus   1465:
1.217     djm      1466:        if (realpath(provider, canonical_provider) == NULL) {
                   1467:                verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
                   1468:                    provider, strerror(errno));
                   1469:                goto send;
                   1470:        }
                   1471:
1.266     djm      1472:        debug_f("remove %.100s", canonical_provider);
1.221     djm      1473:        for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
                   1474:                nxt = TAILQ_NEXT(id, next);
                   1475:                /* Skip file--based keys */
                   1476:                if (id->provider == NULL)
                   1477:                        continue;
                   1478:                if (!strcmp(canonical_provider, id->provider)) {
                   1479:                        TAILQ_REMOVE(&idtab->idlist, id, next);
                   1480:                        free_identity(id);
                   1481:                        idtab->nentries--;
1.59      markus   1482:                }
                   1483:        }
1.217     djm      1484:        if (pkcs11_del_provider(canonical_provider) == 0)
1.163     markus   1485:                success = 1;
                   1486:        else
1.266     djm      1487:                error_f("pkcs11_del_provider failed");
1.218     deraadt  1488: send:
1.173     djm      1489:        free(provider);
1.194     markus   1490:        send_status(e, success);
1.59      markus   1491: }
1.163     markus   1492: #endif /* ENABLE_PKCS11 */
1.59      markus   1493:
1.280     djm      1494: static int
                   1495: process_ext_session_bind(SocketEntry *e)
                   1496: {
                   1497:        int r, sid_match, key_match;
                   1498:        struct sshkey *key = NULL;
                   1499:        struct sshbuf *sid = NULL, *sig = NULL;
                   1500:        char *fp = NULL;
                   1501:        size_t i;
1.281     djm      1502:        u_char fwd = 0;
1.280     djm      1503:
                   1504:        debug2_f("entering");
                   1505:        if ((r = sshkey_froms(e->request, &key)) != 0 ||
                   1506:            (r = sshbuf_froms(e->request, &sid)) != 0 ||
                   1507:            (r = sshbuf_froms(e->request, &sig)) != 0 ||
                   1508:            (r = sshbuf_get_u8(e->request, &fwd)) != 0) {
                   1509:                error_fr(r, "parse");
                   1510:                goto out;
                   1511:        }
                   1512:        if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
                   1513:            SSH_FP_DEFAULT)) == NULL)
                   1514:                fatal_f("fingerprint failed");
                   1515:        /* check signature with hostkey on session ID */
                   1516:        if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig),
                   1517:            sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) {
                   1518:                error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp);
                   1519:                goto out;
                   1520:        }
                   1521:        /* check whether sid/key already recorded */
                   1522:        for (i = 0; i < e->nsession_ids; i++) {
1.281     djm      1523:                if (!e->session_ids[i].forwarded) {
                   1524:                        error_f("attempt to bind session ID to socket "
                   1525:                            "previously bound for authentication attempt");
                   1526:                        r = -1;
                   1527:                        goto out;
                   1528:                }
1.280     djm      1529:                sid_match = buf_equal(sid, e->session_ids[i].sid) == 0;
                   1530:                key_match = sshkey_equal(key, e->session_ids[i].key);
                   1531:                if (sid_match && key_match) {
                   1532:                        debug_f("session ID already recorded for %s %s",
                   1533:                            sshkey_type(key), fp);
                   1534:                        r = 0;
                   1535:                        goto out;
                   1536:                } else if (sid_match) {
                   1537:                        error_f("session ID recorded against different key "
                   1538:                            "for %s %s", sshkey_type(key), fp);
                   1539:                        r = -1;
                   1540:                        goto out;
                   1541:                }
                   1542:                /*
                   1543:                 * new sid with previously-seen key can happen, e.g. multiple
                   1544:                 * connections to the same host.
                   1545:                 */
                   1546:        }
                   1547:        /* record new key/sid */
                   1548:        if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) {
                   1549:                error_f("too many session IDs recorded");
                   1550:                goto out;
                   1551:        }
                   1552:        e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids,
                   1553:            e->nsession_ids + 1, sizeof(*e->session_ids));
                   1554:        i = e->nsession_ids++;
                   1555:        debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i,
                   1556:            AGENT_MAX_SESSION_IDS);
                   1557:        e->session_ids[i].key = key;
                   1558:        e->session_ids[i].forwarded = fwd != 0;
                   1559:        key = NULL; /* transferred */
                   1560:        /* can't transfer sid; it's refcounted and scoped to request's life */
                   1561:        if ((e->session_ids[i].sid = sshbuf_new()) == NULL)
                   1562:                fatal_f("sshbuf_new");
                   1563:        if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0)
                   1564:                fatal_fr(r, "sshbuf_putb session ID");
                   1565:        /* success */
                   1566:        r = 0;
                   1567:  out:
1.288     djm      1568:        free(fp);
1.280     djm      1569:        sshkey_free(key);
                   1570:        sshbuf_free(sid);
                   1571:        sshbuf_free(sig);
                   1572:        return r == 0 ? 1 : 0;
                   1573: }
                   1574:
                   1575: static void
                   1576: process_extension(SocketEntry *e)
                   1577: {
                   1578:        int r, success = 0;
                   1579:        char *name;
                   1580:
                   1581:        debug2_f("entering");
                   1582:        if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) {
                   1583:                error_fr(r, "parse");
                   1584:                goto send;
                   1585:        }
                   1586:        if (strcmp(name, "session-bind@openssh.com") == 0)
                   1587:                success = process_ext_session_bind(e);
                   1588:        else
                   1589:                debug_f("unsupported extension \"%s\"", name);
1.285     djm      1590:        free(name);
1.280     djm      1591: send:
                   1592:        send_status(e, success);
                   1593: }
1.264     djm      1594: /*
                   1595:  * dispatch incoming message.
                   1596:  * returns 1 on success, 0 for incomplete messages or -1 on error.
                   1597:  */
1.223     djm      1598: static int
                   1599: process_message(u_int socknum)
1.1       deraadt  1600: {
1.194     markus   1601:        u_int msg_len;
                   1602:        u_char type;
                   1603:        const u_char *cp;
                   1604:        int r;
1.223     djm      1605:        SocketEntry *e;
                   1606:
1.266     djm      1607:        if (socknum >= sockets_alloc)
                   1608:                fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
1.223     djm      1609:        e = &sockets[socknum];
1.89      markus   1610:
1.194     markus   1611:        if (sshbuf_len(e->input) < 5)
1.223     djm      1612:                return 0;               /* Incomplete message header. */
1.194     markus   1613:        cp = sshbuf_ptr(e->input);
                   1614:        msg_len = PEEK_U32(cp);
1.223     djm      1615:        if (msg_len > AGENT_MAX_LEN) {
1.266     djm      1616:                debug_f("socket %u (fd=%d) message too long %u > %u",
                   1617:                    socknum, e->fd, msg_len, AGENT_MAX_LEN);
1.223     djm      1618:                return -1;
1.21      markus   1619:        }
1.194     markus   1620:        if (sshbuf_len(e->input) < msg_len + 4)
1.223     djm      1621:                return 0;               /* Incomplete message body. */
1.87      markus   1622:
                   1623:        /* move the current input to e->request */
1.194     markus   1624:        sshbuf_reset(e->request);
                   1625:        if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1.223     djm      1626:            (r = sshbuf_get_u8(e->request, &type)) != 0) {
                   1627:                if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
                   1628:                    r == SSH_ERR_STRING_TOO_LARGE) {
1.266     djm      1629:                        error_fr(r, "parse");
1.223     djm      1630:                        return -1;
                   1631:                }
1.266     djm      1632:                fatal_fr(r, "parse");
1.223     djm      1633:        }
                   1634:
1.266     djm      1635:        debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1.21      markus   1636:
1.230     djm      1637:        /* check whether agent is locked */
1.88      markus   1638:        if (locked && type != SSH_AGENTC_UNLOCK) {
1.194     markus   1639:                sshbuf_reset(e->request);
1.88      markus   1640:                switch (type) {
                   1641:                case SSH2_AGENTC_REQUEST_IDENTITIES:
                   1642:                        /* send empty lists */
1.221     djm      1643:                        no_identities(e);
1.88      markus   1644:                        break;
                   1645:                default:
                   1646:                        /* send a fail message for all other request types */
1.194     markus   1647:                        send_status(e, 0);
1.88      markus   1648:                }
1.264     djm      1649:                return 1;
1.88      markus   1650:        }
                   1651:
1.21      markus   1652:        switch (type) {
1.88      markus   1653:        case SSH_AGENTC_LOCK:
                   1654:        case SSH_AGENTC_UNLOCK:
                   1655:                process_lock_agent(e, type == SSH_AGENTC_LOCK);
                   1656:                break;
1.21      markus   1657:        case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1.221     djm      1658:                process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1.33      markus   1659:                break;
                   1660:        /* ssh2 */
                   1661:        case SSH2_AGENTC_SIGN_REQUEST:
                   1662:                process_sign_request2(e);
                   1663:                break;
                   1664:        case SSH2_AGENTC_REQUEST_IDENTITIES:
1.221     djm      1665:                process_request_identities(e);
1.33      markus   1666:                break;
                   1667:        case SSH2_AGENTC_ADD_IDENTITY:
1.94      markus   1668:        case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1.221     djm      1669:                process_add_identity(e);
1.33      markus   1670:                break;
                   1671:        case SSH2_AGENTC_REMOVE_IDENTITY:
1.221     djm      1672:                process_remove_identity(e);
1.33      markus   1673:                break;
                   1674:        case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1.221     djm      1675:                process_remove_all_identities(e);
1.21      markus   1676:                break;
1.163     markus   1677: #ifdef ENABLE_PKCS11
1.59      markus   1678:        case SSH_AGENTC_ADD_SMARTCARD_KEY:
1.110     djm      1679:        case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1.59      markus   1680:                process_add_smartcard_key(e);
1.75      deraadt  1681:                break;
1.59      markus   1682:        case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
                   1683:                process_remove_smartcard_key(e);
1.75      deraadt  1684:                break;
1.163     markus   1685: #endif /* ENABLE_PKCS11 */
1.280     djm      1686:        case SSH_AGENTC_EXTENSION:
                   1687:                process_extension(e);
                   1688:                break;
1.21      markus   1689:        default:
                   1690:                /* Unknown message.  Respond with failure. */
                   1691:                error("Unknown message %d", type);
1.194     markus   1692:                sshbuf_reset(e->request);
                   1693:                send_status(e, 0);
1.21      markus   1694:                break;
                   1695:        }
1.264     djm      1696:        return 1;
1.1       deraadt  1697: }
                   1698:
1.55      itojun   1699: static void
1.73      stevesk  1700: new_socket(sock_type type, int fd)
1.1       deraadt  1701: {
1.112     markus   1702:        u_int i, old_alloc, new_alloc;
1.96      deraadt  1703:
1.269     djm      1704:        debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
                   1705:            (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1.119     djm      1706:        set_nonblock(fd);
1.21      markus   1707:
                   1708:        if (fd > max_fd)
                   1709:                max_fd = fd;
                   1710:
                   1711:        for (i = 0; i < sockets_alloc; i++)
                   1712:                if (sockets[i].type == AUTH_UNUSED) {
                   1713:                        sockets[i].fd = fd;
1.266     djm      1714:                        if ((sockets[i].input = sshbuf_new()) == NULL ||
                   1715:                            (sockets[i].output = sshbuf_new()) == NULL ||
                   1716:                            (sockets[i].request = sshbuf_new()) == NULL)
                   1717:                                fatal_f("sshbuf_new failed");
1.112     markus   1718:                        sockets[i].type = type;
1.21      markus   1719:                        return;
                   1720:                }
                   1721:        old_alloc = sockets_alloc;
1.112     markus   1722:        new_alloc = sockets_alloc + 10;
1.269     djm      1723:        sockets = xrecallocarray(sockets, old_alloc, new_alloc,
                   1724:            sizeof(sockets[0]));
1.112     markus   1725:        for (i = old_alloc; i < new_alloc; i++)
1.21      markus   1726:                sockets[i].type = AUTH_UNUSED;
1.112     markus   1727:        sockets_alloc = new_alloc;
1.21      markus   1728:        sockets[old_alloc].fd = fd;
1.266     djm      1729:        if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
                   1730:            (sockets[old_alloc].output = sshbuf_new()) == NULL ||
                   1731:            (sockets[old_alloc].request = sshbuf_new()) == NULL)
                   1732:                fatal_f("sshbuf_new failed");
1.112     markus   1733:        sockets[old_alloc].type = type;
1.1       deraadt  1734: }
                   1735:
1.55      itojun   1736: static int
1.223     djm      1737: handle_socket_read(u_int socknum)
1.1       deraadt  1738: {
1.223     djm      1739:        struct sockaddr_un sunaddr;
                   1740:        socklen_t slen;
                   1741:        uid_t euid;
                   1742:        gid_t egid;
                   1743:        int fd;
                   1744:
                   1745:        slen = sizeof(sunaddr);
                   1746:        fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1.237     deraadt  1747:        if (fd == -1) {
1.223     djm      1748:                error("accept from AUTH_SOCKET: %s", strerror(errno));
                   1749:                return -1;
                   1750:        }
1.237     deraadt  1751:        if (getpeereid(fd, &euid, &egid) == -1) {
1.223     djm      1752:                error("getpeereid %d failed: %s", fd, strerror(errno));
                   1753:                close(fd);
                   1754:                return -1;
                   1755:        }
                   1756:        if ((euid != 0) && (getuid() != euid)) {
                   1757:                error("uid mismatch: peer euid %u != uid %u",
                   1758:                    (u_int) euid, (u_int) getuid());
                   1759:                close(fd);
                   1760:                return -1;
                   1761:        }
                   1762:        new_socket(AUTH_CONNECTION, fd);
                   1763:        return 0;
                   1764: }
                   1765:
                   1766: static int
                   1767: handle_conn_read(u_int socknum)
                   1768: {
1.233     djm      1769:        char buf[AGENT_RBUF_LEN];
1.223     djm      1770:        ssize_t len;
                   1771:        int r;
                   1772:
                   1773:        if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
                   1774:                if (len == -1) {
                   1775:                        if (errno == EAGAIN || errno == EINTR)
                   1776:                                return 0;
1.266     djm      1777:                        error_f("read error on socket %u (fd %d): %s",
                   1778:                            socknum, sockets[socknum].fd, strerror(errno));
1.223     djm      1779:                }
                   1780:                return -1;
                   1781:        }
                   1782:        if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1.266     djm      1783:                fatal_fr(r, "compose");
1.223     djm      1784:        explicit_bzero(buf, sizeof(buf));
1.264     djm      1785:        for (;;) {
                   1786:                if ((r = process_message(socknum)) == -1)
                   1787:                        return -1;
                   1788:                else if (r == 0)
                   1789:                        break;
                   1790:        }
1.223     djm      1791:        return 0;
                   1792: }
                   1793:
                   1794: static int
                   1795: handle_conn_write(u_int socknum)
                   1796: {
                   1797:        ssize_t len;
                   1798:        int r;
                   1799:
                   1800:        if (sshbuf_len(sockets[socknum].output) == 0)
                   1801:                return 0; /* shouldn't happen */
                   1802:        if ((len = write(sockets[socknum].fd,
                   1803:            sshbuf_ptr(sockets[socknum].output),
                   1804:            sshbuf_len(sockets[socknum].output))) <= 0) {
                   1805:                if (len == -1) {
                   1806:                        if (errno == EAGAIN || errno == EINTR)
                   1807:                                return 0;
1.266     djm      1808:                        error_f("read error on socket %u (fd %d): %s",
                   1809:                            socknum, sockets[socknum].fd, strerror(errno));
1.223     djm      1810:                }
                   1811:                return -1;
                   1812:        }
                   1813:        if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
1.266     djm      1814:                fatal_fr(r, "consume");
1.223     djm      1815:        return 0;
                   1816: }
                   1817:
                   1818: static void
1.231     djm      1819: after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
1.223     djm      1820: {
                   1821:        size_t i;
1.231     djm      1822:        u_int socknum, activefds = npfd;
1.223     djm      1823:
                   1824:        for (i = 0; i < npfd; i++) {
                   1825:                if (pfd[i].revents == 0)
                   1826:                        continue;
                   1827:                /* Find sockets entry */
                   1828:                for (socknum = 0; socknum < sockets_alloc; socknum++) {
                   1829:                        if (sockets[socknum].type != AUTH_SOCKET &&
                   1830:                            sockets[socknum].type != AUTH_CONNECTION)
                   1831:                                continue;
                   1832:                        if (pfd[i].fd == sockets[socknum].fd)
                   1833:                                break;
                   1834:                }
                   1835:                if (socknum >= sockets_alloc) {
1.266     djm      1836:                        error_f("no socket for fd %d", pfd[i].fd);
1.223     djm      1837:                        continue;
                   1838:                }
                   1839:                /* Process events */
                   1840:                switch (sockets[socknum].type) {
                   1841:                case AUTH_SOCKET:
1.231     djm      1842:                        if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
                   1843:                                break;
                   1844:                        if (npfd > maxfds) {
                   1845:                                debug3("out of fds (active %u >= limit %u); "
                   1846:                                    "skipping accept", activefds, maxfds);
                   1847:                                break;
                   1848:                        }
                   1849:                        if (handle_socket_read(socknum) == 0)
                   1850:                                activefds++;
1.223     djm      1851:                        break;
                   1852:                case AUTH_CONNECTION:
1.279     djm      1853:                        if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 &&
                   1854:                            handle_conn_read(socknum) != 0)
1.231     djm      1855:                                goto close_sock;
                   1856:                        if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
                   1857:                            handle_conn_write(socknum) != 0) {
                   1858:  close_sock:
                   1859:                                if (activefds == 0)
                   1860:                                        fatal("activefds == 0 at close_sock");
1.223     djm      1861:                                close_socket(&sockets[socknum]);
1.231     djm      1862:                                activefds--;
1.223     djm      1863:                                break;
                   1864:                        }
                   1865:                        break;
                   1866:                default:
                   1867:                        break;
                   1868:                }
                   1869:        }
                   1870: }
                   1871:
                   1872: static int
1.231     djm      1873: prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
1.223     djm      1874: {
                   1875:        struct pollfd *pfd = *pfdp;
                   1876:        size_t i, j, npfd = 0;
1.174     dtucker  1877:        time_t deadline;
1.233     djm      1878:        int r;
1.46      markus   1879:
1.223     djm      1880:        /* Count active sockets */
1.46      markus   1881:        for (i = 0; i < sockets_alloc; i++) {
1.21      markus   1882:                switch (sockets[i].type) {
                   1883:                case AUTH_SOCKET:
                   1884:                case AUTH_CONNECTION:
1.223     djm      1885:                        npfd++;
1.21      markus   1886:                        break;
                   1887:                case AUTH_UNUSED:
                   1888:                        break;
                   1889:                default:
                   1890:                        fatal("Unknown socket type %d", sockets[i].type);
                   1891:                        break;
                   1892:                }
1.46      markus   1893:        }
1.223     djm      1894:        if (npfd != *npfdp &&
                   1895:            (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
1.266     djm      1896:                fatal_f("recallocarray failed");
1.223     djm      1897:        *pfdp = pfd;
                   1898:        *npfdp = npfd;
1.46      markus   1899:
1.223     djm      1900:        for (i = j = 0; i < sockets_alloc; i++) {
1.46      markus   1901:                switch (sockets[i].type) {
                   1902:                case AUTH_SOCKET:
1.231     djm      1903:                        if (npfd > maxfds) {
                   1904:                                debug3("out of fds (active %zu >= limit %u); "
                   1905:                                    "skipping arming listener", npfd, maxfds);
                   1906:                                break;
                   1907:                        }
                   1908:                        pfd[j].fd = sockets[i].fd;
                   1909:                        pfd[j].revents = 0;
                   1910:                        pfd[j].events = POLLIN;
                   1911:                        j++;
                   1912:                        break;
1.46      markus   1913:                case AUTH_CONNECTION:
1.223     djm      1914:                        pfd[j].fd = sockets[i].fd;
                   1915:                        pfd[j].revents = 0;
1.233     djm      1916:                        /*
                   1917:                         * Only prepare to read if we can handle a full-size
                   1918:                         * input read buffer and enqueue a max size reply..
                   1919:                         */
                   1920:                        if ((r = sshbuf_check_reserve(sockets[i].input,
                   1921:                            AGENT_RBUF_LEN)) == 0 &&
                   1922:                            (r = sshbuf_check_reserve(sockets[i].output,
1.278     djm      1923:                            AGENT_MAX_LEN)) == 0)
1.233     djm      1924:                                pfd[j].events = POLLIN;
1.266     djm      1925:                        else if (r != SSH_ERR_NO_BUFFER_SPACE)
                   1926:                                fatal_fr(r, "reserve");
1.194     markus   1927:                        if (sshbuf_len(sockets[i].output) > 0)
1.223     djm      1928:                                pfd[j].events |= POLLOUT;
                   1929:                        j++;
1.46      markus   1930:                        break;
                   1931:                default:
                   1932:                        break;
                   1933:                }
                   1934:        }
1.155     dtucker  1935:        deadline = reaper();
                   1936:        if (parent_alive_interval != 0)
                   1937:                deadline = (deadline == 0) ? parent_alive_interval :
1.214     deraadt  1938:                    MINIMUM(deadline, parent_alive_interval);
1.155     dtucker  1939:        if (deadline == 0) {
1.224     djm      1940:                *timeoutp = -1; /* INFTIM */
1.155     dtucker  1941:        } else {
1.223     djm      1942:                if (deadline > INT_MAX / 1000)
                   1943:                        *timeoutp = INT_MAX / 1000;
                   1944:                else
                   1945:                        *timeoutp = deadline * 1000;
1.155     dtucker  1946:        }
1.46      markus   1947:        return (1);
1.21      markus   1948: }
                   1949:
1.55      itojun   1950: static void
1.113     markus   1951: cleanup_socket(void)
1.15      markus   1952: {
1.187     djm      1953:        if (cleanup_pid != 0 && getpid() != cleanup_pid)
                   1954:                return;
1.266     djm      1955:        debug_f("cleanup");
1.48      deraadt  1956:        if (socket_name[0])
                   1957:                unlink(socket_name);
                   1958:        if (socket_dir[0])
                   1959:                rmdir(socket_dir);
1.10      markus   1960: }
                   1961:
1.114     markus   1962: void
1.15      markus   1963: cleanup_exit(int i)
                   1964: {
1.113     markus   1965:        cleanup_socket();
                   1966:        _exit(i);
1.15      markus   1967: }
                   1968:
1.135     deraadt  1969: /*ARGSUSED*/
1.55      itojun   1970: static void
1.48      deraadt  1971: cleanup_handler(int sig)
                   1972: {
1.113     markus   1973:        cleanup_socket();
1.163     markus   1974: #ifdef ENABLE_PKCS11
                   1975:        pkcs11_terminate();
                   1976: #endif
1.48      deraadt  1977:        _exit(2);
1.113     markus   1978: }
                   1979:
1.68      markus   1980: static void
1.155     dtucker  1981: check_parent_exists(void)
1.68      markus   1982: {
1.172     dtucker  1983:        /*
                   1984:         * If our parent has exited then getppid() will return (pid_t)1,
                   1985:         * so testing for that should be safe.
                   1986:         */
                   1987:        if (parent_pid != -1 && getppid() != parent_pid) {
1.68      markus   1988:                /* printf("Parent has died - Authentication agent exiting.\n"); */
1.155     dtucker  1989:                cleanup_socket();
                   1990:                _exit(2);
1.68      markus   1991:        }
1.48      deraadt  1992: }
                   1993:
1.55      itojun   1994: static void
1.50      itojun   1995: usage(void)
1.15      markus   1996: {
1.184     deraadt  1997:        fprintf(stderr,
1.250     jmc      1998:            "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1.261     jmc      1999:            "                 [-P allowed_providers] [-t life]\n"
1.260     djm      2000:            "       ssh-agent [-a bind_address] [-E fingerprint_hash] [-P allowed_providers]\n"
1.259     dtucker  2001:            "                 [-t life] command [arg ...]\n"
1.250     jmc      2002:            "       ssh-agent [-c | -s] -k\n");
1.21      markus   2003:        exit(1);
1.15      markus   2004: }
                   2005:
1.2       provos   2006: int
                   2007: main(int ac, char **av)
1.1       deraadt  2008: {
1.201     djm      2009:        int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1.265     djm      2010:        int sock, ch, result, saved_errno;
1.96      deraadt  2011:        char *shell, *format, *pidstr, *agentsocket = NULL;
1.41      markus   2012:        struct rlimit rlim;
1.96      deraadt  2013:        extern int optind;
1.98      stevesk  2014:        extern char *optarg;
1.21      markus   2015:        pid_t pid;
1.96      deraadt  2016:        char pidstrbuf[1 + 3 * sizeof pid];
1.161     tobias   2017:        size_t len;
1.189     djm      2018:        mode_t prev_mask;
1.224     djm      2019:        int timeout = -1; /* INFTIM */
1.223     djm      2020:        struct pollfd *pfd = NULL;
                   2021:        size_t npfd = 0;
1.231     djm      2022:        u_int maxfds;
1.123     djm      2023:
                   2024:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                   2025:        sanitise_stdfd();
1.99      markus   2026:
                   2027:        /* drop */
                   2028:        setegid(getgid());
                   2029:        setgid(getgid());
1.53      markus   2030:
1.231     djm      2031:        if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
                   2032:                fatal("%s: getrlimit: %s", __progname, strerror(errno));
                   2033:
1.185     markus   2034: #ifdef WITH_OPENSSL
1.170     djm      2035:        OpenSSL_add_all_algorithms();
1.185     markus   2036: #endif
1.21      markus   2037:
1.258     djm      2038:        while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:")) != -1) {
1.21      markus   2039:                switch (ch) {
1.192     djm      2040:                case 'E':
                   2041:                        fingerprint_hash = ssh_digest_alg_by_name(optarg);
                   2042:                        if (fingerprint_hash == -1)
                   2043:                                fatal("Invalid hash algorithm \"%s\"", optarg);
                   2044:                        break;
1.21      markus   2045:                case 'c':
                   2046:                        if (s_flag)
                   2047:                                usage();
                   2048:                        c_flag++;
                   2049:                        break;
                   2050:                case 'k':
                   2051:                        k_flag++;
1.258     djm      2052:                        break;
                   2053:                case 'O':
                   2054:                        if (strcmp(optarg, "no-restrict-websafe") == 0)
1.292.4.1! bluhm    2055:                                restrict_websafe = 0;
        !          2056:                        else if (strcmp(optarg, "allow-remote-pkcs11") == 0)
        !          2057:                                remote_add_provider = 1;
1.258     djm      2058:                        else
                   2059:                                fatal("Unknown -O option");
1.21      markus   2060:                        break;
1.215     djm      2061:                case 'P':
1.260     djm      2062:                        if (allowed_providers != NULL)
1.215     djm      2063:                                fatal("-P option already specified");
1.260     djm      2064:                        allowed_providers = xstrdup(optarg);
1.215     djm      2065:                        break;
1.21      markus   2066:                case 's':
                   2067:                        if (c_flag)
                   2068:                                usage();
                   2069:                        s_flag++;
                   2070:                        break;
1.57      markus   2071:                case 'd':
1.201     djm      2072:                        if (d_flag || D_flag)
1.57      markus   2073:                                usage();
                   2074:                        d_flag++;
                   2075:                        break;
1.201     djm      2076:                case 'D':
                   2077:                        if (d_flag || D_flag)
                   2078:                                usage();
                   2079:                        D_flag++;
                   2080:                        break;
1.86      markus   2081:                case 'a':
                   2082:                        agentsocket = optarg;
1.106     marc     2083:                        break;
                   2084:                case 't':
                   2085:                        if ((lifetime = convtime(optarg)) == -1) {
                   2086:                                fprintf(stderr, "Invalid lifetime\n");
                   2087:                                usage();
                   2088:                        }
1.86      markus   2089:                        break;
1.21      markus   2090:                default:
                   2091:                        usage();
                   2092:                }
                   2093:        }
                   2094:        ac -= optind;
                   2095:        av += optind;
                   2096:
1.201     djm      2097:        if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1.21      markus   2098:                usage();
                   2099:
1.260     djm      2100:        if (allowed_providers == NULL)
1.262     djm      2101:                allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
1.215     djm      2102:
1.85      markus   2103:        if (ac == 0 && !c_flag && !s_flag) {
1.21      markus   2104:                shell = getenv("SHELL");
1.161     tobias   2105:                if (shell != NULL && (len = strlen(shell)) > 2 &&
                   2106:                    strncmp(shell + len - 3, "csh", 3) == 0)
1.21      markus   2107:                        c_flag = 1;
                   2108:        }
                   2109:        if (k_flag) {
1.136     deraadt  2110:                const char *errstr = NULL;
                   2111:
1.21      markus   2112:                pidstr = getenv(SSH_AGENTPID_ENV_NAME);
                   2113:                if (pidstr == NULL) {
                   2114:                        fprintf(stderr, "%s not set, cannot kill agent\n",
1.46      markus   2115:                            SSH_AGENTPID_ENV_NAME);
1.21      markus   2116:                        exit(1);
                   2117:                }
1.136     deraadt  2118:                pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
                   2119:                if (errstr) {
                   2120:                        fprintf(stderr,
                   2121:                            "%s=\"%s\", which is not a good PID: %s\n",
                   2122:                            SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1.21      markus   2123:                        exit(1);
                   2124:                }
                   2125:                if (kill(pid, SIGTERM) == -1) {
                   2126:                        perror("kill");
                   2127:                        exit(1);
                   2128:                }
                   2129:                format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1.140     djm      2130:                printf(format, SSH_AUTHSOCKET_ENV_NAME);
                   2131:                printf(format, SSH_AGENTPID_ENV_NAME);
1.91      mpech    2132:                printf("echo Agent pid %ld killed;\n", (long)pid);
1.21      markus   2133:                exit(0);
                   2134:        }
1.231     djm      2135:
                   2136:        /*
                   2137:         * Minimum file descriptors:
                   2138:         * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
                   2139:         * a few spare for libc / stack protectors / sanitisers, etc.
                   2140:         */
                   2141: #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
                   2142:        if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
1.232     djm      2143:                fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
1.231     djm      2144:                    __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
                   2145:        maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
                   2146:
1.21      markus   2147:        parent_pid = getpid();
                   2148:
1.86      markus   2149:        if (agentsocket == NULL) {
                   2150:                /* Create private directory for agent socket */
1.171     djm      2151:                mktemp_proto(socket_dir, sizeof(socket_dir));
1.86      markus   2152:                if (mkdtemp(socket_dir) == NULL) {
                   2153:                        perror("mkdtemp: private socket dir");
                   2154:                        exit(1);
                   2155:                }
1.91      mpech    2156:                snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
                   2157:                    (long)parent_pid);
1.86      markus   2158:        } else {
                   2159:                /* Try to use specified agent socket */
                   2160:                socket_dir[0] = '\0';
                   2161:                strlcpy(socket_name, agentsocket, sizeof socket_name);
1.21      markus   2162:        }
                   2163:
1.23      markus   2164:        /*
                   2165:         * Create socket early so it will exist before command gets run from
                   2166:         * the parent.
                   2167:         */
1.189     djm      2168:        prev_mask = umask(0177);
1.188     millert  2169:        sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1.21      markus   2170:        if (sock < 0) {
1.188     millert  2171:                /* XXX - unix_listener() calls error() not perror() */
1.121     djm      2172:                *socket_name = '\0'; /* Don't unlink any existing file */
1.21      markus   2173:                cleanup_exit(1);
                   2174:        }
1.189     djm      2175:        umask(prev_mask);
1.46      markus   2176:
1.23      markus   2177:        /*
                   2178:         * Fork, and have the parent execute the command, if any, or present
                   2179:         * the socket data.  The child continues as the authentication agent.
                   2180:         */
1.201     djm      2181:        if (D_flag || d_flag) {
                   2182:                log_init(__progname,
                   2183:                    d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
                   2184:                    SYSLOG_FACILITY_AUTH, 1);
1.57      markus   2185:                format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
                   2186:                printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
                   2187:                    SSH_AUTHSOCKET_ENV_NAME);
1.91      mpech    2188:                printf("echo Agent pid %ld;\n", (long)parent_pid);
1.210     dtucker  2189:                fflush(stdout);
1.57      markus   2190:                goto skip;
                   2191:        }
1.21      markus   2192:        pid = fork();
                   2193:        if (pid == -1) {
                   2194:                perror("fork");
1.81      stevesk  2195:                cleanup_exit(1);
1.21      markus   2196:        }
                   2197:        if (pid != 0) {         /* Parent - execute the given command. */
                   2198:                close(sock);
1.91      mpech    2199:                snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1.21      markus   2200:                if (ac == 0) {
                   2201:                        format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
                   2202:                        printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1.46      markus   2203:                            SSH_AUTHSOCKET_ENV_NAME);
1.21      markus   2204:                        printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1.46      markus   2205:                            SSH_AGENTPID_ENV_NAME);
1.91      mpech    2206:                        printf("echo Agent pid %ld;\n", (long)pid);
1.21      markus   2207:                        exit(0);
                   2208:                }
1.36      deraadt  2209:                if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
                   2210:                    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
                   2211:                        perror("setenv");
                   2212:                        exit(1);
                   2213:                }
1.21      markus   2214:                execvp(av[0], av);
                   2215:                perror(av[0]);
                   2216:                exit(1);
                   2217:        }
1.81      stevesk  2218:        /* child */
                   2219:        log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1.67      stevesk  2220:
                   2221:        if (setsid() == -1) {
1.81      stevesk  2222:                error("setsid: %s", strerror(errno));
1.67      stevesk  2223:                cleanup_exit(1);
                   2224:        }
                   2225:
                   2226:        (void)chdir("/");
1.265     djm      2227:        if (stdfd_devnull(1, 1, 1) == -1)
1.266     djm      2228:                error_f("stdfd_devnull failed");
1.21      markus   2229:
1.41      markus   2230:        /* deny core dumps, since memory contains unencrypted private keys */
                   2231:        rlim.rlim_cur = rlim.rlim_max = 0;
1.237     deraadt  2232:        if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
1.81      stevesk  2233:                error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1.21      markus   2234:                cleanup_exit(1);
                   2235:        }
1.57      markus   2236:
                   2237: skip:
1.187     djm      2238:
                   2239:        cleanup_pid = getpid();
1.163     markus   2240:
                   2241: #ifdef ENABLE_PKCS11
                   2242:        pkcs11_init(0);
                   2243: #endif
1.21      markus   2244:        new_socket(AUTH_SOCKET, sock);
1.155     dtucker  2245:        if (ac > 0)
                   2246:                parent_alive_interval = 10;
1.33      markus   2247:        idtab_init();
1.252     dtucker  2248:        ssh_signal(SIGPIPE, SIG_IGN);
                   2249:        ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
                   2250:        ssh_signal(SIGHUP, cleanup_handler);
                   2251:        ssh_signal(SIGTERM, cleanup_handler);
1.205     djm      2252:
1.215     djm      2253:        if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1.205     djm      2254:                fatal("%s: pledge: %s", __progname, strerror(errno));
1.66      markus   2255:
1.21      markus   2256:        while (1) {
1.231     djm      2257:                prepare_poll(&pfd, &npfd, &timeout, maxfds);
1.223     djm      2258:                result = poll(pfd, npfd, timeout);
1.154     dtucker  2259:                saved_errno = errno;
1.155     dtucker  2260:                if (parent_alive_interval != 0)
                   2261:                        check_parent_exists();
                   2262:                (void) reaper();        /* remove expired keys */
1.237     deraadt  2263:                if (result == -1) {
1.154     dtucker  2264:                        if (saved_errno == EINTR)
1.21      markus   2265:                                continue;
1.223     djm      2266:                        fatal("poll: %s", strerror(saved_errno));
1.154     dtucker  2267:                } else if (result > 0)
1.231     djm      2268:                        after_poll(pfd, npfd, maxfds);
1.15      markus   2269:        }
1.21      markus   2270:        /* NOTREACHED */
1.1       deraadt  2271: }