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

1.285   ! djm         1: /* $OpenBSD: ssh-agent.c,v 1.284 2022/01/01 01:55:30 jsg 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
1.284     jsg       440:         * authenticate *to* a host but not permitted for *use* beyond it.
1.281     djm       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.283     djm       717:        struct sshkey *key = NULL, *hostkey = 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.283     djm       746:                if (parse_userauth_request(data, key, &user, &sid,
                    747:                    &hostkey) != 0) {
1.281     djm       748:                        logit_f("refusing use of destination-constrained key "
                    749:                           "to sign an unidentified signature");
                    750:                        goto send;
                    751:                }
                    752:                /* XXX logspam */
                    753:                debug_f("user=%s", user);
                    754:                if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0)
                    755:                        goto send;
                    756:                /* XXX display fwd_host/dest_host in askpass UI */
1.280     djm       757:                /*
1.281     djm       758:                 * Ensure that the session ID is the most recent one
                    759:                 * registered on the socket - it should have been bound by
                    760:                 * ssh immediately before userauth.
1.280     djm       761:                 */
1.281     djm       762:                if (buf_equal(sid,
                    763:                    e->session_ids[e->nsession_ids - 1].sid) != 0) {
                    764:                        error_f("unexpected session ID (%zu listed) on "
                    765:                            "signature request for target user %s with "
                    766:                            "key %s %s", e->nsession_ids, user,
                    767:                            sshkey_type(id->key), fp);
                    768:                        goto send;
1.280     djm       769:                }
1.283     djm       770:                /*
                    771:                 * Ensure that the hostkey embedded in the signature matches
                    772:                 * the one most recently bound to the socket. An exception is
                    773:                 * made for the initial forwarding hop.
                    774:                 */
                    775:                if (e->nsession_ids > 1 && hostkey == NULL) {
                    776:                        error_f("refusing use of destination-constrained key: "
                    777:                            "no hostkey recorded in signature for forwarded "
                    778:                            "connection");
                    779:                        goto send;
                    780:                }
                    781:                if (hostkey != NULL && !sshkey_equal(hostkey,
                    782:                    e->session_ids[e->nsession_ids - 1].key)) {
                    783:                        error_f("refusing use of destination-constrained key: "
                    784:                            "mismatch between hostkey in request and most "
                    785:                            "recently bound session");
                    786:                        goto send;
                    787:                }
1.281     djm       788:                xasprintf(&sig_dest, "public key authentication request for "
                    789:                    "user \"%s\" to listed host", user);
1.280     djm       790:        }
                    791:        if (id->confirm && confirm_key(id, sig_dest) != 0) {
1.266     djm       792:                verbose_f("user refused key");
1.195     djm       793:                goto send;
                    794:        }
1.258     djm       795:        if (sshkey_is_sk(id->key)) {
                    796:                if (strncmp(id->key->sk_application, "ssh:", 4) != 0 &&
1.270     djm       797:                    !check_websafe_message_contents(key, data)) {
1.258     djm       798:                        /* error already logged */
                    799:                        goto send;
                    800:                }
                    801:                if ((id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
                    802:                        notifier = notify_start(0,
1.280     djm       803:                            "Confirm user presence for key %s %s%s%s",
                    804:                            sshkey_type(id->key), fp,
                    805:                            sig_dest == NULL ? "" : "\n",
                    806:                            sig_dest == NULL ? "" : sig_dest);
1.258     djm       807:                }
1.251     djm       808:        }
1.263     djm       809:        /* XXX support PIN required FIDO keys */
1.251     djm       810:        if ((r = sshkey_sign(id->key, &signature, &slen,
1.270     djm       811:            sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
1.263     djm       812:            id->sk_provider, NULL, compat)) != 0) {
1.266     djm       813:                error_fr(r, "sshkey_sign");
1.251     djm       814:                goto send;
1.33      markus    815:        }
1.195     djm       816:        /* Success */
                    817:        ok = 0;
                    818:  send:
1.267     djm       819:        notify_complete(notifier, "User presence confirmed");
1.270     djm       820:
1.33      markus    821:        if (ok == 0) {
1.194     markus    822:                if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
                    823:                    (r = sshbuf_put_string(msg, signature, slen)) != 0)
1.266     djm       824:                        fatal_fr(r, "compose");
1.194     markus    825:        } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
1.266     djm       826:                fatal_fr(r, "compose failure");
1.194     markus    827:
                    828:        if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
1.266     djm       829:                fatal_fr(r, "enqueue");
1.194     markus    830:
1.280     djm       831:        sshbuf_free(sid);
1.270     djm       832:        sshbuf_free(data);
1.194     markus    833:        sshbuf_free(msg);
1.270     djm       834:        sshkey_free(key);
1.283     djm       835:        sshkey_free(hostkey);
1.270     djm       836:        free(fp);
1.173     djm       837:        free(signature);
1.280     djm       838:        free(sig_dest);
                    839:        free(user);
1.1       deraadt   840: }
                    841:
1.33      markus    842: /* shared */
1.55      itojun    843: static void
1.221     djm       844: process_remove_identity(SocketEntry *e)
1.1       deraadt   845: {
1.194     markus    846:        int r, success = 0;
                    847:        struct sshkey *key = NULL;
1.221     djm       848:        Identity *id;
1.21      markus    849:
1.269     djm       850:        debug2_f("entering");
1.221     djm       851:        if ((r = sshkey_froms(e->request, &key)) != 0) {
1.266     djm       852:                error_fr(r, "parse key");
1.221     djm       853:                goto done;
                    854:        }
                    855:        if ((id = lookup_identity(key)) == NULL) {
1.266     djm       856:                debug_f("key not found");
1.221     djm       857:                goto done;
                    858:        }
1.281     djm       859:        /* identity not visible, cannot be removed */
                    860:        if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
                    861:                goto done; /* error already logged */
1.221     djm       862:        /* We have this key, free it. */
                    863:        if (idtab->nentries < 1)
1.266     djm       864:                fatal_f("internal error: nentries %d", idtab->nentries);
1.221     djm       865:        TAILQ_REMOVE(&idtab->idlist, id, next);
                    866:        free_identity(id);
                    867:        idtab->nentries--;
                    868:        success = 1;
                    869:  done:
1.276     djm       870:        sshkey_free(key);
1.194     markus    871:        send_status(e, success);
1.1       deraadt   872: }
                    873:
1.55      itojun    874: static void
1.221     djm       875: process_remove_all_identities(SocketEntry *e)
1.1       deraadt   876: {
1.78      provos    877:        Identity *id;
1.21      markus    878:
1.269     djm       879:        debug2_f("entering");
1.21      markus    880:        /* Loop over all identities and clear the keys. */
1.221     djm       881:        for (id = TAILQ_FIRST(&idtab->idlist); id;
                    882:            id = TAILQ_FIRST(&idtab->idlist)) {
                    883:                TAILQ_REMOVE(&idtab->idlist, id, next);
1.78      provos    884:                free_identity(id);
1.21      markus    885:        }
                    886:
                    887:        /* Mark that there are no identities. */
1.221     djm       888:        idtab->nentries = 0;
1.21      markus    889:
                    890:        /* Send success. */
1.194     markus    891:        send_status(e, 1);
1.1       deraadt   892: }
                    893:
1.155     dtucker   894: /* removes expired keys and returns number of seconds until the next expiry */
1.174     dtucker   895: static time_t
1.89      markus    896: reaper(void)
                    897: {
1.175     dtucker   898:        time_t deadline = 0, now = monotime();
1.89      markus    899:        Identity *id, *nxt;
                    900:
1.221     djm       901:        for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
                    902:                nxt = TAILQ_NEXT(id, next);
                    903:                if (id->death == 0)
                    904:                        continue;
                    905:                if (now >= id->death) {
                    906:                        debug("expiring key '%s'", id->comment);
                    907:                        TAILQ_REMOVE(&idtab->idlist, id, next);
                    908:                        free_identity(id);
                    909:                        idtab->nentries--;
                    910:                } else
                    911:                        deadline = (deadline == 0) ? id->death :
                    912:                            MINIMUM(deadline, id->death);
1.89      markus    913:        }
1.155     dtucker   914:        if (deadline == 0 || deadline <= now)
                    915:                return 0;
                    916:        else
                    917:                return (deadline - now);
1.89      markus    918: }
                    919:
