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

1.235   ! djm         1: /* $OpenBSD: ssh-agent.c,v 1.234 2019/06/06 05:13:13 otto 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.126     stevesk    44:
1.185     markus     45: #ifdef WITH_OPENSSL
1.146     stevesk    46: #include <openssl/evp.h>
1.185     markus     47: #endif
1.146     stevesk    48:
1.143     stevesk    49: #include <errno.h>
1.142     stevesk    50: #include <fcntl.h>
1.126     stevesk    51: #include <paths.h>
1.223     djm        52: #include <poll.h>
1.129     stevesk    53: #include <signal.h>
1.149     stevesk    54: #include <stdlib.h>
1.150     stevesk    55: #include <stdio.h>
1.146     stevesk    56: #include <string.h>
1.196     deraadt    57: #include <limits.h>
1.145     stevesk    58: #include <time.h>
1.144     stevesk    59: #include <unistd.h>
1.203     dtucker    60: #include <util.h>
1.194     markus     61:
1.151     deraadt    62: #include "xmalloc.h"
1.1       deraadt    63: #include "ssh.h"
1.194     markus     64: #include "sshbuf.h"
                     65: #include "sshkey.h"
1.32      markus     66: #include "authfd.h"
1.37      markus     67: #include "compat.h"
1.47      markus     68: #include "log.h"
1.107     markus     69: #include "misc.h"
1.182     markus     70: #include "digest.h"
1.194     markus     71: #include "ssherr.h"
1.215     djm        72: #include "match.h"
1.7       deraadt    73:
1.163     markus     74: #ifdef ENABLE_PKCS11
                     75: #include "ssh-pkcs11.h"
1.71      jakob      76: #endif
1.59      markus     77:
1.215     djm        78: #ifndef DEFAULT_PKCS11_WHITELIST
1.216     djm        79: # define DEFAULT_PKCS11_WHITELIST "/usr/lib*/*,/usr/local/lib*/*"
1.215     djm        80: #endif
                     81:
1.223     djm        82: /* Maximum accepted message length */
                     83: #define AGENT_MAX_LEN  (256*1024)
1.233     djm        84: /* Maximum bytes to read from client socket */
                     85: #define AGENT_RBUF_LEN (4096)
1.223     djm        86:
1.73      stevesk    87: typedef enum {
                     88:        AUTH_UNUSED,
                     89:        AUTH_SOCKET,
                     90:        AUTH_CONNECTION
                     91: } sock_type;
                     92:
1.21      markus     93: typedef struct {
                     94:        int fd;
1.73      stevesk    95:        sock_type type;
1.194     markus     96:        struct sshbuf *input;
                     97:        struct sshbuf *output;
                     98:        struct sshbuf *request;
1.1       deraadt    99: } SocketEntry;
                    100:
1.45      markus    101: u_int sockets_alloc = 0;
1.1       deraadt   102: SocketEntry *sockets = NULL;
                    103:
1.78      provos    104: typedef struct identity {
                    105:        TAILQ_ENTRY(identity) next;
1.194     markus    106:        struct sshkey *key;
1.21      markus    107:        char *comment;
1.163     markus    108:        char *provider;
1.174     dtucker   109:        time_t death;
1.107     markus    110:        u_int confirm;
1.1       deraadt   111: } Identity;
                    112:
1.221     djm       113: struct idtable {
1.33      markus    114:        int nentries;
1.78      provos    115:        TAILQ_HEAD(idqueue, identity) idlist;
1.221     djm       116: };
1.33      markus    117:
1.221     djm       118: /* private key table */
                    119: struct idtable *idtab;
1.1       deraadt   120:
                    121: int max_fd = 0;
                    122:
1.11      markus    123: /* pid of shell == parent of agent */
1.29      deraadt   124: pid_t parent_pid = -1;
1.176     dtucker   125: time_t parent_alive_interval = 0;
1.10      markus    126:
1.187     djm       127: /* pid of process for which cleanup_socket is applicable */
                    128: pid_t cleanup_pid = 0;
                    129:
1.10      markus    130: /* pathname and directory for AUTH_SOCKET */
1.196     deraadt   131: char socket_name[PATH_MAX];
                    132: char socket_dir[PATH_MAX];
1.10      markus    133:
1.215     djm       134: /* PKCS#11 path whitelist */
                    135: static char *pkcs11_whitelist;
                    136:
1.88      markus    137: /* locking */
1.203     dtucker   138: #define LOCK_SIZE      32
                    139: #define LOCK_SALT_SIZE 16
                    140: #define LOCK_ROUNDS    1
1.88      markus    141: int locked = 0;
1.213     djm       142: u_char lock_pwhash[LOCK_SIZE];
                    143: u_char lock_salt[LOCK_SALT_SIZE];
1.88      markus    144:
1.20      markus    145: extern char *__progname;
                    146:
1.174     dtucker   147: /* Default lifetime in seconds (0 == forever) */
                    148: static long lifetime = 0;
1.106     marc      149:
1.192     djm       150: static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
                    151:
1.55      itojun    152: static void
1.101     stevesk   153: close_socket(SocketEntry *e)
                    154: {
                    155:        close(e->fd);
                    156:        e->fd = -1;
                    157:        e->type = AUTH_UNUSED;
1.194     markus    158:        sshbuf_free(e->input);
                    159:        sshbuf_free(e->output);
                    160:        sshbuf_free(e->request);
1.101     stevesk   161: }
                    162:
                    163: static void
1.33      markus    164: idtab_init(void)
1.1       deraadt   165: {
1.221     djm       166:        idtab = xcalloc(1, sizeof(*idtab));
                    167:        TAILQ_INIT(&idtab->idlist);
                    168:        idtab->nentries = 0;
1.33      markus    169: }
                    170:
1.89      markus    171: static void
                    172: free_identity(Identity *id)
                    173: {
1.194     markus    174:        sshkey_free(id->key);
1.173     djm       175:        free(id->provider);
                    176:        free(id->comment);
                    177:        free(id);
1.89      markus    178: }
                    179:
1.33      markus    180: /* return matching private key for given public key */
1.78      provos    181: static Identity *
1.221     djm       182: lookup_identity(struct sshkey *key)
1.33      markus    183: {
1.78      provos    184:        Identity *id;
                    185:
1.221     djm       186:        TAILQ_FOREACH(id, &idtab->idlist, next) {
1.194     markus    187:                if (sshkey_equal(key, id->key))
1.78      provos    188:                        return (id);
1.33      markus    189:        }
1.78      provos    190:        return (NULL);
                    191: }
                    192:
1.107     markus    193: /* Check confirmation of keysign request */
                    194: static int
                    195: confirm_key(Identity *id)
                    196: {
1.122     djm       197:        char *p;
1.107     markus    198:        int ret = -1;
                    199:
1.194     markus    200:        p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
1.197     djm       201:        if (p != NULL &&
                    202:            ask_permission("Allow use of key %s?\nKey fingerprint %s.",
1.122     djm       203:            id->comment, p))
                    204:                ret = 0;
1.173     djm       205:        free(p);
1.122     djm       206:
1.107     markus    207:        return (ret);
                    208: }
                    209:
1.194     markus    210: static void
                    211: send_status(SocketEntry *e, int success)
                    212: {
                    213:        int r;
                    214:
                    215:        if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
                    216:            (r = sshbuf_put_u8(e->output, success ?
                    217:            SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
                    218:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    219: }
                    220:
1.33      markus    221: /* send list of supported public keys to 'client' */
1.55      itojun    222: static void
1.221     djm       223: process_request_identities(SocketEntry *e)
1.33      markus    224: {
1.96      deraadt   225:        Identity *id;
1.194     markus    226:        struct sshbuf *msg;
                    227:        int r;
1.1       deraadt   228:
1.194     markus    229:        if ((msg = sshbuf_new()) == NULL)
                    230:                fatal("%s: sshbuf_new failed", __func__);
1.221     djm       231:        if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
                    232:            (r = sshbuf_put_u32(msg, idtab->nentries)) != 0)
                    233:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    234:        TAILQ_FOREACH(id, &idtab->idlist, next) {
1.228     markus    235:                if ((r = sshkey_puts_opts(id->key, msg, SSHKEY_SERIALIZE_INFO))
                    236:                     != 0 ||
1.221     djm       237:                    (r = sshbuf_put_cstring(msg, id->comment)) != 0) {
                    238:                        error("%s: put key/comment: %s", __func__,
1.220     djm       239:                            ssh_err(r));
                    240:                        continue;
1.33      markus    241:                }
1.21      markus    242:        }
1.194     markus    243:        if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
                    244:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    245:        sshbuf_free(msg);
1.1       deraadt   246: }
                    247:
1.33      markus    248:
1.208     markus    249: static char *
                    250: agent_decode_alg(struct sshkey *key, u_int flags)
                    251: {
                    252:        if (key->type == KEY_RSA) {
                    253:                if (flags & SSH_AGENT_RSA_SHA2_256)
                    254:                        return "rsa-sha2-256";
                    255:                else if (flags & SSH_AGENT_RSA_SHA2_512)
                    256:                        return "rsa-sha2-512";
1.235   ! djm       257:        } else if (key->type == KEY_RSA_CERT) {
        !           258:                if (flags & SSH_AGENT_RSA_SHA2_256)
        !           259:                        return "rsa-sha2-256-cert-v01@openssh.com";
        !           260:                else if (flags & SSH_AGENT_RSA_SHA2_512)
        !           261:                        return "rsa-sha2-512-cert-v01@openssh.com";
1.208     markus    262:        }
                    263:        return NULL;
                    264: }
                    265:
1.33      markus    266: /* ssh2 only */
1.55      itojun    267: static void
1.33      markus    268: process_sign_request2(SocketEntry *e)
                    269: {
1.221     djm       270:        const u_char *data;
                    271:        u_char *signature = NULL;
                    272:        size_t dlen, slen = 0;
1.194     markus    273:        u_int compat = 0, flags;
                    274:        int r, ok = -1;
                    275:        struct sshbuf *msg;
1.221     djm       276:        struct sshkey *key = NULL;
1.195     djm       277:        struct identity *id;
1.194     markus    278:
1.195     djm       279:        if ((msg = sshbuf_new()) == NULL)
                    280:                fatal("%s: sshbuf_new failed", __func__);
1.221     djm       281:        if ((r = sshkey_froms(e->request, &key)) != 0 ||
                    282:            (r = sshbuf_get_string_direct(e->request, &data, &dlen)) != 0 ||
1.225     djm       283:            (r = sshbuf_get_u32(e->request, &flags)) != 0) {
                    284:                error("%s: couldn't parse request: %s", __func__, ssh_err(r));
                    285:                goto send;
                    286:        }
                    287:
1.221     djm       288:        if ((id = lookup_identity(key)) == NULL) {
1.195     djm       289:                verbose("%s: %s key not found", __func__, sshkey_type(key));
                    290:                goto send;
                    291:        }
                    292:        if (id->confirm && confirm_key(id) != 0) {
                    293:                verbose("%s: user refused key", __func__);
                    294:                goto send;
                    295:        }
                    296:        if ((r = sshkey_sign(id->key, &signature, &slen,
1.208     markus    297:            data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
1.209     djm       298:                error("%s: sshkey_sign: %s", __func__, ssh_err(r));
1.195     djm       299:                goto send;
1.33      markus    300:        }
1.195     djm       301:        /* Success */
                    302:        ok = 0;
                    303:  send:
                    304:        sshkey_free(key);
1.33      markus    305:        if (ok == 0) {
1.194     markus    306:                if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
                    307:                    (r = sshbuf_put_string(msg, signature, slen)) != 0)
                    308:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    309:        } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
                    310:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    311:
                    312:        if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
                    313:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    314:
                    315:        sshbuf_free(msg);
1.173     djm       316:        free(signature);
1.1       deraadt   317: }
                    318:
1.33      markus    319: /* shared */
1.55      itojun    320: static void
1.221     djm       321: process_remove_identity(SocketEntry *e)
1.1       deraadt   322: {
1.194     markus    323:        int r, success = 0;
                    324:        struct sshkey *key = NULL;
1.221     djm       325:        Identity *id;
1.21      markus    326:
1.221     djm       327:        if ((r = sshkey_froms(e->request, &key)) != 0) {
                    328:                error("%s: get key: %s", __func__, ssh_err(r));
                    329:                goto done;
                    330:        }
                    331:        if ((id = lookup_identity(key)) == NULL) {
                    332:                debug("%s: key not found", __func__);
                    333:                goto done;
                    334:        }
                    335:        /* We have this key, free it. */
                    336:        if (idtab->nentries < 1)
                    337:                fatal("%s: internal error: nentries %d",
                    338:                    __func__, idtab->nentries);
                    339:        TAILQ_REMOVE(&idtab->idlist, id, next);
                    340:        free_identity(id);
                    341:        idtab->nentries--;
                    342:        sshkey_free(key);
                    343:        success = 1;
                    344:  done:
1.194     markus    345:        send_status(e, success);
1.1       deraadt   346: }
                    347:
1.55      itojun    348: static void
1.221     djm       349: process_remove_all_identities(SocketEntry *e)
1.1       deraadt   350: {
1.78      provos    351:        Identity *id;
1.21      markus    352:
                    353:        /* Loop over all identities and clear the keys. */
1.221     djm       354:        for (id = TAILQ_FIRST(&idtab->idlist); id;
                    355:            id = TAILQ_FIRST(&idtab->idlist)) {
                    356:                TAILQ_REMOVE(&idtab->idlist, id, next);
1.78      provos    357:                free_identity(id);
1.21      markus    358:        }
                    359:
                    360:        /* Mark that there are no identities. */
1.221     djm       361:        idtab->nentries = 0;
1.21      markus    362:
                    363:        /* Send success. */
1.194     markus    364:        send_status(e, 1);
1.1       deraadt   365: }
                    366:
1.155     dtucker   367: /* removes expired keys and returns number of seconds until the next expiry */
1.174     dtucker   368: static time_t
1.89      markus    369: reaper(void)
                    370: {
1.175     dtucker   371:        time_t deadline = 0, now = monotime();
1.89      markus    372:        Identity *id, *nxt;
                    373:
1.221     djm       374:        for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
                    375:                nxt = TAILQ_NEXT(id, next);
                    376:                if (id->death == 0)
                    377:                        continue;
                    378:                if (now >= id->death) {
                    379:                        debug("expiring key '%s'", id->comment);
                    380:                        TAILQ_REMOVE(&idtab->idlist, id, next);
                    381:                        free_identity(id);
                    382:                        idtab->nentries--;
                    383:                } else
                    384:                        deadline = (deadline == 0) ? id->death :
                    385:                            MINIMUM(deadline, id->death);
1.89      markus    386:        }
1.155     dtucker   387:        if (deadline == 0 || deadline <= now)
                    388:                return 0;
                    389:        else
                    390:                return (deadline - now);
1.89      markus    391: }
                    392:
                    393: static void
1.221     djm       394: process_add_identity(SocketEntry *e)
1.1       deraadt   395: {
1.157     canacar   396:        Identity *id;
1.194     markus    397:        int success = 0, confirm = 0;
1.228     markus    398:        u_int seconds, maxsign;
1.194     markus    399:        char *comment = NULL;
1.174     dtucker   400:        time_t death = 0;
1.194     markus    401:        struct sshkey *k = NULL;
                    402:        u_char ctype;
                    403:        int r = SSH_ERR_INTERNAL_ERROR;
1.33      markus    404:
1.221     djm       405:        if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
                    406:            k == NULL ||
1.194     markus    407:            (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
                    408:                error("%s: decode private key: %s", __func__, ssh_err(r));
                    409:                goto err;
                    410:        }
1.186     djm       411:
1.194     markus    412:        while (sshbuf_len(e->request)) {
                    413:                if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
                    414:                        error("%s: buffer error: %s", __func__, ssh_err(r));
                    415:                        goto err;
                    416:                }
                    417:                switch (ctype) {
1.94      markus    418:                case SSH_AGENT_CONSTRAIN_LIFETIME:
1.194     markus    419:                        if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
                    420:                                error("%s: bad lifetime constraint: %s",
                    421:                                    __func__, ssh_err(r));
                    422:                                goto err;
                    423:                        }
                    424:                        death = monotime() + seconds;
1.94      markus    425:                        break;
1.107     markus    426:                case SSH_AGENT_CONSTRAIN_CONFIRM:
                    427:                        confirm = 1;
                    428:                        break;
1.228     markus    429:                case SSH_AGENT_CONSTRAIN_MAXSIGN:
                    430:                        if ((r = sshbuf_get_u32(e->request, &maxsign)) != 0) {
                    431:                                error("%s: bad maxsign constraint: %s",
                    432:                                    __func__, ssh_err(r));
                    433:                                goto err;
                    434:                        }
                    435:                        if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
                    436:                                error("%s: cannot enable maxsign: %s",
                    437:                                    __func__, ssh_err(r));
                    438:                                goto err;
                    439:                        }
                    440:                        break;
1.94      markus    441:                default:
1.194     markus    442:                        error("%s: Unknown constraint %d", __func__, ctype);
                    443:  err:
                    444:                        sshbuf_reset(e->request);
1.173     djm       445:                        free(comment);
1.194     markus    446:                        sshkey_free(k);
1.158     djm       447:                        goto send;
1.94      markus    448:                }
                    449:        }
