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

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