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

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