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

1.195   ! djm         1: /* $OpenBSD: ssh-agent.c,v 1.194 2015/01/14 13:09:09 markus 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;
1.195   ! djm       360:        struct identity *id;
1.194     markus    361:
1.195   ! djm       362:        if ((msg = sshbuf_new()) == NULL)
        !           363:                fatal("%s: sshbuf_new failed", __func__);
1.194     markus    364:        if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 ||
                    365:            (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 ||
                    366:            (r = sshbuf_get_u32(e->request, &flags)) != 0)
                    367:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.37      markus    368:        if (flags & SSH_AGENT_OLD_SIGNATURE)
1.194     markus    369:                compat = SSH_BUG_SIGBLOB;
1.195   ! djm       370:        if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
1.194     markus    371:                error("%s: cannot parse key blob: %s", __func__, ssh_err(ok));
1.195   ! djm       372:                goto send;
        !           373:        }
        !           374:        if ((id = lookup_identity(key, 2)) == NULL) {
        !           375:                verbose("%s: %s key not found", __func__, sshkey_type(key));
        !           376:                goto send;
        !           377:        }
        !           378:        if (id->confirm && confirm_key(id) != 0) {
        !           379:                verbose("%s: user refused key", __func__);
        !           380:                goto send;
        !           381:        }
        !           382:        if ((r = sshkey_sign(id->key, &signature, &slen,
        !           383:            data, dlen, compat)) != 0) {
        !           384:                error("%s: sshkey_sign: %s", __func__, ssh_err(ok));
        !           385:                goto send;
1.33      markus    386:        }
1.195   ! djm       387:        /* Success */
        !           388:        ok = 0;
        !           389:  send:
        !           390:        sshkey_free(key);
1.33      markus    391:        if (ok == 0) {
1.194     markus    392:                if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
                    393:                    (r = sshbuf_put_string(msg, signature, slen)) != 0)
                    394:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    395:        } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
                    396:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    397:
                    398:        if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
                    399:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    400:
                    401:        sshbuf_free(msg);
1.173     djm       402:        free(data);
                    403:        free(blob);
                    404:        free(signature);
1.1       deraadt   405: }
                    406:
1.33      markus    407: /* shared */
1.55      itojun    408: static void
1.33      markus    409: process_remove_identity(SocketEntry *e, int version)
1.1       deraadt   410: {
1.194     markus    411:        size_t blen;
                    412:        int r, success = 0;
                    413:        struct sshkey *key = NULL;
1.45      markus    414:        u_char *blob;
1.186     djm       415: #ifdef WITH_SSH1
                    416:        u_int bits;
                    417: #endif /* WITH_SSH1 */
1.21      markus    418:
1.74      deraadt   419:        switch (version) {
1.186     djm       420: #ifdef WITH_SSH1
1.33      markus    421:        case 1:
1.194     markus    422:                if ((key = sshkey_new(KEY_RSA1)) == NULL) {
                    423:                        error("%s: sshkey_new failed", __func__);
                    424:                        return;
                    425:                }
                    426:                if ((r = sshbuf_get_u32(e->request, &bits)) != 0 ||
                    427:                    (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
                    428:                    (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0)
                    429:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    430:
                    431:                if (bits != sshkey_size(key))
                    432:                        logit("Warning: identity keysize mismatch: "
                    433:                            "actual %u, announced %u",
                    434:                            sshkey_size(key), bits);
1.33      markus    435:                break;
1.186     djm       436: #endif /* WITH_SSH1 */
1.33      markus    437:        case 2:
1.194     markus    438:                if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0)
                    439:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    440:                if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
                    441:                        error("%s: sshkey_from_blob failed: %s",
                    442:                            __func__, ssh_err(r));
1.173     djm       443:                free(blob);
1.33      markus    444:                break;
                    445:        }
                    446:        if (key != NULL) {
1.78      provos    447:                Identity *id = lookup_identity(key, version);
                    448:                if (id != NULL) {
1.23      markus    449:                        /*
                    450:                         * We have this key.  Free the old key.  Since we
1.124     djm       451:                         * don't want to leave empty slots in the middle of
1.40      markus    452:                         * the array, we actually free the key there and move
                    453:                         * all the entries between the empty slot and the end
                    454:                         * of the array.
1.23      markus    455:                         */
1.33      markus    456:                        Idtab *tab = idtab_lookup(version);
1.38      markus    457:                        if (tab->nentries < 1)
                    458:                                fatal("process_remove_identity: "
                    459:                                    "internal error: tab->nentries %d",
                    460:                                    tab->nentries);
1.78      provos    461:                        TAILQ_REMOVE(&tab->idlist, id, next);
                    462:                        free_identity(id);
1.33      markus    463:                        tab->nentries--;
                    464:                        success = 1;
1.21      markus    465:                }
1.194     markus    466:                sshkey_free(key);
1.33      markus    467:        }
1.194     markus    468:        send_status(e, success);
1.1       deraadt   469: }
                    470:
1.55      itojun    471: static void
1.33      markus    472: process_remove_all_identities(SocketEntry *e, int version)
1.1       deraadt   473: {
1.33      markus    474:        Idtab *tab = idtab_lookup(version);
1.78      provos    475:        Identity *id;
1.21      markus    476:
                    477:        /* Loop over all identities and clear the keys. */
1.78      provos    478:        for (id = TAILQ_FIRST(&tab->idlist); id;
                    479:            id = TAILQ_FIRST(&tab->idlist)) {
                    480:                TAILQ_REMOVE(&tab->idlist, id, next);
                    481:                free_identity(id);
1.21      markus    482:        }
                    483:
                    484:        /* Mark that there are no identities. */
1.33      markus    485:        tab->nentries = 0;
1.21      markus    486:
                    487:        /* Send success. */
1.194     markus    488:        send_status(e, 1);
1.1       deraadt   489: }
                    490:
1.155     dtucker   491: /* removes expired keys and returns number of seconds until the next expiry */
1.174     dtucker   492: static time_t
1.89      markus    493: reaper(void)
                    494: {
1.175     dtucker   495:        time_t deadline = 0, now = monotime();
1.89      markus    496:        Identity *id, *nxt;
                    497:        int version;
1.96      deraadt   498:        Idtab *tab;
1.89      markus    499:
                    500:        for (version = 1; version < 3; version++) {
                    501:                tab = idtab_lookup(version);
                    502:                for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
                    503:                        nxt = TAILQ_NEXT(id, next);
1.155     dtucker   504:                        if (id->death == 0)
                    505:                                continue;
                    506:                        if (now >= id->death) {
1.154     dtucker   507:                                debug("expiring key '%s'", id->comment);
1.89      markus    508:                                TAILQ_REMOVE(&tab->idlist, id, next);
                    509:                                free_identity(id);
                    510:                                tab->nentries--;
1.155     dtucker   511:                        } else
                    512:                                deadline = (deadline == 0) ? id->death :
                    513:                                    MIN(deadline, id->death);
1.89      markus    514:                }
                    515:        }
1.155     dtucker   516:        if (deadline == 0 || deadline <= now)
                    517:                return 0;
                    518:        else
                    519:                return (deadline - now);
1.89      markus    520: }
                    521:
1.194     markus    522: /*
                    523:  * XXX this and the corresponding serialisation function probably belongs
                    524:  * in key.c
                    525:  */
                    526: static int
                    527: agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp)
                    528: {
                    529:        struct sshkey *k = NULL;
                    530:        int r = SSH_ERR_INTERNAL_ERROR;
                    531:
                    532:        *kp = NULL;
                    533:        if ((k = sshkey_new_private(KEY_RSA1)) == NULL)
                    534:                return SSH_ERR_ALLOC_FAIL;
                    535:
                    536:        if ((r = sshbuf_get_u32(m, NULL)) != 0 ||               /* ignored */
                    537:            (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 ||
                    538:            (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 ||
                    539:            (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 ||
                    540:            (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 ||
                    541:            /* SSH1 and SSL have p and q swapped */
                    542:            (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 ||      /* p */
                    543:            (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0)        /* q */
                    544:                goto out;
                    545:
                    546:        /* Generate additional parameters */
                    547:        if ((r = rsa_generate_additional_parameters(k->rsa)) != 0)
                    548:                goto out;
                    549:        /* enable blinding */
                    550:        if (RSA_blinding_on(k->rsa, NULL) != 1) {
                    551:                r = SSH_ERR_LIBCRYPTO_ERROR;
                    552:                goto out;
                    553:        }
                    554:
                    555:        r = 0; /* success */
                    556:  out:
                    557:        if (r == 0)
                    558:                *kp = k;
                    559:        else
                    560:                sshkey_free(k);
                    561:        return r;
                    562: }
                    563:
1.89      markus    564: static void
1.33      markus    565: process_add_identity(SocketEntry *e, int version)
1.1       deraadt   566: {
1.96      deraadt   567:        Idtab *tab = idtab_lookup(version);
1.157     canacar   568:        Identity *id;
1.194     markus    569:        int success = 0, confirm = 0;
                    570:        u_int seconds;
                    571:        char *comment = NULL;
1.174     dtucker   572:        time_t death = 0;
1.194     markus    573:        struct sshkey *k = NULL;
                    574:        u_char ctype;
                    575:        int r = SSH_ERR_INTERNAL_ERROR;
1.33      markus    576:
                    577:        switch (version) {
1.186     djm       578: #ifdef WITH_SSH1
1.33      markus    579:        case 1:
1.194     markus    580:                r = agent_decode_rsa1(e->request, &k);
1.33      markus    581:                break;
1.186     djm       582: #endif /* WITH_SSH1 */
1.33      markus    583:        case 2:
1.194     markus    584:                r = sshkey_private_deserialize(e->request, &k);
1.33      markus    585:                break;
                    586:        }
1.194     markus    587:        if (r != 0 || k == NULL ||
                    588:            (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
                    589:                error("%s: decode private key: %s", __func__, ssh_err(r));
                    590:                goto err;
                    591:        }
1.186     djm       592:
1.194     markus    593:        while (sshbuf_len(e->request)) {
                    594:                if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
                    595:                        error("%s: buffer error: %s", __func__, ssh_err(r));
                    596:                        goto err;
                    597:                }
                    598:                switch (ctype) {
1.94      markus    599:                case SSH_AGENT_CONSTRAIN_LIFETIME:
1.194     markus    600:                        if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
                    601:                                error("%s: bad lifetime constraint: %s",
                    602:                                    __func__, ssh_err(r));
                    603:                                goto err;
                    604:                        }
                    605:                        death = monotime() + seconds;
1.94      markus    606:                        break;
1.107     markus    607:                case SSH_AGENT_CONSTRAIN_CONFIRM:
                    608:                        confirm = 1;
                    609:                        break;
1.94      markus    610:                default:
1.194     markus    611:                        error("%s: Unknown constraint %d", __func__, ctype);
                    612:  err:
                    613:                        sshbuf_reset(e->request);
1.173     djm       614:                        free(comment);
1.194     markus    615:                        sshkey_free(k);
1.158     djm       616:                        goto send;
1.94      markus    617:                }
                    618:        }
1.194     markus    619:
1.158     djm       620:        success = 1;
1.106     marc      621:        if (lifetime && !death)
1.175     dtucker   622:                death = monotime() + lifetime;
1.157     canacar   623:        if ((id = lookup_identity(k, version)) == NULL) {
1.163     markus    624:                id = xcalloc(1, sizeof(Identity));
1.78      provos    625:                id->key = k;
                    626:                TAILQ_INSERT_TAIL(&tab->idlist, id, next);
1.33      markus    627:                /* Increment the number of identities. */
                    628:                tab->nentries++;
                    629:        } else {
1.194     markus    630:                sshkey_free(k);
1.173     djm       631:                free(id->comment);
1.33      markus    632:        }
1.157     canacar   633:        id->comment = comment;
                    634:        id->death = death;
                    635:        id->confirm = confirm;
1.33      markus    636: send:
1.194     markus    637:        send_status(e, success);
1.1       deraadt   638: }
                    639:
1.88      markus    640: /* XXX todo: encrypt sensitive data with passphrase */
                    641: static void
                    642: process_lock_agent(SocketEntry *e, int lock)
                    643: {
1.194     markus    644:        int r, success = 0;
1.88      markus    645:        char *passwd;
                    646:
1.194     markus    647:        if ((r = sshbuf_get_cstring(e->request, &passwd, NULL)) != 0)
                    648:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.88      markus    649:        if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
                    650:                locked = 0;
1.183     djm       651:                explicit_bzero(lock_passwd, strlen(lock_passwd));
1.173     djm       652:                free(lock_passwd);
1.88      markus    653:                lock_passwd = NULL;
                    654:                success = 1;
                    655:        } else if (!locked && lock) {
                    656:                locked = 1;
                    657:                lock_passwd = xstrdup(passwd);
                    658:                success = 1;
                    659:        }
1.183     djm       660:        explicit_bzero(passwd, strlen(passwd));
1.173     djm       661:        free(passwd);
1.194     markus    662:        send_status(e, success);
1.88      markus    663: }
                    664:
                    665: static void
                    666: no_identities(SocketEntry *e, u_int type)
                    667: {
1.194     markus    668:        struct sshbuf *msg;
                    669:        int r;
1.88      markus    670:
1.194     markus    671:        if ((msg = sshbuf_new()) == NULL)
                    672:                fatal("%s: sshbuf_new failed", __func__);
                    673:        if ((r = sshbuf_put_u8(msg,
1.88      markus    674:            (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
1.194     markus    675:            SSH_AGENT_RSA_IDENTITIES_ANSWER :
                    676:            SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
                    677:            (r = sshbuf_put_u32(msg, 0)) != 0 ||
                    678:            (r = sshbuf_put_stringb(e->output, msg)) != 0)
                    679:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    680:        sshbuf_free(msg);
1.88      markus    681: }
1.59      markus    682:
1.163     markus    683: #ifdef ENABLE_PKCS11
1.59      markus    684: static void
1.158     djm       685: process_add_smartcard_key(SocketEntry *e)
1.59      markus    686: {
1.163     markus    687:        char *provider = NULL, *pin;
1.194     markus    688:        int r, i, version, count = 0, success = 0, confirm = 0;
                    689:        u_int seconds;
1.174     dtucker   690:        time_t death = 0;
1.194     markus    691:        u_char type;
                    692:        struct sshkey **keys = NULL, *k;
1.84      markus    693:        Identity *id;
1.59      markus    694:        Idtab *tab;
1.75      deraadt   695:
1.194     markus    696:        if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
                    697:            (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
                    698:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    699:
                    700:        while (sshbuf_len(e->request)) {
                    701:                if ((r = sshbuf_get_u8(e->request, &type)) != 0)
                    702:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    703:                switch (type) {
1.110     djm       704:                case SSH_AGENT_CONSTRAIN_LIFETIME:
1.194     markus    705:                        if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
                    706:                                fatal("%s: buffer error: %s",
                    707:                                    __func__, ssh_err(r));
                    708:                        death = monotime() + seconds;
1.110     djm       709:                        break;
                    710:                case SSH_AGENT_CONSTRAIN_CONFIRM:
                    711:                        confirm = 1;
                    712:                        break;
                    713:                default:
1.158     djm       714:                        error("process_add_smartcard_key: "
                    715:                            "Unknown constraint type %d", type);
                    716:                        goto send;
1.110     djm       717:                }
                    718:        }
                    719:        if (lifetime && !death)
1.175     dtucker   720:                death = monotime() + lifetime;
1.110     djm       721:
1.163     markus    722:        count = pkcs11_add_provider(provider, pin, &keys);
                    723:        for (i = 0; i < count; i++) {
1.84      markus    724:                k = keys[i];
                    725:                version = k->type == KEY_RSA1 ? 1 : 2;
                    726:                tab = idtab_lookup(version);
                    727:                if (lookup_identity(k, version) == NULL) {
1.163     markus    728:                        id = xcalloc(1, sizeof(Identity));
1.84      markus    729:                        id->key = k;
1.163     markus    730:                        id->provider = xstrdup(provider);
                    731:                        id->comment = xstrdup(provider); /* XXX */
1.110     djm       732:                        id->death = death;
                    733:                        id->confirm = confirm;
1.84      markus    734:                        TAILQ_INSERT_TAIL(&tab->idlist, id, next);
                    735:                        tab->nentries++;
                    736:                        success = 1;
                    737:                } else {
1.194     markus    738:                        sshkey_free(k);
1.84      markus    739:                }
                    740:                keys[i] = NULL;
1.59      markus    741:        }
                    742: send:
1.173     djm       743:        free(pin);
                    744:        free(provider);
                    745:        free(keys);
1.194     markus    746:        send_status(e, success);
1.59      markus    747: }
                    748:
                    749: static void
                    750: process_remove_smartcard_key(SocketEntry *e)
                    751: {
1.163     markus    752:        char *provider = NULL, *pin = NULL;
1.194     markus    753:        int r, version, success = 0;
1.163     markus    754:        Identity *id, *nxt;
1.84      markus    755:        Idtab *tab;
1.59      markus    756:
1.194     markus    757:        if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
                    758:            (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
                    759:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.173     djm       760:        free(pin);
1.59      markus    761:
1.163     markus    762:        for (version = 1; version < 3; version++) {
                    763:                tab = idtab_lookup(version);
                    764:                for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
                    765:                        nxt = TAILQ_NEXT(id, next);
1.181     djm       766:                        /* Skip file--based keys */
                    767:                        if (id->provider == NULL)
                    768:                                continue;
1.163     markus    769:                        if (!strcmp(provider, id->provider)) {
                    770:                                TAILQ_REMOVE(&tab->idlist, id, next);
                    771:                                free_identity(id);
                    772:                                tab->nentries--;
                    773:                        }
1.59      markus    774:                }
                    775:        }
1.163     markus    776:        if (pkcs11_del_provider(provider) == 0)
                    777:                success = 1;
                    778:        else
                    779:                error("process_remove_smartcard_key:"
                    780:                    " pkcs11_del_provider failed");
1.173     djm       781:        free(provider);
1.194     markus    782:        send_status(e, success);
1.59      markus    783: }
1.163     markus    784: #endif /* ENABLE_PKCS11 */
1.59      markus    785:
1.33      markus    786: /* dispatch incoming messages */
                    787:
1.55      itojun    788: static void
1.2       provos    789: process_message(SocketEntry *e)
1.1       deraadt   790: {
1.194     markus    791:        u_int msg_len;
                    792:        u_char type;
                    793:        const u_char *cp;
                    794:        int r;
1.89      markus    795:
1.194     markus    796:        if (sshbuf_len(e->input) < 5)
1.21      markus    797:                return;         /* Incomplete message. */
1.194     markus    798:        cp = sshbuf_ptr(e->input);
                    799:        msg_len = PEEK_U32(cp);
1.21      markus    800:        if (msg_len > 256 * 1024) {
1.101     stevesk   801:                close_socket(e);
1.21      markus    802:                return;
                    803:        }
1.194     markus    804:        if (sshbuf_len(e->input) < msg_len + 4)
1.21      markus    805:                return;
1.87      markus    806:
                    807:        /* move the current input to e->request */
1.194     markus    808:        sshbuf_reset(e->request);
                    809:        if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
                    810:            (r = sshbuf_get_u8(e->request, &type)) != 0)
                    811:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.21      markus    812:
1.88      markus    813:        /* check wheter agent is locked */
                    814:        if (locked && type != SSH_AGENTC_UNLOCK) {
1.194     markus    815:                sshbuf_reset(e->request);
1.88      markus    816:                switch (type) {
                    817:                case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
                    818:                case SSH2_AGENTC_REQUEST_IDENTITIES:
                    819:                        /* send empty lists */
                    820:                        no_identities(e, type);
                    821:                        break;
                    822:                default:
                    823:                        /* send a fail message for all other request types */
1.194     markus    824:                        send_status(e, 0);
1.88      markus    825:                }
                    826:                return;
                    827:        }
                    828:
1.59      markus    829:        debug("type %d", type);
1.21      markus    830:        switch (type) {
1.88      markus    831:        case SSH_AGENTC_LOCK:
                    832:        case SSH_AGENTC_UNLOCK:
                    833:                process_lock_agent(e, type == SSH_AGENTC_LOCK);
                    834:                break;
1.185     markus    835: #ifdef WITH_SSH1
1.33      markus    836:        /* ssh1 */
                    837:        case SSH_AGENTC_RSA_CHALLENGE:
                    838:                process_authentication_challenge1(e);
                    839:                break;
1.21      markus    840:        case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
1.33      markus    841:                process_request_identities(e, 1);
1.21      markus    842:                break;
                    843:        case SSH_AGENTC_ADD_RSA_IDENTITY:
1.94      markus    844:        case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
1.33      markus    845:                process_add_identity(e, 1);
1.21      markus    846:                break;
                    847:        case SSH_AGENTC_REMOVE_RSA_IDENTITY:
1.33      markus    848:                process_remove_identity(e, 1);
1.21      markus    849:                break;
                    850:        case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1.33      markus    851:                process_remove_all_identities(e, 1);
                    852:                break;
1.185     markus    853: #endif
1.33      markus    854:        /* ssh2 */
                    855:        case SSH2_AGENTC_SIGN_REQUEST:
                    856:                process_sign_request2(e);
                    857:                break;
                    858:        case SSH2_AGENTC_REQUEST_IDENTITIES:
                    859:                process_request_identities(e, 2);
                    860:                break;
                    861:        case SSH2_AGENTC_ADD_IDENTITY:
1.94      markus    862:        case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1.33      markus    863:                process_add_identity(e, 2);
                    864:                break;
                    865:        case SSH2_AGENTC_REMOVE_IDENTITY:
                    866:                process_remove_identity(e, 2);
                    867:                break;
                    868:        case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
                    869:                process_remove_all_identities(e, 2);
1.21      markus    870:                break;
1.163     markus    871: #ifdef ENABLE_PKCS11
1.59      markus    872:        case SSH_AGENTC_ADD_SMARTCARD_KEY:
1.110     djm       873:        case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1.59      markus    874:                process_add_smartcard_key(e);
1.75      deraadt   875:                break;
1.59      markus    876:        case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
                    877:                process_remove_smartcard_key(e);
1.75      deraadt   878:                break;
1.163     markus    879: #endif /* ENABLE_PKCS11 */
1.21      markus    880:        default:
                    881:                /* Unknown message.  Respond with failure. */
                    882:                error("Unknown message %d", type);
1.194     markus    883:                sshbuf_reset(e->request);
                    884:                send_status(e, 0);
1.21      markus    885:                break;
                    886:        }
1.1       deraadt   887: }
                    888:
1.55      itojun    889: static void
1.73      stevesk   890: new_socket(sock_type type, int fd)
1.1       deraadt   891: {
1.112     markus    892:        u_int i, old_alloc, new_alloc;
1.96      deraadt   893:
1.119     djm       894:        set_nonblock(fd);
1.21      markus    895:
                    896:        if (fd > max_fd)
                    897:                max_fd = fd;
                    898:
                    899:        for (i = 0; i < sockets_alloc; i++)
                    900:                if (sockets[i].type == AUTH_UNUSED) {
                    901:                        sockets[i].fd = fd;
1.194     markus    902:                        if ((sockets[i].input = sshbuf_new()) == NULL)
                    903:                                fatal("%s: sshbuf_new failed", __func__);
                    904:                        if ((sockets[i].output = sshbuf_new()) == NULL)
                    905:                                fatal("%s: sshbuf_new failed", __func__);
                    906:                        if ((sockets[i].request = sshbuf_new()) == NULL)
                    907:                                fatal("%s: sshbuf_new failed", __func__);
1.112     markus    908:                        sockets[i].type = type;
1.21      markus    909:                        return;
                    910:                }
                    911:        old_alloc = sockets_alloc;
1.112     markus    912:        new_alloc = sockets_alloc + 10;
1.133     djm       913:        sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
1.112     markus    914:        for (i = old_alloc; i < new_alloc; i++)
1.21      markus    915:                sockets[i].type = AUTH_UNUSED;
1.112     markus    916:        sockets_alloc = new_alloc;
1.21      markus    917:        sockets[old_alloc].fd = fd;
1.194     markus    918:        if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
                    919:                fatal("%s: sshbuf_new failed", __func__);
                    920:        if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
                    921:                fatal("%s: sshbuf_new failed", __func__);
                    922:        if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
                    923:                fatal("%s: sshbuf_new failed", __func__);
1.112     markus    924:        sockets[old_alloc].type = type;
1.1       deraadt   925: }
                    926:
1.55      itojun    927: static int
1.155     dtucker   928: prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
                    929:     struct timeval **tvpp)
1.1       deraadt   930: {
1.174     dtucker   931:        u_int i, sz;
1.46      markus    932:        int n = 0;
1.155     dtucker   933:        static struct timeval tv;
1.174     dtucker   934:        time_t deadline;
1.46      markus    935:
                    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.46      markus    940:                        n = MAX(n, sockets[i].fd);
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:        }
                    949:
                    950:        sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1.66      markus    951:        if (*fdrp == NULL || sz > *nallocp) {
1.173     djm       952:                free(*fdrp);
                    953:                free(*fdwp);
1.46      markus    954:                *fdrp = xmalloc(sz);
                    955:                *fdwp = xmalloc(sz);
1.66      markus    956:                *nallocp = sz;
1.46      markus    957:        }
1.66      markus    958:        if (n < *fdl)
                    959:                debug("XXX shrink: %d < %d", n, *fdl);
                    960:        *fdl = n;
1.46      markus    961:        memset(*fdrp, 0, sz);
                    962:        memset(*fdwp, 0, sz);
                    963:
                    964:        for (i = 0; i < sockets_alloc; i++) {
                    965:                switch (sockets[i].type) {
                    966:                case AUTH_SOCKET:
                    967:                case AUTH_CONNECTION:
                    968:                        FD_SET(sockets[i].fd, *fdrp);
1.194     markus    969:                        if (sshbuf_len(sockets[i].output) > 0)
1.46      markus    970:                                FD_SET(sockets[i].fd, *fdwp);
                    971:                        break;
                    972:                default:
                    973:                        break;
                    974:                }
                    975:        }
1.155     dtucker   976:        deadline = reaper();
                    977:        if (parent_alive_interval != 0)
                    978:                deadline = (deadline == 0) ? parent_alive_interval :
                    979:                    MIN(deadline, parent_alive_interval);
                    980:        if (deadline == 0) {
                    981:                *tvpp = NULL;
                    982:        } else {
                    983:                tv.tv_sec = deadline;
                    984:                tv.tv_usec = 0;
                    985:                *tvpp = &tv;
                    986:        }
1.46      markus    987:        return (1);
1.21      markus    988: }
                    989:
1.55      itojun    990: static void
1.21      markus    991: after_select(fd_set *readset, fd_set *writeset)
                    992: {
1.96      deraadt   993:        struct sockaddr_un sunaddr;
1.26      markus    994:        socklen_t slen;
1.21      markus    995:        char buf[1024];
1.194     markus    996:        int len, sock, r;
1.162     djm       997:        u_int i, orig_alloc;
1.103     markus    998:        uid_t euid;
                    999:        gid_t egid;
1.21      markus   1000:
1.162     djm      1001:        for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1.21      markus   1002:                switch (sockets[i].type) {
                   1003:                case AUTH_UNUSED:
                   1004:                        break;
                   1005:                case AUTH_SOCKET:
                   1006:                        if (FD_ISSET(sockets[i].fd, readset)) {
1.26      markus   1007:                                slen = sizeof(sunaddr);
1.46      markus   1008:                                sock = accept(sockets[i].fd,
1.131     deraadt  1009:                                    (struct sockaddr *)&sunaddr, &slen);
1.21      markus   1010:                                if (sock < 0) {
1.81      stevesk  1011:                                        error("accept from AUTH_SOCKET: %s",
                   1012:                                            strerror(errno));
1.103     markus   1013:                                        break;
                   1014:                                }
                   1015:                                if (getpeereid(sock, &euid, &egid) < 0) {
                   1016:                                        error("getpeereid %d failed: %s",
                   1017:                                            sock, strerror(errno));
                   1018:                                        close(sock);
                   1019:                                        break;
                   1020:                                }
1.105     markus   1021:                                if ((euid != 0) && (getuid() != euid)) {
1.103     markus   1022:                                        error("uid mismatch: "
1.104     stevesk  1023:                                            "peer euid %u != uid %u",
                   1024:                                            (u_int) euid, (u_int) getuid());
1.103     markus   1025:                                        close(sock);
1.21      markus   1026:                                        break;
                   1027:                                }
                   1028:                                new_socket(AUTH_CONNECTION, sock);
                   1029:                        }
                   1030:                        break;
                   1031:                case AUTH_CONNECTION:
1.194     markus   1032:                        if (sshbuf_len(sockets[i].output) > 0 &&
1.21      markus   1033:                            FD_ISSET(sockets[i].fd, writeset)) {
1.162     djm      1034:                                len = write(sockets[i].fd,
1.194     markus   1035:                                    sshbuf_ptr(sockets[i].output),
                   1036:                                    sshbuf_len(sockets[i].output));
1.162     djm      1037:                                if (len == -1 && (errno == EAGAIN ||
                   1038:                                    errno == EINTR))
                   1039:                                        continue;
1.21      markus   1040:                                if (len <= 0) {
1.101     stevesk  1041:                                        close_socket(&sockets[i]);
1.21      markus   1042:                                        break;
                   1043:                                }
1.194     markus   1044:                                if ((r = sshbuf_consume(sockets[i].output,
                   1045:                                    len)) != 0)
                   1046:                                        fatal("%s: buffer error: %s",
                   1047:                                            __func__, ssh_err(r));
1.21      markus   1048:                        }
                   1049:                        if (FD_ISSET(sockets[i].fd, readset)) {
1.162     djm      1050:                                len = read(sockets[i].fd, buf, sizeof(buf));
                   1051:                                if (len == -1 && (errno == EAGAIN ||
                   1052:                                    errno == EINTR))
                   1053:                                        continue;
1.21      markus   1054:                                if (len <= 0) {
1.101     stevesk  1055:                                        close_socket(&sockets[i]);
1.21      markus   1056:                                        break;
                   1057:                                }
1.194     markus   1058:                                if ((r = sshbuf_put(sockets[i].input,
                   1059:                                    buf, len)) != 0)
                   1060:                                        fatal("%s: buffer error: %s",
                   1061:                                            __func__, ssh_err(r));
1.190     dtucker  1062:                                explicit_bzero(buf, sizeof(buf));
1.21      markus   1063:                                process_message(&sockets[i]);
                   1064:                        }
                   1065:                        break;
                   1066:                default:
                   1067:                        fatal("Unknown type %d", sockets[i].type);
                   1068:                }
1.1       deraadt  1069: }
                   1070:
1.55      itojun   1071: static void
1.113     markus   1072: cleanup_socket(void)
1.15      markus   1073: {
1.187     djm      1074:        if (cleanup_pid != 0 && getpid() != cleanup_pid)
                   1075:                return;
                   1076:        debug("%s: cleanup", __func__);
1.48      deraadt  1077:        if (socket_name[0])
                   1078:                unlink(socket_name);
                   1079:        if (socket_dir[0])
                   1080:                rmdir(socket_dir);
1.10      markus   1081: }
                   1082:
1.114     markus   1083: void
1.15      markus   1084: cleanup_exit(int i)
                   1085: {
1.113     markus   1086:        cleanup_socket();
                   1087:        _exit(i);
1.15      markus   1088: }
                   1089:
1.135     deraadt  1090: /*ARGSUSED*/
1.55      itojun   1091: static void
1.48      deraadt  1092: cleanup_handler(int sig)
                   1093: {
1.113     markus   1094:        cleanup_socket();
1.163     markus   1095: #ifdef ENABLE_PKCS11
                   1096:        pkcs11_terminate();
                   1097: #endif
1.48      deraadt  1098:        _exit(2);
1.113     markus   1099: }
                   1100:
1.68      markus   1101: static void
1.155     dtucker  1102: check_parent_exists(void)
1.68      markus   1103: {
1.172     dtucker  1104:        /*
                   1105:         * If our parent has exited then getppid() will return (pid_t)1,
                   1106:         * so testing for that should be safe.
                   1107:         */
                   1108:        if (parent_pid != -1 && getppid() != parent_pid) {
1.68      markus   1109:                /* printf("Parent has died - Authentication agent exiting.\n"); */
1.155     dtucker  1110:                cleanup_socket();
                   1111:                _exit(2);
1.68      markus   1112:        }
1.48      deraadt  1113: }
                   1114:
1.55      itojun   1115: static void
1.50      itojun   1116: usage(void)
1.15      markus   1117: {
1.184     deraadt  1118:        fprintf(stderr,
1.193     jmc      1119:            "usage: ssh-agent [-c | -s] [-d] [-a bind_address] [-E fingerprint_hash]\n"
                   1120:            "                 [-t life] [command [arg ...]]\n"
1.184     deraadt  1121:            "       ssh-agent [-c | -s] -k\n");
1.21      markus   1122:        exit(1);
1.15      markus   1123: }
                   1124:
1.2       provos   1125: int
                   1126: main(int ac, char **av)
1.1       deraadt  1127: {
1.107     markus   1128:        int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1.154     dtucker  1129:        int sock, fd, ch, result, saved_errno;
1.120     avsm     1130:        u_int nalloc;
1.96      deraadt  1131:        char *shell, *format, *pidstr, *agentsocket = NULL;
                   1132:        fd_set *readsetp = NULL, *writesetp = NULL;
1.41      markus   1133:        struct rlimit rlim;
1.96      deraadt  1134:        extern int optind;
1.98      stevesk  1135:        extern char *optarg;
1.21      markus   1136:        pid_t pid;
1.96      deraadt  1137:        char pidstrbuf[1 + 3 * sizeof pid];
1.155     dtucker  1138:        struct timeval *tvp = NULL;
1.161     tobias   1139:        size_t len;
1.189     djm      1140:        mode_t prev_mask;
1.123     djm      1141:
                   1142:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                   1143:        sanitise_stdfd();
1.99      markus   1144:
                   1145:        /* drop */
                   1146:        setegid(getgid());
                   1147:        setgid(getgid());
1.53      markus   1148:
1.185     markus   1149: #ifdef WITH_OPENSSL
1.170     djm      1150:        OpenSSL_add_all_algorithms();
1.185     markus   1151: #endif
1.21      markus   1152:
1.192     djm      1153:        while ((ch = getopt(ac, av, "cdksE:a:t:")) != -1) {
1.21      markus   1154:                switch (ch) {
1.192     djm      1155:                case 'E':
                   1156:                        fingerprint_hash = ssh_digest_alg_by_name(optarg);
                   1157:                        if (fingerprint_hash == -1)
                   1158:                                fatal("Invalid hash algorithm \"%s\"", optarg);
                   1159:                        break;
1.21      markus   1160:                case 'c':
                   1161:                        if (s_flag)
                   1162:                                usage();
                   1163:                        c_flag++;
                   1164:                        break;
                   1165:                case 'k':
                   1166:                        k_flag++;
                   1167:                        break;
                   1168:                case 's':
                   1169:                        if (c_flag)
                   1170:                                usage();
                   1171:                        s_flag++;
                   1172:                        break;
1.57      markus   1173:                case 'd':
                   1174:                        if (d_flag)
                   1175:                                usage();
                   1176:                        d_flag++;
                   1177:                        break;
1.86      markus   1178:                case 'a':
                   1179:                        agentsocket = optarg;
1.106     marc     1180:                        break;
                   1181:                case 't':
                   1182:                        if ((lifetime = convtime(optarg)) == -1) {
                   1183:                                fprintf(stderr, "Invalid lifetime\n");
                   1184:                                usage();
                   1185:                        }
1.86      markus   1186:                        break;
1.21      markus   1187:                default:
                   1188:                        usage();
                   1189:                }
                   1190:        }
                   1191:        ac -= optind;
                   1192:        av += optind;
                   1193:
1.57      markus   1194:        if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1.21      markus   1195:                usage();
                   1196:
1.85      markus   1197:        if (ac == 0 && !c_flag && !s_flag) {
1.21      markus   1198:                shell = getenv("SHELL");
1.161     tobias   1199:                if (shell != NULL && (len = strlen(shell)) > 2 &&
                   1200:                    strncmp(shell + len - 3, "csh", 3) == 0)
1.21      markus   1201:                        c_flag = 1;
                   1202:        }
                   1203:        if (k_flag) {
1.136     deraadt  1204:                const char *errstr = NULL;
                   1205:
1.21      markus   1206:                pidstr = getenv(SSH_AGENTPID_ENV_NAME);
                   1207:                if (pidstr == NULL) {
                   1208:                        fprintf(stderr, "%s not set, cannot kill agent\n",
1.46      markus   1209:                            SSH_AGENTPID_ENV_NAME);
1.21      markus   1210:                        exit(1);
                   1211:                }
1.136     deraadt  1212:                pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
                   1213:                if (errstr) {
                   1214:                        fprintf(stderr,
                   1215:                            "%s=\"%s\", which is not a good PID: %s\n",
                   1216:                            SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1.21      markus   1217:                        exit(1);
                   1218:                }
                   1219:                if (kill(pid, SIGTERM) == -1) {
                   1220:                        perror("kill");
                   1221:                        exit(1);
                   1222:                }
                   1223:                format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1.140     djm      1224:                printf(format, SSH_AUTHSOCKET_ENV_NAME);
                   1225:                printf(format, SSH_AGENTPID_ENV_NAME);
1.91      mpech    1226:                printf("echo Agent pid %ld killed;\n", (long)pid);
1.21      markus   1227:                exit(0);
                   1228:        }
                   1229:        parent_pid = getpid();
                   1230:
1.86      markus   1231:        if (agentsocket == NULL) {
                   1232:                /* Create private directory for agent socket */
1.171     djm      1233:                mktemp_proto(socket_dir, sizeof(socket_dir));
1.86      markus   1234:                if (mkdtemp(socket_dir) == NULL) {
                   1235:                        perror("mkdtemp: private socket dir");
                   1236:                        exit(1);
                   1237:                }
1.91      mpech    1238:                snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
                   1239:                    (long)parent_pid);
1.86      markus   1240:        } else {
                   1241:                /* Try to use specified agent socket */
                   1242:                socket_dir[0] = '\0';
                   1243:                strlcpy(socket_name, agentsocket, sizeof socket_name);
1.21      markus   1244:        }
                   1245:
1.23      markus   1246:        /*
                   1247:         * Create socket early so it will exist before command gets run from
                   1248:         * the parent.
                   1249:         */
1.189     djm      1250:        prev_mask = umask(0177);
1.188     millert  1251:        sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1.21      markus   1252:        if (sock < 0) {
1.188     millert  1253:                /* XXX - unix_listener() calls error() not perror() */
1.121     djm      1254:                *socket_name = '\0'; /* Don't unlink any existing file */
1.21      markus   1255:                cleanup_exit(1);
                   1256:        }
1.189     djm      1257:        umask(prev_mask);
1.46      markus   1258:
1.23      markus   1259:        /*
                   1260:         * Fork, and have the parent execute the command, if any, or present
                   1261:         * the socket data.  The child continues as the authentication agent.
                   1262:         */
1.57      markus   1263:        if (d_flag) {
                   1264:                log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
                   1265:                format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
                   1266:                printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
                   1267:                    SSH_AUTHSOCKET_ENV_NAME);
1.91      mpech    1268:                printf("echo Agent pid %ld;\n", (long)parent_pid);
1.57      markus   1269:                goto skip;
                   1270:        }
1.21      markus   1271:        pid = fork();
                   1272:        if (pid == -1) {
                   1273:                perror("fork");
1.81      stevesk  1274:                cleanup_exit(1);
1.21      markus   1275:        }
                   1276:        if (pid != 0) {         /* Parent - execute the given command. */
                   1277:                close(sock);
1.91      mpech    1278:                snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1.21      markus   1279:                if (ac == 0) {
                   1280:                        format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
                   1281:                        printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1.46      markus   1282:                            SSH_AUTHSOCKET_ENV_NAME);
1.21      markus   1283:                        printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1.46      markus   1284:                            SSH_AGENTPID_ENV_NAME);
1.91      mpech    1285:                        printf("echo Agent pid %ld;\n", (long)pid);
1.21      markus   1286:                        exit(0);
                   1287:                }
1.36      deraadt  1288:                if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
                   1289:                    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
                   1290:                        perror("setenv");
                   1291:                        exit(1);
                   1292:                }
1.21      markus   1293:                execvp(av[0], av);
                   1294:                perror(av[0]);
                   1295:                exit(1);
                   1296:        }
1.81      stevesk  1297:        /* child */
                   1298:        log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1.67      stevesk  1299:
                   1300:        if (setsid() == -1) {
1.81      stevesk  1301:                error("setsid: %s", strerror(errno));
1.67      stevesk  1302:                cleanup_exit(1);
                   1303:        }
                   1304:
                   1305:        (void)chdir("/");
1.107     markus   1306:        if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                   1307:                /* XXX might close listen socket */
                   1308:                (void)dup2(fd, STDIN_FILENO);
                   1309:                (void)dup2(fd, STDOUT_FILENO);
                   1310:                (void)dup2(fd, STDERR_FILENO);
                   1311:                if (fd > 2)
                   1312:                        close(fd);
                   1313:        }
1.21      markus   1314:
1.41      markus   1315:        /* deny core dumps, since memory contains unencrypted private keys */
                   1316:        rlim.rlim_cur = rlim.rlim_max = 0;
                   1317:        if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1.81      stevesk  1318:                error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1.21      markus   1319:                cleanup_exit(1);
                   1320:        }