1.271     djm       920: static int
1.281     djm       921: parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch)
                    922: {
                    923:        u_char key_is_ca;
                    924:        size_t elen = 0;
                    925:        int r;
                    926:        struct sshkey *k = NULL;
                    927:        char *fp;
                    928:
                    929:        memset(dch, '\0', sizeof(*dch));
                    930:        if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 ||
                    931:            (r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 ||
                    932:            (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
                    933:                error_fr(r, "parse");
                    934:                goto out;
                    935:        }
                    936:        if (elen != 0) {
                    937:                error_f("unsupported extensions (len %zu)", elen);
                    938:                r = SSH_ERR_FEATURE_UNSUPPORTED;
                    939:                goto out;
                    940:        }
                    941:        if (*dch->hostname == '\0') {
                    942:                free(dch->hostname);
                    943:                dch->hostname = NULL;
                    944:        }
                    945:        if (*dch->user == '\0') {
                    946:                free(dch->user);
                    947:                dch->user = NULL;
                    948:        }
                    949:        while (sshbuf_len(b) != 0) {
                    950:                dch->keys = xrecallocarray(dch->keys, dch->nkeys,
                    951:                    dch->nkeys + 1, sizeof(*dch->keys));
                    952:                dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
                    953:                    dch->nkeys + 1, sizeof(*dch->key_is_ca));
                    954:                if ((r = sshkey_froms(b, &k)) != 0 ||
                    955:                    (r = sshbuf_get_u8(b, &key_is_ca)) != 0)
                    956:                        goto out;
                    957:                if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
                    958:                    SSH_FP_DEFAULT)) == NULL)
                    959:                        fatal_f("fingerprint failed");
                    960:                debug3_f("%s%s%s: adding %skey %s %s",
                    961:                    dch->user == NULL ? "" : dch->user,
                    962:                    dch->user == NULL ? "" : "@",
                    963:                    dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp);
                    964:                free(fp);
                    965:                dch->keys[dch->nkeys] = k;
                    966:                dch->key_is_ca[dch->nkeys] = key_is_ca != 0;
                    967:                dch->nkeys++;
                    968:                k = NULL; /* transferred */
                    969:        }
                    970:        /* success */
                    971:        r = 0;
                    972:  out:
                    973:        sshkey_free(k);
                    974:        return r;
                    975: }
                    976:
                    977: static int
                    978: parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc)
                    979: {
                    980:        struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL;
                    981:        int r;
                    982:        size_t elen = 0;
                    983:
                    984:        debug3_f("entering");
                    985:
                    986:        memset(dc, '\0', sizeof(*dc));
                    987:        if ((r = sshbuf_froms(m, &b)) != 0 ||
                    988:            (r = sshbuf_froms(b, &frombuf)) != 0 ||
                    989:            (r = sshbuf_froms(b, &tobuf)) != 0 ||
                    990:            (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
                    991:                error_fr(r, "parse");
                    992:                goto out;
                    993:        }
                    994:        if ((r = parse_dest_constraint_hop(frombuf, &dc->from) != 0) ||
                    995:            (r = parse_dest_constraint_hop(tobuf, &dc->to) != 0))
                    996:                goto out; /* already logged */
                    997:        if (elen != 0) {
                    998:                error_f("unsupported extensions (len %zu)", elen);
                    999:                r = SSH_ERR_FEATURE_UNSUPPORTED;
                   1000:                goto out;
                   1001:        }
                   1002:        debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)",
                   1003:            dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
                   1004:            dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
                   1005:            dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
                   1006:        /* check consistency */
                   1007:        if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) ||
                   1008:            dc->from.user != NULL) {
                   1009:                error_f("inconsistent \"from\" specification");
                   1010:                r = SSH_ERR_INVALID_FORMAT;
                   1011:                goto out;
                   1012:        }
                   1013:        if (dc->to.hostname == NULL || dc->to.nkeys == 0) {
                   1014:                error_f("incomplete \"to\" specification");
                   1015:                r = SSH_ERR_INVALID_FORMAT;
                   1016:                goto out;
                   1017:        }
                   1018:        /* success */
                   1019:        r = 0;
                   1020:  out:
                   1021:        sshbuf_free(b);
                   1022:        sshbuf_free(frombuf);
                   1023:        sshbuf_free(tobuf);
                   1024:        return r;
                   1025: }
                   1026:
                   1027: static int
                   1028: parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp,
                   1029:     struct dest_constraint **dcsp, size_t *ndcsp)
1.277     djm      1030: {
                   1031:        char *ext_name = NULL;
                   1032:        int r;
1.281     djm      1033:        struct sshbuf *b = NULL;
1.277     djm      1034:
                   1035:        if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
                   1036:                error_fr(r, "parse constraint extension");
                   1037:                goto out;
                   1038:        }
                   1039:        debug_f("constraint ext %s", ext_name);
                   1040:        if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
                   1041:                if (sk_providerp == NULL) {
                   1042:                        error_f("%s not valid here", ext_name);
                   1043:                        r = SSH_ERR_INVALID_FORMAT;
                   1044:                        goto out;
                   1045:                }
                   1046:                if (*sk_providerp != NULL) {
                   1047:                        error_f("%s already set", ext_name);
                   1048:                        r = SSH_ERR_INVALID_FORMAT;
                   1049:                        goto out;
                   1050:                }
                   1051:                if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
                   1052:                        error_fr(r, "parse %s", ext_name);
                   1053:                        goto out;
                   1054:                }
1.281     djm      1055:        } else if (strcmp(ext_name,
                   1056:            "restrict-destination-v00@openssh.com") == 0) {
                   1057:                if (*dcsp != NULL) {
                   1058:                        error_f("%s already set", ext_name);
                   1059:                        goto out;
                   1060:                }
                   1061:                if ((r = sshbuf_froms(m, &b)) != 0) {
                   1062:                        error_fr(r, "parse %s outer", ext_name);
                   1063:                        goto out;
                   1064:                }
                   1065:                while (sshbuf_len(b) != 0) {
                   1066:                        if (*ndcsp >= AGENT_MAX_DEST_CONSTRAINTS) {
                   1067:                                error_f("too many %s constraints", ext_name);
                   1068:                                goto out;
                   1069:                        }
                   1070:                        *dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1,
                   1071:                            sizeof(**dcsp));
                   1072:                        if ((r = parse_dest_constraint(b,
                   1073:                            *dcsp + (*ndcsp)++)) != 0)
                   1074:                                goto out; /* error already logged */
                   1075:                }
1.277     djm      1076:        } else {
                   1077:                error_f("unsupported constraint \"%s\"", ext_name);
                   1078:                r = SSH_ERR_FEATURE_UNSUPPORTED;
                   1079:                goto out;
                   1080:        }
                   1081:        /* success */
                   1082:        r = 0;
                   1083:  out:
                   1084:        free(ext_name);
1.281     djm      1085:        sshbuf_free(b);
1.277     djm      1086:        return r;
                   1087: }
                   1088:
                   1089: static int
1.271     djm      1090: parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
1.281     djm      1091:     u_int *secondsp, int *confirmp, char **sk_providerp,
                   1092:     struct dest_constraint **dcsp, size_t *ndcsp)
1.1       deraadt  1093: {
1.194     markus   1094:        u_char ctype;
1.271     djm      1095:        int r;
                   1096:        u_int seconds, maxsign = 0;
1.33      markus   1097:
1.271     djm      1098:        while (sshbuf_len(m)) {
                   1099:                if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
1.266     djm      1100:                        error_fr(r, "parse constraint type");
1.277     djm      1101:                        goto out;
1.194     markus   1102:                }
                   1103:                switch (ctype) {
1.94      markus   1104:                case SSH_AGENT_CONSTRAIN_LIFETIME:
1.271     djm      1105:                        if (*deathp != 0) {
                   1106:                                error_f("lifetime already set");
1.277     djm      1107:                                r = SSH_ERR_INVALID_FORMAT;
                   1108:                                goto out;
1.271     djm      1109:                        }
                   1110:                        if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
1.266     djm      1111:                                error_fr(r, "parse lifetime constraint");
1.277     djm      1112:                                goto out;
1.194     markus   1113:                        }
1.271     djm      1114:                        *deathp = monotime() + seconds;
                   1115:                        *secondsp = seconds;
1.94      markus   1116:                        break;
1.107     markus   1117:                case SSH_AGENT_CONSTRAIN_CONFIRM:
1.271     djm      1118:                        if (*confirmp != 0) {
                   1119:                                error_f("confirm already set");
1.277     djm      1120:                                r = SSH_ERR_INVALID_FORMAT;
                   1121:                                goto out;
1.271     djm      1122:                        }
                   1123:                        *confirmp = 1;
1.107     markus   1124:                        break;
1.228     markus   1125:                case SSH_AGENT_CONSTRAIN_MAXSIGN:
1.271     djm      1126:                        if (k == NULL) {
                   1127:                                error_f("maxsign not valid here");
1.277     djm      1128:                                r = SSH_ERR_INVALID_FORMAT;
                   1129:                                goto out;
1.271     djm      1130:                        }
                   1131:                        if (maxsign != 0) {
                   1132:                                error_f("maxsign already set");
1.277     djm      1133:                                r = SSH_ERR_INVALID_FORMAT;
                   1134:                                goto out;
1.271     djm      1135:                        }
                   1136:                        if ((r = sshbuf_get_u32(m, &maxsign)) != 0) {
1.266     djm      1137:                                error_fr(r, "parse maxsign constraint");
1.277     djm      1138:                                goto out;
1.228     markus   1139:                        }
                   1140:                        if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
1.266     djm      1141:                                error_fr(r, "enable maxsign");
1.277     djm      1142:                                goto out;
1.228     markus   1143:                        }
                   1144:                        break;
