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

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