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

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