1.238     djm      1145:                case SSH_AGENT_CONSTRAIN_EXTENSION:
1.277     djm      1146:                        if ((r = parse_key_constraint_extension(m,
1.281     djm      1147:                            sk_providerp, dcsp, ndcsp)) != 0)
1.277     djm      1148:                                goto out; /* error already logged */
1.238     djm      1149:                        break;
1.94      markus   1150:                default:
1.266     djm      1151:                        error_f("Unknown constraint %d", ctype);
1.277     djm      1152:                        r = SSH_ERR_FEATURE_UNSUPPORTED;
                   1153:                        goto out;
1.94      markus   1154:                }
                   1155:        }
1.271     djm      1156:        /* success */
1.277     djm      1157:        r = 0;
                   1158:  out:
                   1159:        return r;
1.271     djm      1160: }
                   1161:
                   1162: static void
                   1163: process_add_identity(SocketEntry *e)
                   1164: {
                   1165:        Identity *id;
                   1166:        int success = 0, confirm = 0;
1.272     dtucker  1167:        char *fp, *comment = NULL, *sk_provider = NULL;
1.271     djm      1168:        char canonical_provider[PATH_MAX];
                   1169:        time_t death = 0;
                   1170:        u_int seconds = 0;
1.281     djm      1171:        struct dest_constraint *dest_constraints = NULL;
                   1172:        size_t ndest_constraints = 0;
1.271     djm      1173:        struct sshkey *k = NULL;
                   1174:        int r = SSH_ERR_INTERNAL_ERROR;
                   1175:
                   1176:        debug2_f("entering");
                   1177:        if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
                   1178:            k == NULL ||
                   1179:            (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
                   1180:                error_fr(r, "parse");
                   1181:                goto out;
                   1182:        }
                   1183:        if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
1.281     djm      1184:            &sk_provider, &dest_constraints, &ndest_constraints) != 0) {
1.271     djm      1185:                error_f("failed to parse constraints");
                   1186:                sshbuf_reset(e->request);
                   1187:                goto out;
                   1188:        }
                   1189:
1.238     djm      1190:        if (sk_provider != NULL) {
1.240     markus   1191:                if (!sshkey_is_sk(k)) {
1.255     naddy    1192:                        error("Cannot add provider: %s is not an "
                   1193:                            "authenticator-hosted key", sshkey_type(k));
1.271     djm      1194:                        goto out;
1.238     djm      1195:                }
1.254     djm      1196:                if (strcasecmp(sk_provider, "internal") == 0) {
1.266     djm      1197:                        debug_f("internal provider");
1.254     djm      1198:                } else {
                   1199:                        if (realpath(sk_provider, canonical_provider) == NULL) {
                   1200:                                verbose("failed provider \"%.100s\": "
                   1201:                                    "realpath: %s", sk_provider,
                   1202:                                    strerror(errno));
1.271     djm      1203:                                goto out;
1.254     djm      1204:                        }
1.238     djm      1205:                        free(sk_provider);
1.254     djm      1206:                        sk_provider = xstrdup(canonical_provider);
                   1207:                        if (match_pattern_list(sk_provider,
1.260     djm      1208:                            allowed_providers, 0) != 1) {
1.254     djm      1209:                                error("Refusing add key: "
1.260     djm      1210:                                    "provider %s not allowed", sk_provider);
1.271     djm      1211:                                goto out;
1.254     djm      1212:                        }
1.238     djm      1213:                }
1.242     markus   1214:        }
                   1215:        if ((r = sshkey_shield_private(k)) != 0) {
1.266     djm      1216:                error_fr(r, "shield private");
1.271     djm      1217:                goto out;
1.238     djm      1218:        }
1.106     marc     1219:        if (lifetime && !death)
1.175     dtucker  1220:                death = monotime() + lifetime;
1.221     djm      1221:        if ((id = lookup_identity(k)) == NULL) {
1.163     markus   1222:                id = xcalloc(1, sizeof(Identity));
1.221     djm      1223:                TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1.33      markus   1224:                /* Increment the number of identities. */
1.221     djm      1225:                idtab->nentries++;
1.33      markus   1226:        } else {
1.281     djm      1227:                /* identity not visible, do not update */
                   1228:                if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
                   1229:                        goto out; /* error already logged */
1.228     markus   1230:                /* key state might have been updated */
                   1231:                sshkey_free(id->key);
1.173     djm      1232:                free(id->comment);
1.238     djm      1233:                free(id->sk_provider);
1.281     djm      1234:                free_dest_constraints(id->dest_constraints,
                   1235:                    id->ndest_constraints);
1.33      markus   1236:        }
1.271     djm      1237:        /* success */
1.228     markus   1238:        id->key = k;
1.157     canacar  1239:        id->comment = comment;
                   1240:        id->death = death;
                   1241:        id->confirm = confirm;
1.238     djm      1242:        id->sk_provider = sk_provider;
1.281     djm      1243:        id->dest_constraints = dest_constraints;
                   1244:        id->ndest_constraints = ndest_constraints;
1.238     djm      1245:
                   1246:        if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
                   1247:            SSH_FP_DEFAULT)) == NULL)
1.266     djm      1248:                fatal_f("sshkey_fingerprint failed");
                   1249:        debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
1.281     djm      1250:            "(provider: %s) (destination constraints: %zu)",
                   1251:            sshkey_ssh_name(k), fp, comment, seconds, confirm,
                   1252:            sk_provider == NULL ? "none" : sk_provider, ndest_constraints);
1.238     djm      1253:        free(fp);
1.271     djm      1254:        /* transferred */
                   1255:        k = NULL;
                   1256:        comment = NULL;
                   1257:        sk_provider = NULL;
1.281     djm      1258:        dest_constraints = NULL;
                   1259:        ndest_constraints = 0;
1.271     djm      1260:        success = 1;
                   1261:  out:
                   1262:        free(sk_provider);
                   1263:        free(comment);
                   1264:        sshkey_free(k);
1.281     djm      1265:        free_dest_constraints(dest_constraints, ndest_constraints);
1.194     markus   1266:        send_status(e, success);
1.1       deraadt  1267: }
                   1268:
1.88      markus   1269: /* XXX todo: encrypt sensitive data with passphrase */
                   1270: static void
                   1271: process_lock_agent(SocketEntry *e, int lock)
                   1272: {
1.203     dtucker  1273:        int r, success = 0, delay;
1.213     djm      1274:        char *passwd;
                   1275:        u_char passwdhash[LOCK_SIZE];
1.203     dtucker  1276:        static u_int fail_count = 0;
                   1277:        size_t pwlen;
                   1278:
1.269     djm      1279:        debug2_f("entering");
1.226     djm      1280:        /*
                   1281:         * This is deliberately fatal: the user has requested that we lock,
                   1282:         * but we can't parse their request properly. The only safe thing to
                   1283:         * do is abort.
                   1284:         */
1.203     dtucker  1285:        if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
1.266     djm      1286:                fatal_fr(r, "parse");
1.203     dtucker  1287:        if (pwlen == 0) {
                   1288:                debug("empty password not supported");
                   1289:        } else if (locked && !lock) {
                   1290:                if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
                   1291:                    passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
                   1292:                        fatal("bcrypt_pbkdf");
1.213     djm      1293:                if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
1.203     dtucker  1294:                        debug("agent unlocked");
                   1295:                        locked = 0;
                   1296:                        fail_count = 0;
1.213     djm      1297:                        explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
1.203     dtucker  1298:                        success = 1;
                   1299:                } else {
                   1300:                        /* delay in 0.1s increments up to 10s */
                   1301:                        if (fail_count < 100)
                   1302:                                fail_count++;
                   1303:                        delay = 100000 * fail_count;
                   1304:                        debug("unlock failed, delaying %0.1lf seconds",
                   1305:                            (double)delay/1000000);
                   1306:                        usleep(delay);
                   1307:                }
                   1308:                explicit_bzero(passwdhash, sizeof(passwdhash));
1.88      markus   1309:        } else if (!locked && lock) {
1.203     dtucker  1310:                debug("agent locked");
1.88      markus   1311:                locked = 1;
1.203     dtucker  1312:                arc4random_buf(lock_salt, sizeof(lock_salt));
                   1313:                if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1.213     djm      1314:                    lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
1.203     dtucker  1315:                        fatal("bcrypt_pbkdf");
1.88      markus   1316:                success = 1;
                   1317:        }
