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

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