1.194     markus    450:
1.158     djm       451:        success = 1;
1.106     marc      452:        if (lifetime && !death)
1.175     dtucker   453:                death = monotime() + lifetime;
1.221     djm       454:        if ((id = lookup_identity(k)) == NULL) {
1.163     markus    455:                id = xcalloc(1, sizeof(Identity));
1.221     djm       456:                TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1.33      markus    457:                /* Increment the number of identities. */
1.221     djm       458:                idtab->nentries++;
1.33      markus    459:        } else {
1.228     markus    460:                /* key state might have been updated */
                    461:                sshkey_free(id->key);
1.173     djm       462:                free(id->comment);
1.33      markus    463:        }
1.228     markus    464:        id->key = k;
1.157     canacar   465:        id->comment = comment;
                    466:        id->death = death;
                    467:        id->confirm = confirm;
1.33      markus    468: send:
1.194     markus    469:        send_status(e, success);
1.1       deraadt   470: }
                    471:
1.88      markus    472: /* XXX todo: encrypt sensitive data with passphrase */
                    473: static void
                    474: process_lock_agent(SocketEntry *e, int lock)
                    475: {
1.203     dtucker   476:        int r, success = 0, delay;
1.213     djm       477:        char *passwd;
                    478:        u_char passwdhash[LOCK_SIZE];
1.203     dtucker   479:        static u_int fail_count = 0;
                    480:        size_t pwlen;
                    481:
1.226     djm       482:        /*
                    483:         * This is deliberately fatal: the user has requested that we lock,
                    484:         * but we can't parse their request properly. The only safe thing to
                    485:         * do is abort.
                    486:         */
1.203     dtucker   487:        if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
                    488:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    489:        if (pwlen == 0) {
                    490:                debug("empty password not supported");
                    491:        } else if (locked && !lock) {
                    492:                if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
                    493:                    passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
                    494:                        fatal("bcrypt_pbkdf");
1.213     djm       495:                if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
1.203     dtucker   496:                        debug("agent unlocked");
                    497:                        locked = 0;
                    498:                        fail_count = 0;
1.213     djm       499:                        explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
1.203     dtucker   500:                        success = 1;
                    501:                } else {
                    502:                        /* delay in 0.1s increments up to 10s */
                    503:                        if (fail_count < 100)
                    504:                                fail_count++;
                    505:                        delay = 100000 * fail_count;
                    506:                        debug("unlock failed, delaying %0.1lf seconds",
                    507:                            (double)delay/1000000);
                    508:                        usleep(delay);
                    509:                }
                    510:                explicit_bzero(passwdhash, sizeof(passwdhash));
1.88      markus    511:        } else if (!locked && lock) {
1.203     dtucker   512:                debug("agent locked");
1.88      markus    513:                locked = 1;
1.203     dtucker   514:                arc4random_buf(lock_salt, sizeof(lock_salt));
                    515:                if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1.213     djm       516:                    lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
1.203     dtucker   517:                        fatal("bcrypt_pbkdf");
1.88      markus    518:                success = 1;
                    519:        }
1.203     dtucker   520:        explicit_bzero(passwd, pwlen);
1.173     djm       521:        free(passwd);
1.194     markus    522:        send_status(e, success);
1.88      markus    523: }
                    524:
                    525: static void