1.256     jsg      1318:        freezero(passwd, pwlen);
1.194     markus   1319:        send_status(e, success);
1.88      markus   1320: }
                   1321:
                   1322: static void
1.221     djm      1323: no_identities(SocketEntry *e)
1.88      markus   1324: {
1.194     markus   1325:        struct sshbuf *msg;
                   1326:        int r;
1.88      markus   1327:
1.194     markus   1328:        if ((msg = sshbuf_new()) == NULL)
1.266     djm      1329:                fatal_f("sshbuf_new failed");
1.221     djm      1330:        if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
1.194     markus   1331:            (r = sshbuf_put_u32(msg, 0)) != 0 ||
                   1332:            (r = sshbuf_put_stringb(e->output, msg)) != 0)
1.266     djm      1333:                fatal_fr(r, "compose");
1.194     markus   1334:        sshbuf_free(msg);
1.88      markus   1335: }
1.59      markus   1336:
1.163     markus   1337: #ifdef ENABLE_PKCS11
1.59      markus   1338: static void
1.158     djm      1339: process_add_smartcard_key(SocketEntry *e)
1.59      markus   1340: {
1.226     djm      1341:        char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1.253     djm      1342:        char **comments = NULL;
1.221     djm      1343:        int r, i, count = 0, success = 0, confirm = 0;
1.271     djm      1344:        u_int seconds = 0;
1.174     dtucker  1345:        time_t death = 0;
1.194     markus   1346:        struct sshkey **keys = NULL, *k;
1.84      markus   1347:        Identity *id;
1.281     djm      1348:        struct dest_constraint *dest_constraints = NULL;
                   1349:        size_t ndest_constraints = 0;
1.75      deraadt  1350:
1.269     djm      1351:        debug2_f("entering");
1.194     markus   1352:        if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1.226     djm      1353:            (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1.266     djm      1354:                error_fr(r, "parse");
1.226     djm      1355:                goto send;
                   1356:        }
1.271     djm      1357:        if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
1.281     djm      1358:            NULL, &dest_constraints, &ndest_constraints) != 0) {
1.271     djm      1359:                error_f("failed to parse constraints");
                   1360:                goto send;
1.110     djm      1361:        }
1.215     djm      1362:        if (realpath(provider, canonical_provider) == NULL) {
                   1363:                verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
                   1364:                    provider, strerror(errno));
                   1365:                goto send;
                   1366:        }
1.260     djm      1367:        if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
1.215     djm      1368:                verbose("refusing PKCS#11 add of \"%.100s\": "
1.260     djm      1369:                    "provider not allowed", canonical_provider);
1.215     djm      1370:                goto send;
                   1371:        }
1.266     djm      1372:        debug_f("add %.100s", canonical_provider);
1.110     djm      1373:        if (lifetime && !death)
1.175     dtucker  1374:                death = monotime() + lifetime;
1.110     djm      1375:
1.253     djm      1376:        count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
1.163     markus   1377:        for (i = 0; i < count; i++) {
1.84      markus   1378:                k = keys[i];
1.221     djm      1379:                if (lookup_identity(k) == NULL) {
1.163     markus   1380:                        id = xcalloc(1, sizeof(Identity));
1.84      markus   1381:                        id->key = k;
1.253     djm      1382:                        keys[i] = NULL; /* transferred */
1.215     djm      1383:                        id->provider = xstrdup(canonical_provider);
1.253     djm      1384:                        if (*comments[i] != '\0') {
                   1385:                                id->comment = comments[i];
                   1386:                                comments[i] = NULL; /* transferred */
                   1387:                        } else {
                   1388:                                id->comment = xstrdup(canonical_provider);
                   1389:                        }
1.110     djm      1390:                        id->death = death;
                   1391:                        id->confirm = confirm;
1.281     djm      1392:                        id->dest_constraints = dest_constraints;
                   1393:                        id->ndest_constraints = ndest_constraints;
                   1394:                        dest_constraints = NULL; /* transferred */
                   1395:                        ndest_constraints = 0;
1.221     djm      1396:                        TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
                   1397:                        idtab->nentries++;
1.84      markus   1398:                        success = 1;
                   1399:                }
1.271     djm      1400:                /* XXX update constraints for existing keys */
1.253     djm      1401:                sshkey_free(keys[i]);
                   1402:                free(comments[i]);
1.59      markus   1403:        }
                   1404: send:
1.173     djm      1405:        free(pin);
                   1406:        free(provider);
                   1407:        free(keys);
1.253     djm      1408:        free(comments);
1.281     djm      1409:        free_dest_constraints(dest_constraints, ndest_constraints);
1.194     markus   1410:        send_status(e, success);
1.59      markus   1411: }
                   1412:
                   1413: static void
                   1414: process_remove_smartcard_key(SocketEntry *e)
                   1415: {
1.217     djm      1416:        char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1.221     djm      1417:        int r, success = 0;
1.163     markus   1418:        Identity *id, *nxt;
1.59      markus   1419:
1.269     djm      1420:        debug2_f("entering");
1.194     markus   1421:        if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1.226     djm      1422:            (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1.266     djm      1423:                error_fr(r, "parse");
1.226     djm      1424:                goto send;
                   1425:        }
1.173     djm      1426:        free(pin);
1.59      markus   1427:
1.217     djm      1428:        if (realpath(provider, canonical_provider) == NULL) {
                   1429:                verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
                   1430:                    provider, strerror(errno));
                   1431:                goto send;
                   1432:        }
                   1433:
1.266     djm      1434:        debug_f("remove %.100s", canonical_provider);
1.221     djm      1435:        for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
                   1436:                nxt = TAILQ_NEXT(id, next);
                   1437:                /* Skip file--based keys */
                   1438:                if (id->provider == NULL)
                   1439:                        continue;
                   1440:                if (!strcmp(canonical_provider, id->provider)) {
                   1441:                        TAILQ_REMOVE(&idtab->idlist, id, next);
                   1442:                        free_identity(id);
                   1443:                        idtab->nentries--;
1.59      markus   1444:                }
                   1445:        }
1.217     djm      1446:        if (pkcs11_del_provider(canonical_provider) == 0)
1.163     markus   1447:                success = 1;
                   1448:        else
