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

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