1.221     djm       526: no_identities(SocketEntry *e)
1.88      markus    527: {
1.194     markus    528:        struct sshbuf *msg;
                    529:        int r;
1.88      markus    530:
1.194     markus    531:        if ((msg = sshbuf_new()) == NULL)
                    532:                fatal("%s: sshbuf_new failed", __func__);
1.221     djm       533:        if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
1.194     markus    534:            (r = sshbuf_put_u32(msg, 0)) != 0 ||
                    535:            (r = sshbuf_put_stringb(e->output, msg)) != 0)
                    536:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    537:        sshbuf_free(msg);
1.88      markus    538: }
1.59      markus    539:
1.163     markus    540: #ifdef ENABLE_PKCS11
1.59      markus    541: static void
1.158     djm       542: process_add_smartcard_key(SocketEntry *e)
1.59      markus    543: {
1.226     djm       544:        char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1.221     djm       545:        int r, i, count = 0, success = 0, confirm = 0;
1.194     markus    546:        u_int seconds;
1.174     dtucker   547:        time_t death = 0;
1.194     markus    548:        u_char type;
                    549:        struct sshkey **keys = NULL, *k;
1.84      markus    550:        Identity *id;
1.75      deraadt   551:
1.194     markus    552:        if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1.226     djm       553:            (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
                    554:                error("%s: buffer error: %s", __func__, ssh_err(r));
                    555:                goto send;
                    556:        }
1.194     markus    557:
                    558:        while (sshbuf_len(e->request)) {
1.226     djm       559:                if ((r = sshbuf_get_u8(e->request, &type)) != 0) {
                    560:                        error("%s: buffer error: %s", __func__, ssh_err(r));
                    561:                        goto send;
                    562:                }
1.194     markus    563:                switch (type) {
1.110     djm       564:                case SSH_AGENT_CONSTRAIN_LIFETIME:
1.226     djm       565:                        if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
                    566:                                error("%s: buffer error: %s",
1.194     markus    567:                                    __func__, ssh_err(r));
1.226     djm       568:                                goto send;
                    569:                        }
1.194     markus    570:                        death = monotime() + seconds;
1.110     djm       571:                        break;
                    572:                case SSH_AGENT_CONSTRAIN_CONFIRM:
                    573:                        confirm = 1;
                    574:                        break;
                    575:                default:
1.221     djm       576:                        error("%s: Unknown constraint type %d", __func__, type);
1.158     djm       577:                        goto send;
1.110     djm       578:                }
                    579:        }
1.215     djm       580:        if (realpath(provider, canonical_provider) == NULL) {
                    581:                verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
                    582:                    provider, strerror(errno));
                    583:                goto send;
                    584:        }
                    585:        if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
                    586:                verbose("refusing PKCS#11 add of \"%.100s\": "
                    587:                    "provider not whitelisted", canonical_provider);
                    588:                goto send;
                    589:        }
                    590:        debug("%s: add %.100s", __func__, canonical_provider);
1.110     djm       591:        if (lifetime && !death)
1.175     dtucker   592:                death = monotime() + lifetime;
1.110     djm       593:
1.215     djm       594:        count = pkcs11_add_provider(canonical_provider, pin, &keys);
1.163     markus    595:        for (i = 0; i < count; i++) {
1.84      markus    596:                k = keys[i];
1.221     djm       597:                if (lookup_identity(k) == NULL) {
1.163     markus    598:                        id = xcalloc(1, sizeof(Identity));
1.84      markus    599:                        id->key = k;
1.215     djm       600:                        id->provider = xstrdup(canonical_provider);
                    601:                        id->comment = xstrdup(canonical_provider); /* XXX */
1.110     djm       602:                        id->death = death;
                    603:                        id->confirm = confirm;
1.221     djm       604:                        TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
                    605:                        idtab->nentries++;
1.84      markus    606:                        success = 1;
                    607:                } else {
1.194     markus    608:                        sshkey_free(k);
1.84      markus    609:                }
                    610:                keys[i] = NULL;
1.59      markus    611:        }
                    612: send:
1.173     djm       613:        free(pin);
                    614:        free(provider);
                    615:        free(keys);
1.194     markus    616:        send_status(e, success);
1.59      markus    617: }
                    618:
                    619: static void
                    620: process_remove_smartcard_key(SocketEntry *e)
                    621: {
1.217     djm       622:        char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1.221     djm       623:        int r, success = 0;
1.163     markus    624:        Identity *id, *nxt;
1.59      markus    625:
1.194     markus    626:        if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1.226     djm       627:            (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
                    628:                error("%s: buffer error: %s", __func__, ssh_err(r));
                    629:                goto send;
                    630:        }
1.173     djm       631:        free(pin);
1.59      markus    632:
1.217     djm       633:        if (realpath(provider, canonical_provider) == NULL) {
                    634:                verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
                    635:                    provider, strerror(errno));
                    636:                goto send;
                    637:        }
                    638:
                    639:        debug("%s: remove %.100s", __func__, canonical_provider);
1.221     djm       640:        for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
                    641:                nxt = TAILQ_NEXT(id, next);
                    642:                /* Skip file--based keys */
                    643:                if (id->provider == NULL)
                    644:                        continue;
                    645:                if (!strcmp(canonical_provider, id->provider)) {
                    646:                        TAILQ_REMOVE(&idtab->idlist, id, next);
                    647:                        free_identity(id);
                    648:                        idtab->nentries--;
1.59      markus    649:                }
                    650:        }
1.217     djm       651:        if (pkcs11_del_provider(canonical_provider) == 0)
1.163     markus    652:                success = 1;
                    653:        else
1.221     djm       654:                error("%s: pkcs11_del_provider failed", __func__);
1.218     deraadt   655: send:
1.173     djm       656:        free(provider);
1.194     markus    657:        send_status(e, success);
1.59      markus    658: }
1.163     markus    659: #endif /* ENABLE_PKCS11 */
1.59      markus    660:
1.33      markus    661: /* dispatch incoming messages */
                    662:
1.223     djm       663: static int
                    664: process_message(u_int socknum)
1.1       deraadt   665: {
1.194     markus    666:        u_int msg_len;
                    667:        u_char type;
                    668:        const u_char *cp;
                    669:        int r;
1.223     djm       670:        SocketEntry *e;
                    671:
                    672:        if (socknum >= sockets_alloc) {
                    673:                fatal("%s: socket number %u >= allocated %u",
                    674:                    __func__, socknum, sockets_alloc);
                    675:        }
                    676:        e = &sockets[socknum];
1.89      markus    677:
1.194     markus    678:        if (sshbuf_len(e->input) < 5)
1.223     djm       679:                return 0;               /* Incomplete message header. */
1.194     markus    680:        cp = sshbuf_ptr(e->input);
                    681:        msg_len = PEEK_U32(cp);
1.223     djm       682:        if (msg_len > AGENT_MAX_LEN) {
                    683:                debug("%s: socket %u (fd=%d) message too long %u > %u",
                    684:                    __func__, socknum, e->fd, msg_len, AGENT_MAX_LEN);
                    685:                return -1;
1.21      markus    686:        }
1.194     markus    687:        if (sshbuf_len(e->input) < msg_len + 4)
1.223     djm       688:                return 0;               /* Incomplete message body. */
1.87      markus    689:
                    690:        /* move the current input to e->request */
1.194     markus    691:        sshbuf_reset(e->request);
                    692:        if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1.223     djm       693:            (r = sshbuf_get_u8(e->request, &type)) != 0) {
                    694:                if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
                    695:                    r == SSH_ERR_STRING_TOO_LARGE) {
                    696:                        debug("%s: buffer error: %s", __func__, ssh_err(r));
                    697:                        return -1;
                    698:                }