1.266     djm      1449:                error_f("pkcs11_del_provider failed");
1.218     deraadt  1450: send:
1.173     djm      1451:        free(provider);
1.194     markus   1452:        send_status(e, success);
1.59      markus   1453: }
1.163     markus   1454: #endif /* ENABLE_PKCS11 */
1.59      markus   1455:
1.280     djm      1456: static int
                   1457: process_ext_session_bind(SocketEntry *e)
                   1458: {
                   1459:        int r, sid_match, key_match;
                   1460:        struct sshkey *key = NULL;
                   1461:        struct sshbuf *sid = NULL, *sig = NULL;
                   1462:        char *fp = NULL;
                   1463:        size_t i;
1.281     djm      1464:        u_char fwd = 0;
1.280     djm      1465:
                   1466:        debug2_f("entering");
                   1467:        if ((r = sshkey_froms(e->request, &key)) != 0 ||
                   1468:            (r = sshbuf_froms(e->request, &sid)) != 0 ||
                   1469:            (r = sshbuf_froms(e->request, &sig)) != 0 ||
                   1470:            (r = sshbuf_get_u8(e->request, &fwd)) != 0) {
                   1471:                error_fr(r, "parse");
                   1472:                goto out;
                   1473:        }
                   1474:        if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
                   1475:            SSH_FP_DEFAULT)) == NULL)
                   1476:                fatal_f("fingerprint failed");
                   1477:        /* check signature with hostkey on session ID */
                   1478:        if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig),
                   1479:            sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) {
                   1480:                error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp);
                   1481:                goto out;
                   1482:        }
                   1483:        /* check whether sid/key already recorded */
                   1484:        for (i = 0; i < e->nsession_ids; i++) {
1.281     djm      1485:                if (!e->session_ids[i].forwarded) {
                   1486:                        error_f("attempt to bind session ID to socket "
                   1487:                            "previously bound for authentication attempt");
                   1488:                        r = -1;
                   1489:                        goto out;
                   1490:                }
1.280     djm      1491:                sid_match = buf_equal(sid, e->session_ids[i].sid) == 0;
                   1492:                key_match = sshkey_equal(key, e->session_ids[i].key);
                   1493:                if (sid_match && key_match) {
                   1494:                        debug_f("session ID already recorded for %s %s",
                   1495:                            sshkey_type(key), fp);
                   1496:                        r = 0;
                   1497:                        goto out;
                   1498:                } else if (sid_match) {
                   1499:                        error_f("session ID recorded against different key "
                   1500:                            "for %s %s", sshkey_type(key), fp);
                   1501:                        r = -1;
                   1502:                        goto out;
                   1503:                }
                   1504:                /*
                   1505:                 * new sid with previously-seen key can happen, e.g. multiple
                   1506:                 * connections to the same host.
                   1507:                 */
                   1508:        }
                   1509:        /* record new key/sid */
                   1510:        if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) {
                   1511:                error_f("too many session IDs recorded");
                   1512:                goto out;
                   1513:        }
                   1514:        e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids,
                   1515:            e->nsession_ids + 1, sizeof(*e->session_ids));
                   1516:        i = e->nsession_ids++;
                   1517:        debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i,
                   1518:            AGENT_MAX_SESSION_IDS);
                   1519:        e->session_ids[i].key = key;
                   1520:        e->session_ids[i].forwarded = fwd != 0;
                   1521:        key = NULL; /* transferred */
                   1522:        /* can't transfer sid; it's refcounted and scoped to request's life */
                   1523:        if ((e->session_ids[i].sid = sshbuf_new()) == NULL)
                   1524:                fatal_f("sshbuf_new");
                   1525:        if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0)
                   1526:                fatal_fr(r, "sshbuf_putb session ID");
                   1527:        /* success */
                   1528:        r = 0;
                   1529:  out:
                   1530:        sshkey_free(key);
                   1531:        sshbuf_free(sid);
                   1532:        sshbuf_free(sig);
                   1533:        return r == 0 ? 1 : 0;
                   1534: }
                   1535:
                   1536: static void
                   1537: process_extension(SocketEntry *e)
                   1538: {
                   1539:        int r, success = 0;
                   1540:        char *name;
                   1541:
                   1542:        debug2_f("entering");
                   1543:        if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) {
                   1544:                error_fr(r, "parse");
                   1545:                goto send;
                   1546:        }
                   1547:        if (strcmp(name, "session-bind@openssh.com") == 0)
                   1548:                success = process_ext_session_bind(e);
                   1549:        else
                   1550:                debug_f("unsupported extension \"%s\"", name);
1.285   ! djm      1551:        free(name);
1.280     djm      1552: send:
                   1553:        send_status(e, success);
                   1554: }
1.264     djm      1555: /*
                   1556:  * dispatch incoming message.
                   1557:  * returns 1 on success, 0 for incomplete messages or -1 on error.
                   1558:  */
1.223     djm      1559: static int
                   1560: process_message(u_int socknum)
1.1       deraadt  1561: {
1.194     markus   1562:        u_int msg_len;
                   1563:        u_char type;
                   1564:        const u_char *cp;
                   1565:        int r;
1.223     djm      1566:        SocketEntry *e;
                   1567:
1.266     djm      1568:        if (socknum >= sockets_alloc)
                   1569:                fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
1.223     djm      1570:        e = &sockets[socknum];
1.89      markus   1571:
1.194     markus   1572:        if (sshbuf_len(e->input) < 5)
1.223     djm      1573:                return 0;               /* Incomplete message header. */
1.194     markus   1574:        cp = sshbuf_ptr(e->input);
                   1575:        msg_len = PEEK_U32(cp);
1.223     djm      1576:        if (msg_len > AGENT_MAX_LEN) {
1.266     djm      1577:                debug_f("socket %u (fd=%d) message too long %u > %u",
                   1578:                    socknum, e->fd, msg_len, AGENT_MAX_LEN);
1.223     djm      1579:                return -1;
1.21      markus   1580:        }
1.194     markus   1581:        if (sshbuf_len(e->input) < msg_len + 4)
1.223     djm      1582:                return 0;               /* Incomplete message body. */
1.87      markus   1583:
                   1584:        /* move the current input to e->request */
1.194     markus   1585:        sshbuf_reset(e->request);
                   1586:        if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1.223     djm      1587:            (r = sshbuf_get_u8(e->request, &type)) != 0) {
                   1588:                if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
                   1589:                    r == SSH_ERR_STRING_TOO_LARGE) {
1.266     djm      1590:                        error_fr(r, "parse");
1.223     djm      1591:                        return -1;
                   1592:                }
1.266     djm      1593:                fatal_fr(r, "parse");
1.223     djm      1594:        }
                   1595:
1.266     djm      1596:        debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1.21      markus   1597:
1.230     djm      1598:        /* check whether agent is locked */
1.88      markus   1599:        if (locked && type != SSH_AGENTC_UNLOCK) {
1.194     markus   1600:                sshbuf_reset(e->request);
1.88      markus   1601:                switch (type) {
                   1602:                case SSH2_AGENTC_REQUEST_IDENTITIES:
                   1603:                        /* send empty lists */
1.221     djm      1604:                        no_identities(e);
1.88      markus   1605:                        break;
                   1606:                default:
                   1607:                        /* send a fail message for all other request types */
1.194     markus   1608:                        send_status(e, 0);
1.88      markus   1609:                }
1.264     djm      1610:                return 1;
1.88      markus   1611:        }
                   1612:
1.21      markus   1613:        switch (type) {
1.88      markus   1614:        case SSH_AGENTC_LOCK:
                   1615:        case SSH_AGENTC_UNLOCK:
                   1616:                process_lock_agent(e, type == SSH_AGENTC_LOCK);
                   1617:                break;
1.21      markus   1618:        case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1.221     djm      1619:                process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1.33      markus   1620:                break;
                   1621:        /* ssh2 */
                   1622:        case SSH2_AGENTC_SIGN_REQUEST:
                   1623:                process_sign_request2(e);
                   1624:                break;
                   1625:        case SSH2_AGENTC_REQUEST_IDENTITIES:
1.221     djm      1626:                process_request_identities(e);
1.33      markus   1627:                break;
                   1628:        case SSH2_AGENTC_ADD_IDENTITY:
1.94      markus   1629:        case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1.221     djm      1630:                process_add_identity(e);
1.33      markus   1631:                break;
                   1632:        case SSH2_AGENTC_REMOVE_IDENTITY:
1.221     djm      1633:                process_remove_identity(e);
1.33      markus   1634:                break;
                   1635:        case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1.221     djm      1636:                process_remove_all_identities(e);
1.21      markus   1637:                break;
1.163     markus   1638: #ifdef ENABLE_PKCS11
1.59      markus   1639:        case SSH_AGENTC_ADD_SMARTCARD_KEY:
1.110     djm      1640:        case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1.59      markus   1641:                process_add_smartcard_key(e);
1.75      deraadt  1642:                break;
1.59      markus   1643:        case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
                   1644:                process_remove_smartcard_key(e);
1.75      deraadt  1645:                break;
1.163     markus   1646: #endif /* ENABLE_PKCS11 */
1.280     djm      1647:        case SSH_AGENTC_EXTENSION:
                   1648:                process_extension(e);
                   1649:                break;
1.21      markus   1650:        default:
                   1651:                /* Unknown message.  Respond with failure. */
                   1652:                error("Unknown message %d", type);
1.194     markus   1653:                sshbuf_reset(e->request);
                   1654:                send_status(e, 0);
1.21      markus   1655:                break;
                   1656:        }
1.264     djm      1657:        return 1;
1.1       deraadt  1658: }
                   1659:
1.55      itojun   1660: static void
1.73      stevesk  1661: new_socket(sock_type type, int fd)
1.1       deraadt  1662: {
1.112     markus   1663:        u_int i, old_alloc, new_alloc;
1.96      deraadt  1664:
1.269     djm      1665:        debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
                   1666:            (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1.119     djm      1667:        set_nonblock(fd);
1.21      markus   1668:
                   1669:        if (fd > max_fd)
                   1670:                max_fd = fd;
                   1671:
                   1672:        for (i = 0; i < sockets_alloc; i++)
                   1673:                if (sockets[i].type == AUTH_UNUSED) {
                   1674:                        sockets[i].fd = fd;
1.266     djm      1675:                        if ((sockets[i].input = sshbuf_new()) == NULL ||
                   1676:                            (sockets[i].output = sshbuf_new()) == NULL ||
                   1677:                            (sockets[i].request = sshbuf_new()) == NULL)
                   1678:                                fatal_f("sshbuf_new failed");
1.112     markus   1679:                        sockets[i].type = type;
1.21      markus   1680:                        return;
                   1681:                }
                   1682:        old_alloc = sockets_alloc;
1.112     markus   1683:        new_alloc = sockets_alloc + 10;
1.269     djm      1684:        sockets = xrecallocarray(sockets, old_alloc, new_alloc,
                   1685:            sizeof(sockets[0]));
1.112     markus   1686:        for (i = old_alloc; i < new_alloc; i++)
1.21      markus   1687:                sockets[i].type = AUTH_UNUSED;
1.112     markus   1688:        sockets_alloc = new_alloc;
1.21      markus   1689:        sockets[old_alloc].fd = fd;
1.266     djm      1690:        if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
                   1691:            (sockets[old_alloc].output = sshbuf_new()) == NULL ||
                   1692:            (sockets[old_alloc].request = sshbuf_new()) == NULL)
                   1693:                fatal_f("sshbuf_new failed");
1.112     markus   1694:        sockets[old_alloc].type = type;
1.1       deraadt  1695: }
                   1696:
1.55      itojun   1697: static int
1.223     djm      1698: handle_socket_read(u_int socknum)
1.1       deraadt  1699: {
1.223     djm      1700:        struct sockaddr_un sunaddr;
                   1701:        socklen_t slen;
                   1702:        uid_t euid;
                   1703:        gid_t egid;
                   1704:        int fd;
                   1705:
                   1706:        slen = sizeof(sunaddr);
                   1707:        fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1.237     deraadt  1708:        if (fd == -1) {
1.223     djm      1709:                error("accept from AUTH_SOCKET: %s", strerror(errno));
                   1710:                return -1;
                   1711:        }
1.237     deraadt  1712:        if (getpeereid(fd, &euid, &egid) == -1) {
1.223     djm      1713:                error("getpeereid %d failed: %s", fd, strerror(errno));
                   1714:                close(fd);
                   1715:                return -1;
                   1716:        }
                   1717:        if ((euid != 0) && (getuid() != euid)) {
                   1718:                error("uid mismatch: peer euid %u != uid %u",
                   1719:                    (u_int) euid, (u_int) getuid());
                   1720:                close(fd);
                   1721:                return -1;
                   1722:        }
                   1723:        new_socket(AUTH_CONNECTION, fd);
                   1724:        return 0;
                   1725: }
                   1726:
                   1727: static int
                   1728: handle_conn_read(u_int socknum)
                   1729: {
1.233     djm      1730:        char buf[AGENT_RBUF_LEN];
1.223     djm      1731:        ssize_t len;
                   1732:        int r;
                   1733:
                   1734:        if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
                   1735:                if (len == -1) {
                   1736:                        if (errno == EAGAIN || errno == EINTR)
                   1737:                                return 0;
1.266     djm      1738:                        error_f("read error on socket %u (fd %d): %s",
                   1739:                            socknum, sockets[socknum].fd, strerror(errno));
1.223     djm      1740:                }
                   1741:                return -1;
                   1742:        }
                   1743:        if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1.266     djm      1744:                fatal_fr(r, "compose");
1.223     djm      1745:        explicit_bzero(buf, sizeof(buf));
1.264     djm      1746:        for (;;) {
                   1747:                if ((r = process_message(socknum)) == -1)
                   1748:                        return -1;
                   1749:                else if (r == 0)
                   1750:                        break;
                   1751:        }
1.223     djm      1752:        return 0;
                   1753: }
                   1754:
                   1755: static int
                   1756: handle_conn_write(u_int socknum)
                   1757: {
                   1758:        ssize_t len;
                   1759:        int r;
                   1760:
                   1761:        if (sshbuf_len(sockets[socknum].output) == 0)
                   1762:                return 0; /* shouldn't happen */
                   1763:        if ((len = write(sockets[socknum].fd,
                   1764:            sshbuf_ptr(sockets[socknum].output),
                   1765:            sshbuf_len(sockets[socknum].output))) <= 0) {
                   1766:                if (len == -1) {
                   1767:                        if (errno == EAGAIN || errno == EINTR)
                   1768:                                return 0;
1.266     djm      1769:                        error_f("read error on socket %u (fd %d): %s",
                   1770:                            socknum, sockets[socknum].fd, strerror(errno));
1.223     djm      1771:                }
                   1772:                return -1;
                   1773:        }
                   1774:        if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
1.266     djm      1775:                fatal_fr(r, "consume");
1.223     djm      1776:        return 0;
                   1777: }
                   1778:
                   1779: static void
1.231     djm      1780: after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
1.223     djm      1781: {
                   1782:        size_t i;
1.231     djm      1783:        u_int socknum, activefds = npfd;
1.223     djm      1784:
                   1785:        for (i = 0; i < npfd; i++) {
                   1786:                if (pfd[i].revents == 0)
                   1787:                        continue;
                   1788:                /* Find sockets entry */
                   1789:                for (socknum = 0; socknum < sockets_alloc; socknum++) {
                   1790:                        if (sockets[socknum].type != AUTH_SOCKET &&
                   1791:                            sockets[socknum].type != AUTH_CONNECTION)
                   1792:                                continue;
                   1793:                        if (pfd[i].fd == sockets[socknum].fd)
                   1794:                                break;
                   1795:                }
                   1796:                if (socknum >= sockets_alloc) {
1.266     djm      1797:                        error_f("no socket for fd %d", pfd[i].fd);
1.223     djm      1798:                        continue;
                   1799:                }
                   1800:                /* Process events */
                   1801:                switch (sockets[socknum].type) {
                   1802:                case AUTH_SOCKET:
1.231     djm      1803:                        if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
                   1804:                                break;
                   1805:                        if (npfd > maxfds) {
                   1806:                                debug3("out of fds (active %u >= limit %u); "
                   1807:                                    "skipping accept", activefds, maxfds);
                   1808:                                break;
                   1809:                        }
                   1810:                        if (handle_socket_read(socknum) == 0)
                   1811:                                activefds++;
1.223     djm      1812:                        break;
                   1813:                case AUTH_CONNECTION:
1.279     djm      1814:                        if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 &&
                   1815:                            handle_conn_read(socknum) != 0)
1.231     djm      1816:                                goto close_sock;
                   1817:                        if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
                   1818:                            handle_conn_write(socknum) != 0) {
                   1819:  close_sock:
                   1820:                                if (activefds == 0)
                   1821:                                        fatal("activefds == 0 at close_sock");
1.223     djm      1822:                                close_socket(&sockets[socknum]);
1.231     djm      1823:                                activefds--;
1.223     djm      1824:                                break;
                   1825:                        }
                   1826:                        break;
                   1827:                default:
                   1828:                        break;
                   1829:                }
                   1830:        }
                   1831: }
                   1832:
                   1833: static int
