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

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