1.194     markus    699:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.223     djm       700:        }
                    701:
                    702:        debug("%s: socket %u (fd=%d) type %d", __func__, socknum, e->fd, type);
1.21      markus    703:
1.230     djm       704:        /* check whether agent is locked */
1.88      markus    705:        if (locked && type != SSH_AGENTC_UNLOCK) {
1.194     markus    706:                sshbuf_reset(e->request);
1.88      markus    707:                switch (type) {
                    708:                case SSH2_AGENTC_REQUEST_IDENTITIES:
                    709:                        /* send empty lists */
1.221     djm       710:                        no_identities(e);
1.88      markus    711:                        break;
                    712:                default:
                    713:                        /* send a fail message for all other request types */
1.194     markus    714:                        send_status(e, 0);
1.88      markus    715:                }
1.223     djm       716:                return 0;
1.88      markus    717:        }
                    718:
1.21      markus    719:        switch (type) {
1.88      markus    720:        case SSH_AGENTC_LOCK:
                    721:        case SSH_AGENTC_UNLOCK:
                    722:                process_lock_agent(e, type == SSH_AGENTC_LOCK);
                    723:                break;
1.21      markus    724:        case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1.221     djm       725:                process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1.33      markus    726:                break;
                    727:        /* ssh2 */
                    728:        case SSH2_AGENTC_SIGN_REQUEST:
                    729:                process_sign_request2(e);
                    730:                break;
                    731:        case SSH2_AGENTC_REQUEST_IDENTITIES:
1.221     djm       732:                process_request_identities(e);
1.33      markus    733:                break;
                    734:        case SSH2_AGENTC_ADD_IDENTITY:
1.94      markus    735:        case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1.221     djm       736:                process_add_identity(e);
1.33      markus    737:                break;
                    738:        case SSH2_AGENTC_REMOVE_IDENTITY:
1.221     djm       739:                process_remove_identity(e);
1.33      markus    740:                break;
                    741:        case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1.221     djm       742:                process_remove_all_identities(e);
1.21      markus    743:                break;
1.163     markus    744: #ifdef ENABLE_PKCS11
1.59      markus    745:        case SSH_AGENTC_ADD_SMARTCARD_KEY:
1.110     djm       746:        case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1.59      markus    747:                process_add_smartcard_key(e);
1.75      deraadt   748:                break;
1.59      markus    749:        case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
                    750:                process_remove_smartcard_key(e);
1.75      deraadt   751:                break;
1.163     markus    752: #endif /* ENABLE_PKCS11 */
1.21      markus    753:        default:
                    754:                /* Unknown message.  Respond with failure. */
                    755:                error("Unknown message %d", type);
1.194     markus    756:                sshbuf_reset(e->request);
                    757:                send_status(e, 0);
1.21      markus    758:                break;
                    759:        }
1.223     djm       760:        return 0;
1.1       deraadt   761: }
                    762:
1.55      itojun    763: static void
1.73      stevesk   764: new_socket(sock_type type, int fd)
1.1       deraadt   765: {
1.112     markus    766:        u_int i, old_alloc, new_alloc;
1.96      deraadt   767:
1.119     djm       768:        set_nonblock(fd);
1.21      markus    769:
                    770:        if (fd > max_fd)
                    771:                max_fd = fd;
                    772:
                    773:        for (i = 0; i < sockets_alloc; i++)
                    774:                if (sockets[i].type == AUTH_UNUSED) {
                    775:                        sockets[i].fd = fd;
1.194     markus    776:                        if ((sockets[i].input = sshbuf_new()) == NULL)
                    777:                                fatal("%s: sshbuf_new failed", __func__);
                    778:                        if ((sockets[i].output = sshbuf_new()) == NULL)
                    779:                                fatal("%s: sshbuf_new failed", __func__);
                    780:                        if ((sockets[i].request = sshbuf_new()) == NULL)
                    781:                                fatal("%s: sshbuf_new failed", __func__);
1.112     markus    782:                        sockets[i].type = type;
1.21      markus    783:                        return;
                    784:                }
                    785:        old_alloc = sockets_alloc;
1.112     markus    786:        new_alloc = sockets_alloc + 10;
1.200     deraadt   787:        sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
1.112     markus    788:        for (i = old_alloc; i < new_alloc; i++)
1.21      markus    789:                sockets[i].type = AUTH_UNUSED;
1.112     markus    790:        sockets_alloc = new_alloc;
1.21      markus    791:        sockets[old_alloc].fd = fd;
1.194     markus    792:        if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
                    793:                fatal("%s: sshbuf_new failed", __func__);
                    794:        if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
                    795:                fatal("%s: sshbuf_new failed", __func__);
                    796:        if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
                    797:                fatal("%s: sshbuf_new failed", __func__);
1.112     markus    798:        sockets[old_alloc].type = type;
1.1       deraadt   799: }
                    800:
1.55      itojun    801: static int
1.223     djm       802: handle_socket_read(u_int socknum)
1.1       deraadt   803: {
1.223     djm       804:        struct sockaddr_un sunaddr;
                    805:        socklen_t slen;
                    806:        uid_t euid;
                    807:        gid_t egid;
                    808:        int fd;
                    809:
                    810:        slen = sizeof(sunaddr);
                    811:        fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
                    812:        if (fd < 0) {
                    813:                error("accept from AUTH_SOCKET: %s", strerror(errno));
                    814:                return -1;
                    815:        }
                    816:        if (getpeereid(fd, &euid, &egid) < 0) {
                    817:                error("getpeereid %d failed: %s", fd, strerror(errno));
                    818:                close(fd);
                    819:                return -1;
                    820:        }
                    821:        if ((euid != 0) && (getuid() != euid)) {
                    822:                error("uid mismatch: peer euid %u != uid %u",
                    823:                    (u_int) euid, (u_int) getuid());
                    824:                close(fd);
                    825:                return -1;
                    826:        }
                    827:        new_socket(AUTH_CONNECTION, fd);
                    828:        return 0;
                    829: }
                    830:
                    831: static int
                    832: handle_conn_read(u_int socknum)
                    833: {
1.233     djm       834:        char buf[AGENT_RBUF_LEN];
1.223     djm       835:        ssize_t len;
                    836:        int r;
                    837:
                    838:        if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
                    839:                if (len == -1) {
                    840:                        if (errno == EAGAIN || errno == EINTR)
                    841:                                return 0;
                    842:                        error("%s: read error on socket %u (fd %d): %s",
                    843:                            __func__, socknum, sockets[socknum].fd,
                    844:                            strerror(errno));
                    845:                }
                    846:                return -1;
                    847:        }
                    848:        if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
                    849:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    850:        explicit_bzero(buf, sizeof(buf));
                    851:        process_message(socknum);
                    852:        return 0;
                    853: }
                    854:
                    855: static int
                    856: handle_conn_write(u_int socknum)
                    857: {
                    858:        ssize_t len;
                    859:        int r;
                    860:
                    861:        if (sshbuf_len(sockets[socknum].output) == 0)
                    862:                return 0; /* shouldn't happen */
                    863:        if ((len = write(sockets[socknum].fd,
                    864:            sshbuf_ptr(sockets[socknum].output),
                    865:            sshbuf_len(sockets[socknum].output))) <= 0) {
                    866:                if (len == -1) {
                    867:                        if (errno == EAGAIN || errno == EINTR)
                    868:                                return 0;
                    869:                        error("%s: read error on socket %u (fd %d): %s",
                    870:                            __func__, socknum, sockets[socknum].fd,
                    871:                            strerror(errno));
                    872:                }
                    873:                return -1;
                    874:        }
                    875:        if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
                    876:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    877:        return 0;
                    878: }
                    879:
                    880: static void
