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

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