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

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