1.231     djm       881: after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
1.223     djm       882: {
                    883:        size_t i;
1.231     djm       884:        u_int socknum, activefds = npfd;
1.223     djm       885:
                    886:        for (i = 0; i < npfd; i++) {
                    887:                if (pfd[i].revents == 0)
                    888:                        continue;
                    889:                /* Find sockets entry */
                    890:                for (socknum = 0; socknum < sockets_alloc; socknum++) {
                    891:                        if (sockets[socknum].type != AUTH_SOCKET &&
                    892:                            sockets[socknum].type != AUTH_CONNECTION)
                    893:                                continue;
                    894:                        if (pfd[i].fd == sockets[socknum].fd)
                    895:                                break;
                    896:                }
                    897:                if (socknum >= sockets_alloc) {
                    898:                        error("%s: no socket for fd %d", __func__, pfd[i].fd);
                    899:                        continue;
                    900:                }
                    901:                /* Process events */
                    902:                switch (sockets[socknum].type) {
                    903:                case AUTH_SOCKET:
1.231     djm       904:                        if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
                    905:                                break;
                    906:                        if (npfd > maxfds) {
                    907:                                debug3("out of fds (active %u >= limit %u); "
                    908:                                    "skipping accept", activefds, maxfds);
                    909:                                break;
                    910:                        }
                    911:                        if (handle_socket_read(socknum) == 0)
                    912:                                activefds++;
1.223     djm       913:                        break;
                    914:                case AUTH_CONNECTION:
                    915:                        if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
                    916:                            handle_conn_read(socknum) != 0) {
1.231     djm       917:                                goto close_sock;
                    918:                        }
                    919:                        if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
                    920:                            handle_conn_write(socknum) != 0) {
                    921:  close_sock:
                    922:                                if (activefds == 0)
                    923:                                        fatal("activefds == 0 at close_sock");
1.223     djm       924:                                close_socket(&sockets[socknum]);
1.231     djm       925:                                activefds--;
1.223     djm       926:                                break;
                    927:                        }
                    928:                        break;
                    929:                default:
                    930:                        break;
                    931:                }
                    932:        }
                    933: }
                    934:
                    935: static int