1.57      markus   1321:
                   1322: skip:
1.187     djm      1323:
                   1324:        cleanup_pid = getpid();
1.163     markus   1325:
                   1326: #ifdef ENABLE_PKCS11
                   1327:        pkcs11_init(0);
                   1328: #endif
1.21      markus   1329:        new_socket(AUTH_SOCKET, sock);
1.155     dtucker  1330:        if (ac > 0)
                   1331:                parent_alive_interval = 10;
1.33      markus   1332:        idtab_init();
1.61      markus   1333:        signal(SIGPIPE, SIG_IGN);
1.177     djm      1334:        signal(SIGINT, d_flag ? cleanup_handler : SIG_IGN);
1.48      deraadt  1335:        signal(SIGHUP, cleanup_handler);
                   1336:        signal(SIGTERM, cleanup_handler);
1.66      markus   1337:        nalloc = 0;
                   1338:
1.21      markus   1339:        while (1) {
1.155     dtucker  1340:                prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
                   1341:                result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1.154     dtucker  1342:                saved_errno = errno;
1.155     dtucker  1343:                if (parent_alive_interval != 0)
                   1344:                        check_parent_exists();
                   1345:                (void) reaper();        /* remove expired keys */
1.154     dtucker  1346:                if (result < 0) {
                   1347:                        if (saved_errno == EINTR)
1.21      markus   1348:                                continue;
1.154     dtucker  1349:                        fatal("select: %s", strerror(saved_errno));
                   1350:                } else if (result > 0)
                   1351:                        after_select(readsetp, writesetp);
1.15      markus   1352:        }
1.21      markus   1353:        /* NOTREACHED */
1.1       deraadt  1354: }