1.231     djm      1834: prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
1.223     djm      1835: {
                   1836:        struct pollfd *pfd = *pfdp;
                   1837:        size_t i, j, npfd = 0;
1.174     dtucker  1838:        time_t deadline;
1.233     djm      1839:        int r;
1.46      markus   1840:
1.223     djm      1841:        /* Count active sockets */
1.46      markus   1842:        for (i = 0; i < sockets_alloc; i++) {
1.21      markus   1843:                switch (sockets[i].type) {
                   1844:                case AUTH_SOCKET:
                   1845:                case AUTH_CONNECTION:
1.223     djm      1846:                        npfd++;
1.21      markus   1847:                        break;
                   1848:                case AUTH_UNUSED:
                   1849:                        break;
                   1850:                default:
                   1851:                        fatal("Unknown socket type %d", sockets[i].type);
                   1852:                        break;
                   1853:                }
1.46      markus   1854:        }
1.223     djm      1855:        if (npfd != *npfdp &&
                   1856:            (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
1.266     djm      1857:                fatal_f("recallocarray failed");
1.223     djm      1858:        *pfdp = pfd;
                   1859:        *npfdp = npfd;
1.46      markus   1860:
1.223     djm      1861:        for (i = j = 0; i < sockets_alloc; i++) {
1.46      markus   1862:                switch (sockets[i].type) {
                   1863:                case AUTH_SOCKET:
1.231     djm      1864:                        if (npfd > maxfds) {
                   1865:                                debug3("out of fds (active %zu >= limit %u); "
                   1866:                                    "skipping arming listener", npfd, maxfds);
                   1867:                                break;
                   1868:                        }
                   1869:                        pfd[j].fd = sockets[i].fd;
                   1870:                        pfd[j].revents = 0;
                   1871:                        pfd[j].events = POLLIN;
                   1872:                        j++;
                   1873:                        break;
1.46      markus   1874:                case AUTH_CONNECTION:
1.223     djm      1875:                        pfd[j].fd = sockets[i].fd;
                   1876:                        pfd[j].revents = 0;
1.233     djm      1877:                        /*
                   1878:                         * Only prepare to read if we can handle a full-size
                   1879:                         * input read buffer and enqueue a max size reply..
                   1880:                         */
                   1881:                        if ((r = sshbuf_check_reserve(sockets[i].input,
                   1882:                            AGENT_RBUF_LEN)) == 0 &&
                   1883:                            (r = sshbuf_check_reserve(sockets[i].output,
1.278     djm      1884:                            AGENT_MAX_LEN)) == 0)
1.233     djm      1885:                                pfd[j].events = POLLIN;
1.266     djm      1886:                        else if (r != SSH_ERR_NO_BUFFER_SPACE)
                   1887:                                fatal_fr(r, "reserve");
1.194     markus   1888:                        if (sshbuf_len(sockets[i].output) > 0)
1.223     djm      1889:                                pfd[j].events |= POLLOUT;
                   1890:                        j++;
1.46      markus   1891:                        break;
                   1892:                default:
                   1893:                        break;
                   1894:                }
                   1895:        }
1.155     dtucker  1896:        deadline = reaper();
                   1897:        if (parent_alive_interval != 0)
                   1898:                deadline = (deadline == 0) ? parent_alive_interval :
1.214     deraadt  1899:                    MINIMUM(deadline, parent_alive_interval);
1.155     dtucker  1900:        if (deadline == 0) {
1.224     djm      1901:                *timeoutp = -1; /* INFTIM */
1.155     dtucker  1902:        } else {
1.223     djm      1903:                if (deadline > INT_MAX / 1000)
                   1904:                        *timeoutp = INT_MAX / 1000;
                   1905:                else
                   1906:                        *timeoutp = deadline * 1000;
1.155     dtucker  1907:        }
1.46      markus   1908:        return (1);
1.21      markus   1909: }
                   1910:
1.55      itojun   1911: static void
1.113     markus   1912: cleanup_socket(void)
1.15      markus   1913: {
1.187     djm      1914:        if (cleanup_pid != 0 && getpid() != cleanup_pid)
                   1915:                return;
1.266     djm      1916:        debug_f("cleanup");
1.48      deraadt  1917:        if (socket_name[0])
                   1918:                unlink(socket_name);
                   1919:        if (socket_dir[0])
                   1920:                rmdir(socket_dir);
1.10      markus   1921: }
                   1922:
1.114     markus   1923: void
1.15      markus   1924: cleanup_exit(int i)
                   1925: {
1.113     markus   1926:        cleanup_socket();
                   1927:        _exit(i);
1.15      markus   1928: }
                   1929:
1.135     deraadt  1930: /*ARGSUSED*/
1.55      itojun   1931: static void
1.48      deraadt  1932: cleanup_handler(int sig)
                   1933: {
1.113     markus   1934:        cleanup_socket();
1.163     markus   1935: #ifdef ENABLE_PKCS11
                   1936:        pkcs11_terminate();
                   1937: #endif
1.48      deraadt  1938:        _exit(2);
1.113     markus   1939: }
                   1940:
1.68      markus   1941: static void
1.155     dtucker  1942: check_parent_exists(void)
1.68      markus   1943: {
1.172     dtucker  1944:        /*
                   1945:         * If our parent has exited then getppid() will return (pid_t)1,
                   1946:         * so testing for that should be safe.
                   1947:         */
                   1948:        if (parent_pid != -1 && getppid() != parent_pid) {
1.68      markus   1949:                /* printf("Parent has died - Authentication agent exiting.\n"); */
1.155     dtucker  1950:                cleanup_socket();
                   1951:                _exit(2);
1.68      markus   1952:        }
1.48      deraadt  1953: }
                   1954:
1.55      itojun   1955: static void
1.50      itojun   1956: usage(void)
1.15      markus   1957: {
1.184     deraadt  1958:        fprintf(stderr,
1.250     jmc      1959:            "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1.261     jmc      1960:            "                 [-P allowed_providers] [-t life]\n"
1.260     djm      1961:            "       ssh-agent [-a bind_address] [-E fingerprint_hash] [-P allowed_providers]\n"
1.259     dtucker  1962:            "                 [-t life] command [arg ...]\n"
1.250     jmc      1963:            "       ssh-agent [-c | -s] -k\n");
1.21      markus   1964:        exit(1);
1.15      markus   1965: }
                   1966:
1.2       provos   1967: int
                   1968: main(int ac, char **av)
1.1       deraadt  1969: {
1.201     djm      1970:        int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1.265     djm      1971:        int sock, ch, result, saved_errno;
1.96      deraadt  1972:        char *shell, *format, *pidstr, *agentsocket = NULL;
1.41      markus   1973:        struct rlimit rlim;
1.96      deraadt  1974:        extern int optind;
1.98      stevesk  1975:        extern char *optarg;
1.21      markus   1976:        pid_t pid;
1.96      deraadt  1977:        char pidstrbuf[1 + 3 * sizeof pid];
1.161     tobias   1978:        size_t len;
1.189     djm      1979:        mode_t prev_mask;
1.224     djm      1980:        int timeout = -1; /* INFTIM */
1.223     djm      1981:        struct pollfd *pfd = NULL;
                   1982:        size_t npfd = 0;
1.231     djm      1983:        u_int maxfds;
1.123     djm      1984:
                   1985:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                   1986:        sanitise_stdfd();
1.99      markus   1987:
                   1988:        /* drop */
                   1989:        setegid(getgid());
                   1990:        setgid(getgid());
1.53      markus   1991:
1.231     djm      1992:        if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
                   1993:                fatal("%s: getrlimit: %s", __progname, strerror(errno));
                   1994:
1.185     markus   1995: #ifdef WITH_OPENSSL
1.170     djm      1996:        OpenSSL_add_all_algorithms();
1.185     markus   1997: #endif
1.21      markus   1998:
1.258     djm      1999:        while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:")) != -1) {
1.21      markus   2000:                switch (ch) {
1.192     djm      2001:                case 'E':
                   2002:                        fingerprint_hash = ssh_digest_alg_by_name(optarg);
                   2003:                        if (fingerprint_hash == -1)
                   2004:                                fatal("Invalid hash algorithm \"%s\"", optarg);
                   2005:                        break;
1.21      markus   2006:                case 'c':
                   2007:                        if (s_flag)
                   2008:                                usage();
                   2009:                        c_flag++;
                   2010:                        break;
                   2011:                case 'k':
                   2012:                        k_flag++;
1.258     djm      2013:                        break;
                   2014:                case 'O':
                   2015:                        if (strcmp(optarg, "no-restrict-websafe") == 0)
                   2016:                                restrict_websafe  = 0;
                   2017:                        else
                   2018:                                fatal("Unknown -O option");
1.21      markus   2019:                        break;
1.215     djm      2020:                case 'P':
1.260     djm      2021:                        if (allowed_providers != NULL)
1.215     djm      2022:                                fatal("-P option already specified");
1.260     djm      2023:                        allowed_providers = xstrdup(optarg);
1.215     djm      2024:                        break;
1.21      markus   2025:                case 's':
                   2026:                        if (c_flag)
                   2027:                                usage();
                   2028:                        s_flag++;
                   2029:                        break;
1.57      markus   2030:                case 'd':
1.201     djm      2031:                        if (d_flag || D_flag)
1.57      markus   2032:                                usage();
                   2033:                        d_flag++;
                   2034:                        break;
1.201     djm      2035:                case 'D':
                   2036:                        if (d_flag || D_flag)
                   2037:                                usage();
                   2038:                        D_flag++;
                   2039:                        break;
1.86      markus   2040:                case 'a':
                   2041:                        agentsocket = optarg;
1.106     marc     2042:                        break;
                   2043:                case 't':
                   2044:                        if ((lifetime = convtime(optarg)) == -1) {
                   2045:                                fprintf(stderr, "Invalid lifetime\n");
                   2046:                                usage();
                   2047:                        }
1.86      markus   2048:                        break;
1.21      markus   2049:                default:
                   2050:                        usage();
                   2051:                }
                   2052:        }
                   2053:        ac -= optind;
                   2054:        av += optind;
                   2055:
1.201     djm      2056:        if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1.21      markus   2057:                usage();
                   2058:
1.260     djm      2059:        if (allowed_providers == NULL)
1.262     djm      2060:                allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
1.215     djm      2061:
1.85      markus   2062:        if (ac == 0 && !c_flag && !s_flag) {
1.21      markus   2063:                shell = getenv("SHELL");
1.161     tobias   2064:                if (shell != NULL && (len = strlen(shell)) > 2 &&
                   2065:                    strncmp(shell + len - 3, "csh", 3) == 0)
1.21      markus   2066:                        c_flag = 1;
                   2067:        }
                   2068:        if (k_flag) {
1.136     deraadt  2069:                const char *errstr = NULL;
                   2070:
1.21      markus   2071:                pidstr = getenv(SSH_AGENTPID_ENV_NAME);
                   2072:                if (pidstr == NULL) {
                   2073:                        fprintf(stderr, "%s not set, cannot kill agent\n",
1.46      markus   2074:                            SSH_AGENTPID_ENV_NAME);
1.21      markus   2075:                        exit(1);
                   2076:                }
1.136     deraadt  2077:                pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
                   2078:                if (errstr) {
                   2079:                        fprintf(stderr,
                   2080:                            "%s=\"%s\", which is not a good PID: %s\n",
                   2081:                            SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1.21      markus   2082:                        exit(1);
                   2083:                }
                   2084:                if (kill(pid, SIGTERM) == -1) {
                   2085:                        perror("kill");
                   2086:                        exit(1);
                   2087:                }
                   2088:                format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1.140     djm      2089:                printf(format, SSH_AUTHSOCKET_ENV_NAME);
                   2090:                printf(format, SSH_AGENTPID_ENV_NAME);
1.91      mpech    2091:                printf("echo Agent pid %ld killed;\n", (long)pid);
1.21      markus   2092:                exit(0);
                   2093:        }
1.231     djm      2094:
                   2095:        /*
                   2096:         * Minimum file descriptors:
                   2097:         * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
                   2098:         * a few spare for libc / stack protectors / sanitisers, etc.
                   2099:         */
                   2100: #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
                   2101:        if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
1.232     djm      2102:                fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
1.231     djm      2103:                    __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
                   2104:        maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
                   2105:
1.21      markus   2106:        parent_pid = getpid();
                   2107:
1.86      markus   2108:        if (agentsocket == NULL) {
                   2109:                /* Create private directory for agent socket */
1.171     djm      2110:                mktemp_proto(socket_dir, sizeof(socket_dir));
1.86      markus   2111:                if (mkdtemp(socket_dir) == NULL) {
                   2112:                        perror("mkdtemp: private socket dir");
                   2113:                        exit(1);
                   2114:                }
1.91      mpech    2115:                snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
                   2116:                    (long)parent_pid);
1.86      markus   2117:        } else {
                   2118:                /* Try to use specified agent socket */
                   2119:                socket_dir[0] = '\0';
                   2120:                strlcpy(socket_name, agentsocket, sizeof socket_name);
1.21      markus   2121:        }
                   2122:
1.23      markus   2123:        /*
                   2124:         * Create socket early so it will exist before command gets run from
                   2125:         * the parent.
                   2126:         */
1.189     djm      2127:        prev_mask = umask(0177);
1.188     millert  2128:        sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1.21      markus   2129:        if (sock < 0) {
1.188     millert  2130:                /* XXX - unix_listener() calls error() not perror() */
1.121     djm      2131:                *socket_name = '\0'; /* Don't unlink any existing file */
1.21      markus   2132:                cleanup_exit(1);
                   2133:        }
1.189     djm      2134:        umask(prev_mask);
1.46      markus   2135:
1.23      markus   2136:        /*
                   2137:         * Fork, and have the parent execute the command, if any, or present
                   2138:         * the socket data.  The child continues as the authentication agent.
                   2139:         */
1.201     djm      2140:        if (D_flag || d_flag) {
                   2141:                log_init(__progname,
                   2142:                    d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
                   2143:                    SYSLOG_FACILITY_AUTH, 1);
1.57      markus   2144:                format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
                   2145:                printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
                   2146:                    SSH_AUTHSOCKET_ENV_NAME);
1.91      mpech    2147:                printf("echo Agent pid %ld;\n", (long)parent_pid);
1.210     dtucker  2148:                fflush(stdout);
1.57      markus   2149:                goto skip;
                   2150:        }
1.21      markus   2151:        pid = fork();
                   2152:        if (pid == -1) {
                   2153:                perror("fork");
1.81      stevesk  2154:                cleanup_exit(1);
1.21      markus   2155:        }
                   2156:        if (pid != 0) {         /* Parent - execute the given command. */
                   2157:                close(sock);
1.91      mpech    2158:                snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1.21      markus   2159:                if (ac == 0) {
                   2160:                        format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
                   2161:                        printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1.46      markus   2162:                            SSH_AUTHSOCKET_ENV_NAME);
1.21      markus   2163:                        printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1.46      markus   2164:                            SSH_AGENTPID_ENV_NAME);
1.91      mpech    2165:                        printf("echo Agent pid %ld;\n", (long)pid);
1.21      markus   2166:                        exit(0);
                   2167:                }
