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

1.39    ! markus      1: /*     $OpenBSD: ssh-agent.c,v 1.38 2000/11/12 19:03:28 markus Exp $   */
1.15      markus      2:
1.1       deraadt     3: /*
1.22      deraadt     4:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      5:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      6:  *                    All rights reserved
                      7:  * The authentication agent program.
1.33      markus      8:  *
1.35      deraadt     9:  * As far as I am concerned, the code I have written for this software
                     10:  * can be used freely for any purpose.  Any derived versions of this
                     11:  * software must be clearly marked as such, and if the derived work is
                     12:  * incompatible with the protocol description in the RFC file, it must be
                     13:  * called by a name other than "ssh" or "Secure Shell".
                     14:  *
1.33      markus     15:  * SSH2 implementation,
                     16:  * Copyright (c) 2000 Markus Friedl. All rights reserved.
1.35      deraadt    17:  *
                     18:  * Redistribution and use in source and binary forms, with or without
                     19:  * modification, are permitted provided that the following conditions
                     20:  * are met:
                     21:  * 1. Redistributions of source code must retain the above copyright
                     22:  *    notice, this list of conditions and the following disclaimer.
                     23:  * 2. Redistributions in binary form must reproduce the above copyright
                     24:  *    notice, this list of conditions and the following disclaimer in the
                     25:  *    documentation and/or other materials provided with the distribution.
                     26:  *
                     27:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     28:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     29:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     30:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     31:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     32:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     33:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     34:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     35:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     36:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.22      deraadt    37:  */
1.1       deraadt    38:
                     39: #include "includes.h"
1.39    ! markus     40: RCSID("$OpenBSD: ssh-agent.c,v 1.38 2000/11/12 19:03:28 markus Exp $");
1.1       deraadt    41:
                     42: #include "ssh.h"
                     43: #include "rsa.h"
                     44: #include "buffer.h"
                     45: #include "bufaux.h"
                     46: #include "xmalloc.h"
                     47: #include "packet.h"
                     48: #include "getput.h"
                     49: #include "mpaux.h"
                     50:
1.33      markus     51: #include <openssl/evp.h>
1.27      markus     52: #include <openssl/md5.h>
1.32      markus     53: #include <openssl/dsa.h>
                     54: #include <openssl/rsa.h>
                     55: #include "key.h"
                     56: #include "authfd.h"
1.33      markus     57: #include "kex.h"
1.37      markus     58: #include "compat.h"
1.7       deraadt    59:
1.21      markus     60: typedef struct {
                     61:        int fd;
                     62:        enum {
                     63:                AUTH_UNUSED, AUTH_SOCKET, AUTH_CONNECTION
                     64:        } type;
                     65:        Buffer input;
                     66:        Buffer output;
1.1       deraadt    67: } SocketEntry;
                     68:
                     69: unsigned int sockets_alloc = 0;
                     70: SocketEntry *sockets = NULL;
                     71:
1.21      markus     72: typedef struct {
1.33      markus     73:        Key *key;
1.21      markus     74:        char *comment;
1.1       deraadt    75: } Identity;
                     76:
1.33      markus     77: typedef struct {
                     78:        int nentries;
                     79:        Identity *identities;
                     80: } Idtab;
                     81:
                     82: /* private key table, one per protocol version */
                     83: Idtab idtable[3];
1.1       deraadt    84:
                     85: int max_fd = 0;
                     86:
1.11      markus     87: /* pid of shell == parent of agent */
1.29      deraadt    88: pid_t parent_pid = -1;
1.10      markus     89:
                     90: /* pathname and directory for AUTH_SOCKET */
                     91: char socket_name[1024];
                     92: char socket_dir[1024];
                     93:
1.20      markus     94: extern char *__progname;
                     95:
1.2       provos     96: void
1.33      markus     97: idtab_init(void)
1.1       deraadt    98: {
1.33      markus     99:        int i;
                    100:        for (i = 0; i <=2; i++){
                    101:                idtable[i].identities = NULL;
                    102:                idtable[i].nentries = 0;
                    103:        }
                    104: }
                    105:
                    106: /* return private key table for requested protocol version */
                    107: Idtab *
                    108: idtab_lookup(int version)
                    109: {
                    110:        if (version < 1 || version > 2)
                    111:                fatal("internal error, bad protocol version %d", version);
                    112:        return &idtable[version];
                    113: }
                    114:
                    115: /* return matching private key for given public key */
                    116: Key *
                    117: lookup_private_key(Key *key, int *idx, int version)
                    118: {
                    119:        int i;
                    120:        Idtab *tab = idtab_lookup(version);
                    121:        for (i = 0; i < tab->nentries; i++) {
                    122:                if (key_equal(key, tab->identities[i].key)) {
                    123:                        if (idx != NULL)
                    124:                                *idx = i;
                    125:                        return tab->identities[i].key;
                    126:                }
                    127:        }
                    128:        return NULL;
                    129: }
                    130:
                    131: /* send list of supported public keys to 'client' */
                    132: void
                    133: process_request_identities(SocketEntry *e, int version)
                    134: {
                    135:        Idtab *tab = idtab_lookup(version);
1.21      markus    136:        Buffer msg;
                    137:        int i;
1.1       deraadt   138:
1.21      markus    139:        buffer_init(&msg);
1.33      markus    140:        buffer_put_char(&msg, (version == 1) ?
                    141:            SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
                    142:        buffer_put_int(&msg, tab->nentries);
                    143:        for (i = 0; i < tab->nentries; i++) {
                    144:                Identity *id = &tab->identities[i];
1.39    ! markus    145:                if (id->key->type == KEY_RSA1) {
1.33      markus    146:                        buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
                    147:                        buffer_put_bignum(&msg, id->key->rsa->e);
                    148:                        buffer_put_bignum(&msg, id->key->rsa->n);
                    149:                } else {
                    150:                        unsigned char *blob;
                    151:                        unsigned int blen;
1.39    ! markus    152:                        key_to_blob(id->key, &blob, &blen);
1.33      markus    153:                        buffer_put_string(&msg, blob, blen);
                    154:                        xfree(blob);
                    155:                }
                    156:                buffer_put_cstring(&msg, id->comment);
1.21      markus    157:        }
                    158:        buffer_put_int(&e->output, buffer_len(&msg));
                    159:        buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
                    160:        buffer_free(&msg);
1.1       deraadt   161: }
                    162:
1.33      markus    163: /* ssh1 only */
1.2       provos    164: void
1.33      markus    165: process_authentication_challenge1(SocketEntry *e)
1.1       deraadt   166: {
1.33      markus    167:        Key *key, *private;
                    168:        BIGNUM *challenge;
                    169:        int i, len;
1.21      markus    170:        Buffer msg;
                    171:        MD5_CTX md;
                    172:        unsigned char buf[32], mdbuf[16], session_id[16];
                    173:        unsigned int response_type;
                    174:
                    175:        buffer_init(&msg);
1.39    ! markus    176:        key = key_new(KEY_RSA1);
1.21      markus    177:        challenge = BN_new();
1.33      markus    178:
                    179:        buffer_get_int(&e->input);                              /* ignored */
                    180:        buffer_get_bignum(&e->input, key->rsa->e);
                    181:        buffer_get_bignum(&e->input, key->rsa->n);
1.21      markus    182:        buffer_get_bignum(&e->input, challenge);
                    183:
1.33      markus    184:        /* Only protocol 1.1 is supported */
                    185:        if (buffer_len(&e->input) == 0)
                    186:                goto failure;
                    187:        buffer_get(&e->input, (char *) session_id, 16);
                    188:        response_type = buffer_get_int(&e->input);
                    189:        if (response_type != 1)
                    190:                goto failure;
                    191:
                    192:        private = lookup_private_key(key, NULL, 1);
                    193:        if (private != NULL) {
                    194:                /* Decrypt the challenge using the private key. */
                    195:                rsa_private_decrypt(challenge, challenge, private->rsa);
                    196:
                    197:                /* The response is MD5 of decrypted challenge plus session id. */
                    198:                len = BN_num_bytes(challenge);
                    199:                if (len <= 0 || len > 32) {
                    200:                        log("process_authentication_challenge: bad challenge length %d", len);
                    201:                        goto failure;
                    202:                }
                    203:                memset(buf, 0, 32);
                    204:                BN_bn2bin(challenge, buf + 32 - len);
                    205:                MD5_Init(&md);
                    206:                MD5_Update(&md, buf, 32);
                    207:                MD5_Update(&md, session_id, 16);
                    208:                MD5_Final(mdbuf, &md);
                    209:
                    210:                /* Send the response. */
                    211:                buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
                    212:                for (i = 0; i < 16; i++)
                    213:                        buffer_put_char(&msg, mdbuf[i]);
                    214:                goto send;
                    215:        }
1.21      markus    216:
1.33      markus    217: failure:
                    218:        /* Unknown identity or protocol error.  Send failure. */
1.21      markus    219:        buffer_put_char(&msg, SSH_AGENT_FAILURE);
                    220: send:
                    221:        buffer_put_int(&e->output, buffer_len(&msg));
1.33      markus    222:        buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
                    223:        key_free(key);
                    224:        BN_clear_free(challenge);
                    225:        buffer_free(&msg);
                    226: }
                    227:
                    228: /* ssh2 only */
                    229: void
                    230: process_sign_request2(SocketEntry *e)
                    231: {
                    232:        extern int datafellows;
                    233:        Key *key, *private;
                    234:        unsigned char *blob, *data, *signature = NULL;
                    235:        unsigned int blen, dlen, slen = 0;
1.37      markus    236:        int flags;
1.33      markus    237:        Buffer msg;
                    238:        int ok = -1;
                    239:
                    240:        datafellows = 0;
                    241:
                    242:        blob = buffer_get_string(&e->input, &blen);
                    243:        data = buffer_get_string(&e->input, &dlen);
1.37      markus    244:
                    245:        flags = buffer_get_int(&e->input);
                    246:        if (flags & SSH_AGENT_OLD_SIGNATURE)
                    247:                datafellows = SSH_BUG_SIGBLOB;
1.33      markus    248:
1.39    ! markus    249:        key = key_from_blob(blob, blen);
1.33      markus    250:        if (key != NULL) {
                    251:                private = lookup_private_key(key, NULL, 2);
                    252:                if (private != NULL)
1.39    ! markus    253:                        ok = key_sign(private, &signature, &slen, data, dlen);
1.33      markus    254:        }
                    255:        key_free(key);
                    256:        buffer_init(&msg);
                    257:        if (ok == 0) {
                    258:                buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
                    259:                buffer_put_string(&msg, signature, slen);
                    260:        } else {
                    261:                buffer_put_char(&msg, SSH_AGENT_FAILURE);
                    262:        }
                    263:        buffer_put_int(&e->output, buffer_len(&msg));
1.21      markus    264:        buffer_append(&e->output, buffer_ptr(&msg),
1.33      markus    265:            buffer_len(&msg));
1.21      markus    266:        buffer_free(&msg);
1.33      markus    267:        xfree(data);
                    268:        xfree(blob);
                    269:        if (signature != NULL)
                    270:                xfree(signature);
1.1       deraadt   271: }
                    272:
1.33      markus    273: /* shared */
1.2       provos    274: void
1.33      markus    275: process_remove_identity(SocketEntry *e, int version)
1.1       deraadt   276: {
1.33      markus    277:        Key *key = NULL, *private;
                    278:        unsigned char *blob;
                    279:        unsigned int blen;
1.21      markus    280:        unsigned int bits;
1.33      markus    281:        int success = 0;
1.21      markus    282:
1.33      markus    283:        switch(version){
                    284:        case 1:
1.39    ! markus    285:                key = key_new(KEY_RSA1);
1.33      markus    286:                bits = buffer_get_int(&e->input);
                    287:                buffer_get_bignum(&e->input, key->rsa->e);
                    288:                buffer_get_bignum(&e->input, key->rsa->n);
                    289:
                    290:                if (bits != key_size(key))
                    291:                        log("Warning: identity keysize mismatch: actual %d, announced %d",
                    292:                              key_size(key), bits);
                    293:                break;
                    294:        case 2:
                    295:                blob = buffer_get_string(&e->input, &blen);
1.39    ! markus    296:                key = key_from_blob(blob, blen);
1.33      markus    297:                xfree(blob);
                    298:                break;
                    299:        }
                    300:        if (key != NULL) {
                    301:                int idx;
                    302:                private = lookup_private_key(key, &idx, version);
                    303:                if (private != NULL) {
1.23      markus    304:                        /*
                    305:                         * We have this key.  Free the old key.  Since we
                    306:                         * don\'t want to leave empty slots in the middle of
                    307:                         * the array, we actually free the key there and copy
                    308:                         * data from the last entry.
                    309:                         */
1.33      markus    310:                        Idtab *tab = idtab_lookup(version);
                    311:                        key_free(tab->identities[idx].key);
                    312:                        xfree(tab->identities[idx].comment);
1.38      markus    313:                        if (tab->nentries < 1)
                    314:                                fatal("process_remove_identity: "
                    315:                                    "internal error: tab->nentries %d",
                    316:                                    tab->nentries);
                    317:                        if (idx != tab->nentries - 1)
                    318:                                tab->identities[idx] = tab->identities[tab->nentries - 1];
1.33      markus    319:                        tab->nentries--;
                    320:                        success = 1;
1.21      markus    321:                }
1.33      markus    322:                key_free(key);
                    323:        }
1.1       deraadt   324:        buffer_put_int(&e->output, 1);
1.33      markus    325:        buffer_put_char(&e->output,
                    326:            success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
1.1       deraadt   327: }
                    328:
1.2       provos    329: void
1.33      markus    330: process_remove_all_identities(SocketEntry *e, int version)
1.1       deraadt   331: {
1.21      markus    332:        unsigned int i;
1.33      markus    333:        Idtab *tab = idtab_lookup(version);
1.21      markus    334:
                    335:        /* Loop over all identities and clear the keys. */
1.33      markus    336:        for (i = 0; i < tab->nentries; i++) {
                    337:                key_free(tab->identities[i].key);
                    338:                xfree(tab->identities[i].comment);
1.21      markus    339:        }
                    340:
                    341:        /* Mark that there are no identities. */
1.33      markus    342:        tab->nentries = 0;
1.21      markus    343:
                    344:        /* Send success. */
                    345:        buffer_put_int(&e->output, 1);
                    346:        buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
                    347:        return;
1.1       deraadt   348: }
                    349:
1.2       provos    350: void
1.39    ! markus    351: generate_additional_parameters(RSA *rsa)
        !           352: {
        !           353:        BIGNUM *aux;
        !           354:        BN_CTX *ctx;
        !           355:        /* Generate additional parameters */
        !           356:        aux = BN_new();
        !           357:        ctx = BN_CTX_new();
        !           358:
        !           359:        BN_sub(aux, rsa->q, BN_value_one());
        !           360:        BN_mod(rsa->dmq1, rsa->d, aux, ctx);
        !           361:
        !           362:        BN_sub(aux, rsa->p, BN_value_one());
        !           363:        BN_mod(rsa->dmp1, rsa->d, aux, ctx);
        !           364:
        !           365:        BN_clear_free(aux);
        !           366:        BN_CTX_free(ctx);
        !           367: }
        !           368:
        !           369: void
1.33      markus    370: process_add_identity(SocketEntry *e, int version)
1.1       deraadt   371: {
1.33      markus    372:        Key *k = NULL;
1.39    ! markus    373:        char *type_name;
1.33      markus    374:        char *comment;
1.39    ! markus    375:        int type, success = 0;
1.33      markus    376:        Idtab *tab = idtab_lookup(version);
                    377:
                    378:        switch (version) {
                    379:        case 1:
1.39    ! markus    380:                k = key_new_private(KEY_RSA1);
        !           381:                buffer_get_int(&e->input);                      /* ignored */
        !           382:                buffer_get_bignum(&e->input, k->rsa->n);
        !           383:                buffer_get_bignum(&e->input, k->rsa->e);
        !           384:                buffer_get_bignum(&e->input, k->rsa->d);
        !           385:                buffer_get_bignum(&e->input, k->rsa->iqmp);
1.33      markus    386:
                    387:                /* SSH and SSL have p and q swapped */
1.39    ! markus    388:                buffer_get_bignum(&e->input, k->rsa->q);        /* p */
        !           389:                buffer_get_bignum(&e->input, k->rsa->p);        /* q */
1.33      markus    390:
                    391:                /* Generate additional parameters */
1.39    ! markus    392:                generate_additional_parameters(k->rsa);
1.33      markus    393:                break;
                    394:        case 2:
1.39    ! markus    395:                type_name = buffer_get_string(&e->input, NULL);
        !           396:                 type = key_type_from_name(type_name);
        !           397:                xfree(type_name);
        !           398:                switch(type) {
        !           399:                case KEY_DSA:
        !           400:                        k = key_new_private(type);
        !           401:                        buffer_get_bignum2(&e->input, k->dsa->p);
        !           402:                        buffer_get_bignum2(&e->input, k->dsa->q);
        !           403:                        buffer_get_bignum2(&e->input, k->dsa->g);
        !           404:                        buffer_get_bignum2(&e->input, k->dsa->pub_key);
        !           405:                        buffer_get_bignum2(&e->input, k->dsa->priv_key);
        !           406:                        break;
        !           407:                case KEY_RSA:
        !           408:                        k = key_new_private(type);
        !           409:                        buffer_get_bignum2(&e->input, k->rsa->n);
        !           410:                        buffer_get_bignum2(&e->input, k->rsa->e);
        !           411:                        buffer_get_bignum2(&e->input, k->rsa->d);
        !           412:                        buffer_get_bignum2(&e->input, k->rsa->iqmp);
        !           413:                        buffer_get_bignum2(&e->input, k->rsa->p);
        !           414:                        buffer_get_bignum2(&e->input, k->rsa->q);
        !           415:
        !           416:                        /* Generate additional parameters */
        !           417:                        generate_additional_parameters(k->rsa);
        !           418:                        break;
        !           419:                default:
1.33      markus    420:                        buffer_clear(&e->input);
                    421:                        goto send;
1.21      markus    422:                }
1.33      markus    423:                break;
                    424:        }
                    425:        comment = buffer_get_string(&e->input, NULL);
                    426:        if (k == NULL) {
                    427:                xfree(comment);
                    428:                goto send;
                    429:        }
                    430:        success = 1;
                    431:        if (lookup_private_key(k, NULL, version) == NULL) {
                    432:                if (tab->nentries == 0)
                    433:                        tab->identities = xmalloc(sizeof(Identity));
                    434:                else
                    435:                        tab->identities = xrealloc(tab->identities,
                    436:                            (tab->nentries + 1) * sizeof(Identity));
                    437:                tab->identities[tab->nentries].key = k;
                    438:                tab->identities[tab->nentries].comment = comment;
                    439:                /* Increment the number of identities. */
                    440:                tab->nentries++;
                    441:        } else {
                    442:                key_free(k);
                    443:                xfree(comment);
                    444:        }
                    445: send:
1.1       deraadt   446:        buffer_put_int(&e->output, 1);
1.33      markus    447:        buffer_put_char(&e->output,
                    448:            success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
1.1       deraadt   449: }
                    450:
1.33      markus    451: /* dispatch incoming messages */
                    452:
1.2       provos    453: void
                    454: process_message(SocketEntry *e)
1.1       deraadt   455: {
1.21      markus    456:        unsigned int msg_len;
                    457:        unsigned int type;
                    458:        unsigned char *cp;
                    459:        if (buffer_len(&e->input) < 5)
                    460:                return;         /* Incomplete message. */
                    461:        cp = (unsigned char *) buffer_ptr(&e->input);
                    462:        msg_len = GET_32BIT(cp);
                    463:        if (msg_len > 256 * 1024) {
                    464:                shutdown(e->fd, SHUT_RDWR);
                    465:                close(e->fd);
                    466:                e->type = AUTH_UNUSED;
                    467:                return;
                    468:        }
                    469:        if (buffer_len(&e->input) < msg_len + 4)
                    470:                return;
                    471:        buffer_consume(&e->input, 4);
                    472:        type = buffer_get_char(&e->input);
                    473:
                    474:        switch (type) {
1.33      markus    475:        /* ssh1 */
                    476:        case SSH_AGENTC_RSA_CHALLENGE:
                    477:                process_authentication_challenge1(e);
                    478:                break;
1.21      markus    479:        case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
1.33      markus    480:                process_request_identities(e, 1);
1.21      markus    481:                break;
                    482:        case SSH_AGENTC_ADD_RSA_IDENTITY:
1.33      markus    483:                process_add_identity(e, 1);
1.21      markus    484:                break;
                    485:        case SSH_AGENTC_REMOVE_RSA_IDENTITY:
1.33      markus    486:                process_remove_identity(e, 1);
1.21      markus    487:                break;
                    488:        case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1.33      markus    489:                process_remove_all_identities(e, 1);
                    490:                break;
                    491:        /* ssh2 */
                    492:        case SSH2_AGENTC_SIGN_REQUEST:
                    493:                process_sign_request2(e);
                    494:                break;
                    495:        case SSH2_AGENTC_REQUEST_IDENTITIES:
                    496:                process_request_identities(e, 2);
                    497:                break;
                    498:        case SSH2_AGENTC_ADD_IDENTITY:
                    499:                process_add_identity(e, 2);
                    500:                break;
                    501:        case SSH2_AGENTC_REMOVE_IDENTITY:
                    502:                process_remove_identity(e, 2);
                    503:                break;
                    504:        case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
                    505:                process_remove_all_identities(e, 2);
1.21      markus    506:                break;
                    507:        default:
                    508:                /* Unknown message.  Respond with failure. */
                    509:                error("Unknown message %d", type);
                    510:                buffer_clear(&e->input);
                    511:                buffer_put_int(&e->output, 1);
                    512:                buffer_put_char(&e->output, SSH_AGENT_FAILURE);
                    513:                break;
                    514:        }
1.1       deraadt   515: }
                    516:
1.2       provos    517: void
                    518: new_socket(int type, int fd)
1.1       deraadt   519: {
1.21      markus    520:        unsigned int i, old_alloc;
                    521:        if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
                    522:                error("fcntl O_NONBLOCK: %s", strerror(errno));
                    523:
                    524:        if (fd > max_fd)
                    525:                max_fd = fd;
                    526:
                    527:        for (i = 0; i < sockets_alloc; i++)
                    528:                if (sockets[i].type == AUTH_UNUSED) {
                    529:                        sockets[i].fd = fd;
                    530:                        sockets[i].type = type;
                    531:                        buffer_init(&sockets[i].input);
                    532:                        buffer_init(&sockets[i].output);
                    533:                        return;
                    534:                }
                    535:        old_alloc = sockets_alloc;
                    536:        sockets_alloc += 10;
                    537:        if (sockets)
                    538:                sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
                    539:        else
                    540:                sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
                    541:        for (i = old_alloc; i < sockets_alloc; i++)
                    542:                sockets[i].type = AUTH_UNUSED;
                    543:        sockets[old_alloc].type = type;
                    544:        sockets[old_alloc].fd = fd;
                    545:        buffer_init(&sockets[old_alloc].input);
                    546:        buffer_init(&sockets[old_alloc].output);
1.1       deraadt   547: }
                    548:
1.2       provos    549: void
                    550: prepare_select(fd_set *readset, fd_set *writeset)
1.1       deraadt   551: {
1.21      markus    552:        unsigned int i;
                    553:        for (i = 0; i < sockets_alloc; i++)
                    554:                switch (sockets[i].type) {
                    555:                case AUTH_SOCKET:
                    556:                case AUTH_CONNECTION:
                    557:                        FD_SET(sockets[i].fd, readset);
                    558:                        if (buffer_len(&sockets[i].output) > 0)
                    559:                                FD_SET(sockets[i].fd, writeset);
                    560:                        break;
                    561:                case AUTH_UNUSED:
                    562:                        break;
                    563:                default:
                    564:                        fatal("Unknown socket type %d", sockets[i].type);
                    565:                        break;
                    566:                }
                    567: }
                    568:
1.28      markus    569: void
1.21      markus    570: after_select(fd_set *readset, fd_set *writeset)
                    571: {
                    572:        unsigned int i;
                    573:        int len, sock;
1.26      markus    574:        socklen_t slen;
1.21      markus    575:        char buf[1024];
                    576:        struct sockaddr_un sunaddr;
                    577:
                    578:        for (i = 0; i < sockets_alloc; i++)
                    579:                switch (sockets[i].type) {
                    580:                case AUTH_UNUSED:
                    581:                        break;
                    582:                case AUTH_SOCKET:
                    583:                        if (FD_ISSET(sockets[i].fd, readset)) {
1.26      markus    584:                                slen = sizeof(sunaddr);
                    585:                                sock = accept(sockets[i].fd, (struct sockaddr *) & sunaddr, &slen);
1.21      markus    586:                                if (sock < 0) {
                    587:                                        perror("accept from AUTH_SOCKET");
                    588:                                        break;
                    589:                                }
                    590:                                new_socket(AUTH_CONNECTION, sock);
                    591:                        }
                    592:                        break;
                    593:                case AUTH_CONNECTION:
                    594:                        if (buffer_len(&sockets[i].output) > 0 &&
                    595:                            FD_ISSET(sockets[i].fd, writeset)) {
                    596:                                len = write(sockets[i].fd, buffer_ptr(&sockets[i].output),
                    597:                                         buffer_len(&sockets[i].output));
                    598:                                if (len <= 0) {
                    599:                                        shutdown(sockets[i].fd, SHUT_RDWR);
                    600:                                        close(sockets[i].fd);
                    601:                                        sockets[i].type = AUTH_UNUSED;
1.30      djm       602:                                        buffer_free(&sockets[i].input);
                    603:                                        buffer_free(&sockets[i].output);
1.21      markus    604:                                        break;
                    605:                                }
                    606:                                buffer_consume(&sockets[i].output, len);
                    607:                        }
                    608:                        if (FD_ISSET(sockets[i].fd, readset)) {
                    609:                                len = read(sockets[i].fd, buf, sizeof(buf));
                    610:                                if (len <= 0) {
                    611:                                        shutdown(sockets[i].fd, SHUT_RDWR);
                    612:                                        close(sockets[i].fd);
                    613:                                        sockets[i].type = AUTH_UNUSED;
1.30      djm       614:                                        buffer_free(&sockets[i].input);
                    615:                                        buffer_free(&sockets[i].output);
1.21      markus    616:                                        break;
                    617:                                }
                    618:                                buffer_append(&sockets[i].input, buf, len);
                    619:                                process_message(&sockets[i]);
                    620:                        }
                    621:                        break;
                    622:                default:
                    623:                        fatal("Unknown type %d", sockets[i].type);
                    624:                }
1.1       deraadt   625: }
                    626:
1.6       deraadt   627: void
1.2       provos    628: check_parent_exists(int sig)
1.1       deraadt   629: {
1.29      deraadt   630:        if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
1.21      markus    631:                /* printf("Parent has died - Authentication agent exiting.\n"); */
                    632:                exit(1);
                    633:        }
                    634:        signal(SIGALRM, check_parent_exists);
                    635:        alarm(10);
1.1       deraadt   636: }
                    637:
1.15      markus    638: void
                    639: cleanup_socket(void)
                    640: {
1.21      markus    641:        remove(socket_name);
                    642:        rmdir(socket_dir);
1.10      markus    643: }
                    644:
1.15      markus    645: void
                    646: cleanup_exit(int i)
                    647: {
1.21      markus    648:        cleanup_socket();
                    649:        exit(i);
1.15      markus    650: }
                    651:
                    652: void
                    653: usage()
                    654: {
1.21      markus    655:        fprintf(stderr, "ssh-agent version %s\n", SSH_VERSION);
                    656:        fprintf(stderr, "Usage: %s [-c | -s] [-k] [command {args...]]\n",
                    657:                __progname);
                    658:        exit(1);
1.15      markus    659: }
                    660:
1.2       provos    661: int
                    662: main(int ac, char **av)
1.1       deraadt   663: {
1.21      markus    664:        fd_set readset, writeset;
                    665:        int sock, c_flag = 0, k_flag = 0, s_flag = 0, ch;
                    666:        struct sockaddr_un sunaddr;
                    667:        pid_t pid;
                    668:        char *shell, *format, *pidstr, pidstrbuf[1 + 3 * sizeof pid];
                    669:
                    670:        while ((ch = getopt(ac, av, "cks")) != -1) {
                    671:                switch (ch) {
                    672:                case 'c':
                    673:                        if (s_flag)
                    674:                                usage();
                    675:                        c_flag++;
                    676:                        break;
                    677:                case 'k':
                    678:                        k_flag++;
                    679:                        break;
                    680:                case 's':
                    681:                        if (c_flag)
                    682:                                usage();
                    683:                        s_flag++;
                    684:                        break;
                    685:                default:
                    686:                        usage();
                    687:                }
                    688:        }
                    689:        ac -= optind;
                    690:        av += optind;
                    691:
                    692:        if (ac > 0 && (c_flag || k_flag || s_flag))
                    693:                usage();
                    694:
                    695:        if (ac == 0 && !c_flag && !k_flag && !s_flag) {
                    696:                shell = getenv("SHELL");
                    697:                if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
                    698:                        c_flag = 1;
                    699:        }
                    700:        if (k_flag) {
                    701:                pidstr = getenv(SSH_AGENTPID_ENV_NAME);
                    702:                if (pidstr == NULL) {
                    703:                        fprintf(stderr, "%s not set, cannot kill agent\n",
                    704:                                SSH_AGENTPID_ENV_NAME);
                    705:                        exit(1);
                    706:                }
                    707:                pid = atoi(pidstr);
                    708:                if (pid < 1) {  /* XXX PID_MAX check too */
1.29      deraadt   709:                /* Yes, PID_MAX check please */
1.21      markus    710:                        fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
                    711:                                SSH_AGENTPID_ENV_NAME, pidstr);
                    712:                        exit(1);
                    713:                }
                    714:                if (kill(pid, SIGTERM) == -1) {
                    715:                        perror("kill");
                    716:                        exit(1);
                    717:                }
                    718:                format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
                    719:                printf(format, SSH_AUTHSOCKET_ENV_NAME);
                    720:                printf(format, SSH_AGENTPID_ENV_NAME);
                    721:                printf("echo Agent pid %d killed;\n", pid);
                    722:                exit(0);
                    723:        }
                    724:        parent_pid = getpid();
                    725:
                    726:        /* Create private directory for agent socket */
                    727:        strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
                    728:        if (mkdtemp(socket_dir) == NULL) {
                    729:                perror("mkdtemp: private socket dir");
                    730:                exit(1);
                    731:        }
                    732:        snprintf(socket_name, sizeof socket_name, "%s/agent.%d", socket_dir,
                    733:                 parent_pid);
                    734:
1.23      markus    735:        /*
                    736:         * Create socket early so it will exist before command gets run from
                    737:         * the parent.
                    738:         */
1.21      markus    739:        sock = socket(AF_UNIX, SOCK_STREAM, 0);
                    740:        if (sock < 0) {
                    741:                perror("socket");
                    742:                cleanup_exit(1);
                    743:        }
                    744:        memset(&sunaddr, 0, sizeof(sunaddr));
                    745:        sunaddr.sun_family = AF_UNIX;
                    746:        strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
                    747:        if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
                    748:                perror("bind");
                    749:                cleanup_exit(1);
                    750:        }
                    751:        if (listen(sock, 5) < 0) {
                    752:                perror("listen");
                    753:                cleanup_exit(1);
                    754:        }
1.23      markus    755:        /*
                    756:         * Fork, and have the parent execute the command, if any, or present
                    757:         * the socket data.  The child continues as the authentication agent.
                    758:         */
1.21      markus    759:        pid = fork();
                    760:        if (pid == -1) {
                    761:                perror("fork");
                    762:                exit(1);
                    763:        }
                    764:        if (pid != 0) {         /* Parent - execute the given command. */
                    765:                close(sock);
                    766:                snprintf(pidstrbuf, sizeof pidstrbuf, "%d", pid);
                    767:                if (ac == 0) {
                    768:                        format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
                    769:                        printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
                    770:                               SSH_AUTHSOCKET_ENV_NAME);
                    771:                        printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
                    772:                               SSH_AGENTPID_ENV_NAME);
                    773:                        printf("echo Agent pid %d;\n", pid);
                    774:                        exit(0);
                    775:                }