1.231     djm       936: prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
1.223     djm       937: {
                    938:        struct pollfd *pfd = *pfdp;
                    939:        size_t i, j, npfd = 0;
1.174     dtucker   940:        time_t deadline;
1.233     djm       941:        int r;
1.46      markus    942:
1.223     djm       943:        /* Count active sockets */
1.46      markus    944:        for (i = 0; i < sockets_alloc; i++) {
1.21      markus    945:                switch (sockets[i].type) {
                    946:                case AUTH_SOCKET:
                    947:                case AUTH_CONNECTION:
1.223     djm       948:                        npfd++;
1.21      markus    949:                        break;
                    950:                case AUTH_UNUSED:
                    951:                        break;
                    952:                default:
                    953:                        fatal("Unknown socket type %d", sockets[i].type);
                    954:                        break;
                    955:                }
1.46      markus    956:        }
1.223     djm       957:        if (npfd != *npfdp &&
                    958:            (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
                    959:                fatal("%s: recallocarray failed", __func__);
                    960:        *pfdp = pfd;
                    961:        *npfdp = npfd;
1.46      markus    962:
1.223     djm       963:        for (i = j = 0; i < sockets_alloc; i++) {
1.46      markus    964:                switch (sockets[i].type) {
                    965:                case AUTH_SOCKET:
1.231     djm       966:                        if (npfd > maxfds) {
                    967:                                debug3("out of fds (active %zu >= limit %u); "
                    968:                                    "skipping arming listener", npfd, maxfds);
                    969:                                break;
                    970:                        }
                    971:                        pfd[j].fd = sockets[i].fd;
                    972:                        pfd[j].revents = 0;
                    973:                        pfd[j].events = POLLIN;
                    974:                        j++;
                    975:                        break;
1.46      markus    976:                case AUTH_CONNECTION:
1.223     djm       977:                        pfd[j].fd = sockets[i].fd;
                    978:                        pfd[j].revents = 0;
1.233     djm       979:                        /*
                    980:                         * Only prepare to read if we can handle a full-size
                    981:                         * input read buffer and enqueue a max size reply..
                    982:                         */
                    983:                        if ((r = sshbuf_check_reserve(sockets[i].input,
                    984:                            AGENT_RBUF_LEN)) == 0 &&
                    985:                            (r = sshbuf_check_reserve(sockets[i].output,
                    986:                             AGENT_MAX_LEN)) == 0)
                    987:                                pfd[j].events = POLLIN;
                    988:                        else if (r != SSH_ERR_NO_BUFFER_SPACE) {
                    989:                                fatal("%s: buffer error: %s",
                    990:                                    __func__, ssh_err(r));
                    991:                        }
1.194     markus    992:                        if (sshbuf_len(sockets[i].output) > 0)
1.223     djm       993:                                pfd[j].events |= POLLOUT;
                    994:                        j++;
1.46      markus    995:                        break;
                    996:                default:
                    997:                        break;
                    998:                }
                    999:        }
1.155     dtucker  1000:        deadline = reaper();
                   1001:        if (parent_alive_interval != 0)
                   1002:                deadline = (deadline == 0) ? parent_alive_interval :
1.214     deraadt  1003:                    MINIMUM(deadline, parent_alive_interval);
1.155     dtucker  1004:        if (deadline == 0) {
1.224     djm      1005:                *timeoutp = -1; /* INFTIM */
1.155     dtucker  1006:        } else {
1.223     djm      1007:                if (deadline > INT_MAX / 1000)
                   1008:                        *timeoutp = INT_MAX / 1000;
                   1009:                else
                   1010:                        *timeoutp = deadline * 1000;
1.155     dtucker  1011:        }
1.46      markus   1012:        return (1);
1.21      markus   1013: }
                   1014:
1.55      itojun   1015: static void
1.113     markus   1016: cleanup_socket(void)
1.15      markus   1017: {
1.187     djm      1018:        if (cleanup_pid != 0 && getpid() != cleanup_pid)
                   1019:                return;
                   1020:        debug("%s: cleanup", __func__);
1.48      deraadt  1021:        if (socket_name[0])
                   1022:                unlink(socket_name);
                   1023:        if (socket_dir[0])
                   1024:                rmdir(socket_dir);
1.10      markus   1025: }
                   1026:
1.114     markus   1027: void
1.15      markus   1028: cleanup_exit(int i)
                   1029: {
1.113     markus   1030:        cleanup_socket();
                   1031:        _exit(i);
1.15      markus   1032: }
                   1033:
1.135     deraadt  1034: /*ARGSUSED*/
1.55      itojun   1035: static void
1.48      deraadt  1036: cleanup_handler(int sig)
                   1037: {
1.113     markus   1038:        cleanup_socket();
1.163     markus   1039: #ifdef ENABLE_PKCS11
                   1040:        pkcs11_terminate();
                   1041: #endif
1.48      deraadt  1042:        _exit(2);
1.113     markus   1043: }
                   1044:
1.68      markus   1045: static void
1.155     dtucker  1046: check_parent_exists(void)
1.68      markus   1047: {
1.172     dtucker  1048:        /*
                   1049:         * If our parent has exited then getppid() will return (pid_t)1,
                   1050:         * so testing for that should be safe.
                   1051:         */
                   1052:        if (parent_pid != -1 && getppid() != parent_pid) {
1.68      markus   1053:                /* printf("Parent has died - Authentication agent exiting.\n"); */
1.155     dtucker  1054:                cleanup_socket();
                   1055:                _exit(2);
1.68      markus   1056:        }
1.48      deraadt  1057: }
                   1058:
1.55      itojun   1059: static void
1.50      itojun   1060: usage(void)
1.15      markus   1061: {
1.184     deraadt  1062:        fprintf(stderr,
1.202     jmc      1063:            "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1.215     djm      1064:            "                 [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n"
1.184     deraadt  1065:            "       ssh-agent [-c | -s] -k\n");
1.21      markus   1066:        exit(1);
1.15      markus   1067: }
                   1068:
1.2       provos   1069: int
                   1070: main(int ac, char **av)
1.1       deraadt  1071: {
1.201     djm      1072:        int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1.154     dtucker  1073:        int sock, fd, ch, result, saved_errno;
1.96      deraadt  1074:        char *shell, *format, *pidstr, *agentsocket = NULL;
1.41      markus   1075:        struct rlimit rlim;
1.96      deraadt  1076:        extern int optind;
1.98      stevesk  1077:        extern char *optarg;
1.21      markus   1078:        pid_t pid;
1.96      deraadt  1079:        char pidstrbuf[1 + 3 * sizeof pid];
1.161     tobias   1080:        size_t len;
1.189     djm      1081:        mode_t prev_mask;
1.224     djm      1082:        int timeout = -1; /* INFTIM */
1.223     djm      1083:        struct pollfd *pfd = NULL;
                   1084:        size_t npfd = 0;
1.231     djm      1085:        u_int maxfds;
1.123     djm      1086:
                   1087:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                   1088:        sanitise_stdfd();
1.99      markus   1089:
                   1090:        /* drop */
                   1091:        setegid(getgid());
                   1092:        setgid(getgid());
1.53      markus   1093:
1.231     djm      1094:        if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
                   1095:                fatal("%s: getrlimit: %s", __progname, strerror(errno));
                   1096:
1.185     markus   1097: #ifdef WITH_OPENSSL
1.170     djm      1098:        OpenSSL_add_all_algorithms();
1.185     markus   1099: #endif
1.21      markus   1100:
1.215     djm      1101:        while ((ch = getopt(ac, av, "cDdksE:a:P:t:")) != -1) {
1.21      markus   1102:                switch (ch) {
1.192     djm      1103:                case 'E':
                   1104:                        fingerprint_hash = ssh_digest_alg_by_name(optarg);
                   1105:                        if (fingerprint_hash == -1)
                   1106:                                fatal("Invalid hash algorithm \"%s\"", optarg);
                   1107:                        break;
1.21      markus   1108:                case 'c':
                   1109:                        if (s_flag)
                   1110:                                usage();
                   1111:                        c_flag++;
                   1112:                        break;
                   1113:                case 'k':
                   1114:                        k_flag++;
                   1115:                        break;
1.215     djm      1116:                case 'P':
                   1117:                        if (pkcs11_whitelist != NULL)
                   1118:                                fatal("-P option already specified");
                   1119:                        pkcs11_whitelist = xstrdup(optarg);
                   1120:                        break;
1.21      markus   1121:                case 's':
                   1122:                        if (c_flag)
                   1123:                                usage();
                   1124:                        s_flag++;
                   1125:                        break;
1.57      markus   1126:                case 'd':
1.201     djm      1127:                        if (d_flag || D_flag)
1.57      markus   1128:                                usage();
                   1129:                        d_flag++;
                   1130:                        break;
1.201     djm      1131:                case 'D':
                   1132:                        if (d_flag || D_flag)
                   1133:                                usage();
                   1134:                        D_flag++;
                   1135:                        break;
1.86      markus   1136:                case 'a':
                   1137:                        agentsocket = optarg;
1.106     marc     1138:                        break;
                   1139:                case 't':
                   1140:                        if ((lifetime = convtime(optarg)) == -1) {
                   1141:                                fprintf(stderr, "Invalid lifetime\n");
                   1142:                                usage();
                   1143:                        }
1.86      markus   1144:                        break;
1.21      markus   1145:                default:
                   1146:                        usage();
                   1147:                }
                   1148:        }
                   1149:        ac -= optind;
                   1150:        av += optind;
                   1151:
1.201     djm      1152:        if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1.21      markus   1153:                usage();
                   1154:
1.215     djm      1155:        if (pkcs11_whitelist == NULL)
                   1156:                pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST);
                   1157:
1.85      markus   1158:        if (ac == 0 && !c_flag && !s_flag) {
1.21      markus   1159:                shell = getenv("SHELL");
1.161     tobias   1160:                if (shell != NULL && (len = strlen(shell)) > 2 &&
                   1161:                    strncmp(shell + len - 3, "csh", 3) == 0)
1.21      markus   1162:                        c_flag = 1;
                   1163:        }
                   1164:        if (k_flag) {
1.136     deraadt  1165:                const char *errstr = NULL;
                   1166:
1.21      markus   1167:                pidstr = getenv(SSH_AGENTPID_ENV_NAME);
                   1168:                if (pidstr == NULL) {
                   1169:                        fprintf(stderr, "%s not set, cannot kill agent\n",
1.46      markus   1170:                            SSH_AGENTPID_ENV_NAME);
1.21      markus   1171:                        exit(1);
                   1172:                }
1.136     deraadt  1173:                pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
                   1174:                if (errstr) {
                   1175:                        fprintf(stderr,
                   1176:                            "%s=\"%s\", which is not a good PID: %s\n",
                   1177:                            SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1.21      markus   1178:                        exit(1);
                   1179:                }
                   1180:                if (kill(pid, SIGTERM) == -1) {
                   1181:                        perror("kill");
                   1182:                        exit(1);
                   1183:                }
                   1184:                format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1.140     djm      1185:                printf(format, SSH_AUTHSOCKET_ENV_NAME);
                   1186:                printf(format, SSH_AGENTPID_ENV_NAME);
1.91      mpech    1187:                printf("echo Agent pid %ld killed;\n", (long)pid);
1.21      markus   1188:                exit(0);
                   1189:        }
1.231     djm      1190:
                   1191:        /*
                   1192:         * Minimum file descriptors:
                   1193:         * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
                   1194:         * a few spare for libc / stack protectors / sanitisers, etc.
                   1195:         */
                   1196: #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
                   1197:        if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
1.232     djm      1198:                fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
1.231     djm      1199:                    __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
                   1200:        maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
                   1201:
1.21      markus   1202:        parent_pid = getpid();
                   1203:
1.86      markus   1204:        if (agentsocket == NULL) {
                   1205:                /* Create private directory for agent socket */
1.171     djm      1206:                mktemp_proto(socket_dir, sizeof(socket_dir));
1.86      markus   1207:                if (mkdtemp(socket_dir) == NULL) {
                   1208:                        perror("mkdtemp: private socket dir");
                   1209:                        exit(1);
                   1210:                }
1.91      mpech    1211:                snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
                   1212:                    (long)parent_pid);
1.86      markus   1213:        } else {
                   1214:                /* Try to use specified agent socket */
                   1215:                socket_dir[0] = '\0';
                   1216:                strlcpy(socket_name, agentsocket, sizeof socket_name);
1.21      markus   1217:        }
                   1218:
1.23      markus   1219:        /*
                   1220:         * Create socket early so it will exist before command gets run from
                   1221:         * the parent.
                   1222:         */
1.189     djm      1223:        prev_mask = umask(0177);
1.188     millert  1224:        sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1.21      markus   1225:        if (sock < 0) {
1.188     millert  1226:                /* XXX - unix_listener() calls error() not perror() */
1.121     djm      1227:                *socket_name = '\0'; /* Don't unlink any existing file */
1.21      markus   1228:                cleanup_exit(1);
                   1229:        }
1.189     djm      1230:        umask(prev_mask);
1.46      markus   1231:
1.23      markus   1232:        /*
                   1233:         * Fork, and have the parent execute the command, if any, or present
                   1234:         * the socket data.  The child continues as the authentication agent.
                   1235:         */
1.201     djm      1236:        if (D_flag || d_flag) {
                   1237:                log_init(__progname,
                   1238:                    d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
                   1239:                    SYSLOG_FACILITY_AUTH, 1);
1.57      markus   1240:                format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
                   1241:                printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
                   1242:                    SSH_AUTHSOCKET_ENV_NAME);
1.91      mpech    1243:                printf("echo Agent pid %ld;\n", (long)parent_pid);
1.210     dtucker  1244:                fflush(stdout);
1.57      markus   1245:                goto skip;
                   1246:        }
1.21      markus   1247:        pid = fork();
                   1248:        if (pid == -1) {
                   1249:                perror("fork");
1.81      stevesk  1250:                cleanup_exit(1);
1.21      markus   1251:        }
                   1252:        if (pid != 0) {         /* Parent - execute the given command. */
                   1253:                close(sock);
1.91      mpech    1254:                snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1.21      markus   1255:                if (ac == 0) {
                   1256:                        format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
                   1257:                        printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1.46      markus   1258:                            SSH_AUTHSOCKET_ENV_NAME);
1.21      markus   1259:                        printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1.46      markus   1260:                            SSH_AGENTPID_ENV_NAME);
1.91      mpech    1261:                        printf("echo Agent pid %ld;\n", (long)pid);
1.21      markus   1262:                        exit(0);
                   1263:                }
1.36      deraadt  1264:                if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
                   1265:                    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
                   1266:                        perror("setenv");
                   1267:                        exit(1);
                   1268:                }
