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

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