1.36      deraadt   776:                if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
                    777:                    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
                    778:                        perror("setenv");
                    779:                        exit(1);
                    780:                }
1.21      markus    781:                execvp(av[0], av);
                    782:                perror(av[0]);
                    783:                exit(1);
                    784:        }
                    785:        close(0);
                    786:        close(1);
                    787:        close(2);
                    788:
                    789:        if (setsid() == -1) {
                    790:                perror("setsid");
                    791:                cleanup_exit(1);
                    792:        }
                    793:        if (atexit(cleanup_socket) < 0) {
                    794:                perror("atexit");
                    795:                cleanup_exit(1);
                    796:        }
                    797:        new_socket(AUTH_SOCKET, sock);
                    798:        if (ac > 0) {
                    799:                signal(SIGALRM, check_parent_exists);
                    800:                alarm(10);
                    801:        }
1.33      markus    802:        idtab_init();
1.21      markus    803:        signal(SIGINT, SIG_IGN);
                    804:        signal(SIGPIPE, SIG_IGN);
1.28      markus    805:        signal(SIGHUP, cleanup_exit);
                    806:        signal(SIGTERM, cleanup_exit);
1.21      markus    807:        while (1) {
                    808:                FD_ZERO(&readset);
                    809:                FD_ZERO(&writeset);
                    810:                prepare_select(&readset, &writeset);
                    811:                if (select(max_fd + 1, &readset, &writeset, NULL, NULL) < 0) {
                    812:                        if (errno == EINTR)
                    813:                                continue;
                    814:                        exit(1);
                    815:                }
                    816:                after_select(&readset, &writeset);
1.15      markus    817:        }
1.21      markus    818:        /* NOTREACHED */
1.1       deraadt   819: }