1.36      deraadt  2168:                if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
                   2169:                    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
                   2170:                        perror("setenv");
                   2171:                        exit(1);
                   2172:                }
1.21      markus   2173:                execvp(av[0], av);
                   2174:                perror(av[0]);
                   2175:                exit(1);
                   2176:        }
1.81      stevesk  2177:        /* child */
                   2178:        log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1.67      stevesk  2179:
                   2180:        if (setsid() == -1) {
1.81      stevesk  2181:                error("setsid: %s", strerror(errno));
1.67      stevesk  2182:                cleanup_exit(1);
                   2183:        }
                   2184:
                   2185:        (void)chdir("/");
1.265     djm      2186:        if (stdfd_devnull(1, 1, 1) == -1)
1.266     djm      2187:                error_f("stdfd_devnull failed");
1.21      markus   2188:
1.41      markus   2189:        /* deny core dumps, since memory contains unencrypted private keys */
                   2190:        rlim.rlim_cur = rlim.rlim_max = 0;
1.237     deraadt  2191:        if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
1.81      stevesk  2192:                error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1.21      markus   2193:                cleanup_exit(1);
                   2194:        }
1.57      markus   2195:
                   2196: skip:
1.187     djm      2197:
                   2198:        cleanup_pid = getpid();
1.163     markus   2199:
                   2200: #ifdef ENABLE_PKCS11
                   2201:        pkcs11_init(0);
                   2202: #endif
1.21      markus   2203:        new_socket(AUTH_SOCKET, sock);
1.155     dtucker  2204:        if (ac > 0)
                   2205:                parent_alive_interval = 10;
1.33      markus   2206:        idtab_init();
1.252     dtucker  2207:        ssh_signal(SIGPIPE, SIG_IGN);
                   2208:        ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
                   2209:        ssh_signal(SIGHUP, cleanup_handler);
                   2210:        ssh_signal(SIGTERM, cleanup_handler);
1.205     djm      2211:
1.215     djm      2212:        if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1.205     djm      2213:                fatal("%s: pledge: %s", __progname, strerror(errno));
1.66      markus   2214:
1.21      markus   2215:        while (1) {
1.231     djm      2216:                prepare_poll(&pfd, &npfd, &timeout, maxfds);
1.223     djm      2217:                result = poll(pfd, npfd, timeout);
1.154     dtucker  2218:                saved_errno = errno;
1.155     dtucker  2219:                if (parent_alive_interval != 0)
                   2220:                        check_parent_exists();
                   2221:                (void) reaper();        /* remove expired keys */
1.237     deraadt  2222:                if (result == -1) {
1.154     dtucker  2223:                        if (saved_errno == EINTR)
1.21      markus   2224:                                continue;
1.223     djm      2225:                        fatal("poll: %s", strerror(saved_errno));
1.154     dtucker  2226:                } else if (result > 0)
1.231     djm      2227:                        after_poll(pfd, npfd, maxfds);
1.15      markus   2228:        }
1.21      markus   2229:        /* NOTREACHED */
1.1       deraadt  2230: }