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

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