1.21      markus   1269:                execvp(av[0], av);
                   1270:                perror(av[0]);
                   1271:                exit(1);
                   1272:        }
1.81      stevesk  1273:        /* child */
                   1274:        log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1.67      stevesk  1275:
                   1276:        if (setsid() == -1) {
1.81      stevesk  1277:                error("setsid: %s", strerror(errno));
1.67      stevesk  1278:                cleanup_exit(1);
                   1279:        }
                   1280:
                   1281:        (void)chdir("/");
1.107     markus   1282:        if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                   1283:                /* XXX might close listen socket */
                   1284:                (void)dup2(fd, STDIN_FILENO);
                   1285:                (void)dup2(fd, STDOUT_FILENO);
                   1286:                (void)dup2(fd, STDERR_FILENO);
                   1287:                if (fd > 2)
                   1288:                        close(fd);
                   1289:        }
1.21      markus   1290:
1.41      markus   1291:        /* deny core dumps, since memory contains unencrypted private keys */
                   1292:        rlim.rlim_cur = rlim.rlim_max = 0;
                   1293:        if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1.81      stevesk  1294:                error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1.21      markus   1295:                cleanup_exit(1);
                   1296:        }
1.57      markus   1297:
                   1298: skip:
1.187     djm      1299:
                   1300:        cleanup_pid = getpid();
1.163     markus   1301:
                   1302: #ifdef ENABLE_PKCS11
                   1303:        pkcs11_init(0);
                   1304: #endif
1.21      markus   1305:        new_socket(AUTH_SOCKET, sock);
1.155     dtucker  1306:        if (ac > 0)
                   1307:                parent_alive_interval = 10;
1.33      markus   1308:        idtab_init();
1.61      markus   1309:        signal(SIGPIPE, SIG_IGN);
1.201     djm      1310:        signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1.48      deraadt  1311:        signal(SIGHUP, cleanup_handler);
                   1312:        signal(SIGTERM, cleanup_handler);
1.205     djm      1313:
1.215     djm      1314:        if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1.205     djm      1315:                fatal("%s: pledge: %s", __progname, strerror(errno));
1.66      markus   1316:
1.21      markus   1317:        while (1) {
1.231     djm      1318:                prepare_poll(&pfd, &npfd, &timeout, maxfds);
1.223     djm      1319:                result = poll(pfd, npfd, timeout);
1.154     dtucker  1320:                saved_errno = errno;
1.155     dtucker  1321:                if (parent_alive_interval != 0)
                   1322:                        check_parent_exists();
                   1323:                (void) reaper();        /* remove expired keys */
1.154     dtucker  1324:                if (result < 0) {
                   1325:                        if (saved_errno == EINTR)
1.21      markus   1326:                                continue;
1.223     djm      1327:                        fatal("poll: %s", strerror(saved_errno));
1.154     dtucker  1328:                } else if (result > 0)
1.231     djm      1329:                        after_poll(pfd, npfd, maxfds);
1.15      markus   1330:        }
1.21      markus   1331:        /* NOTREACHED */
1.1       deraadt  1332: }