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

1.38    ! markus      1: /*     $OpenBSD: ssh-agent.c,v 1.37 2000/09/21 11:07:51 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.38    ! markus     40: RCSID("$OpenBSD: ssh-agent.c,v 1.37 2000/09/21 11:07:51 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 "dsa.h"
                     58: #include "kex.h"
1.37      markus     59: #include "compat.h"
1.7       deraadt    60:
1.21      markus     61: typedef struct {
                     62:        int fd;
                     63:        enum {
                     64:                AUTH_UNUSED, AUTH_SOCKET, AUTH_CONNECTION
                     65:        } type;
                     66:        Buffer input;
                     67:        Buffer output;
1.1       deraadt    68: } SocketEntry;
                     69:
                     70: unsigned int sockets_alloc = 0;
                     71: SocketEntry *sockets = NULL;
                     72:
1.21      markus     73: typedef struct {
1.33      markus     74:        Key *key;
1.21      markus     75:        char *comment;
1.1       deraadt    76: } Identity;
                     77:
1.33      markus     78: typedef struct {
                     79:        int nentries;
                     80:        Identity *identities;
                     81: } Idtab;
                     82:
                     83: /* private key table, one per protocol version */
                     84: Idtab idtable[3];
1.1       deraadt    85:
                     86: int max_fd = 0;
                     87:
1.11      markus     88: /* pid of shell == parent of agent */
1.29      deraadt    89: pid_t parent_pid = -1;
1.10      markus     90:
                     91: /* pathname and directory for AUTH_SOCKET */
                     92: char socket_name[1024];
                     93: char socket_dir[1024];
                     94:
1.20      markus     95: extern char *__progname;
                     96:
1.2       provos     97: void
1.33      markus     98: idtab_init(void)
1.1       deraadt    99: {
1.33      markus    100:        int i;
                    101:        for (i = 0; i <=2; i++){
                    102:                idtable[i].identities = NULL;
                    103:                idtable[i].nentries = 0;
                    104:        }
                    105: }
                    106:
                    107: /* return private key table for requested protocol version */
                    108: Idtab *
                    109: idtab_lookup(int version)
                    110: {
                    111:        if (version < 1 || version > 2)
                    112:                fatal("internal error, bad protocol version %d", version);
                    113:        return &idtable[version];
                    114: }
                    115:
                    116: /* return matching private key for given public key */
                    117: Key *
                    118: lookup_private_key(Key *key, int *idx, int version)
                    119: {
                    120:        int i;
                    121:        Idtab *tab = idtab_lookup(version);
                    122:        for (i = 0; i < tab->nentries; i++) {
                    123:                if (key_equal(key, tab->identities[i].key)) {
                    124:                        if (idx != NULL)
                    125:                                *idx = i;
                    126:                        return tab->identities[i].key;
                    127:                }
                    128:        }
                    129:        return NULL;
                    130: }
                    131:
                    132: /* send list of supported public keys to 'client' */
                    133: void
                    134: process_request_identities(SocketEntry *e, int version)
                    135: {
                    136:        Idtab *tab = idtab_lookup(version);
1.21      markus    137:        Buffer msg;
                    138:        int i;
1.1       deraadt   139:
1.21      markus    140:        buffer_init(&msg);
1.33      markus    141:        buffer_put_char(&msg, (version == 1) ?
                    142:            SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
                    143:        buffer_put_int(&msg, tab->nentries);
                    144:        for (i = 0; i < tab->nentries; i++) {
                    145:                Identity *id = &tab->identities[i];
                    146:                if (id->key->type == KEY_RSA) {
                    147:                        buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
                    148:                        buffer_put_bignum(&msg, id->key->rsa->e);
                    149:                        buffer_put_bignum(&msg, id->key->rsa->n);
                    150:                } else {
                    151:                        unsigned char *blob;
                    152:                        unsigned int blen;
                    153:                        dsa_make_key_blob(id->key, &blob, &blen);
                    154:                        buffer_put_string(&msg, blob, blen);
                    155:                        xfree(blob);
                    156:                }
                    157:                buffer_put_cstring(&msg, id->comment);
1.21      markus    158:        }
                    159:        buffer_put_int(&e->output, buffer_len(&msg));
                    160:        buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
                    161:        buffer_free(&msg);
1.1       deraadt   162: }
                    163:
1.33      markus    164: /* ssh1 only */
1.2       provos    165: void
1.33      markus    166: process_authentication_challenge1(SocketEntry *e)
1.1       deraadt   167: {
1.33      markus    168:        Key *key, *private;
                    169:        BIGNUM *challenge;
                    170:        int i, len;
1.21      markus    171:        Buffer msg;
                    172:        MD5_CTX md;
                    173:        unsigned char buf[32], mdbuf[16], session_id[16];
                    174:        unsigned int response_type;
                    175:
                    176:        buffer_init(&msg);
1.33      markus    177:        key = key_new(KEY_RSA);
1.21      markus    178:        challenge = BN_new();
1.33      markus    179:
                    180:        buffer_get_int(&e->input);                              /* ignored */
                    181:        buffer_get_bignum(&e->input, key->rsa->e);
                    182:        buffer_get_bignum(&e->input, key->rsa->n);
1.21      markus    183:        buffer_get_bignum(&e->input, challenge);
                    184:
1.33      markus    185:        /* Only protocol 1.1 is supported */
                    186:        if (buffer_len(&e->input) == 0)
                    187:                goto failure;
                    188:        buffer_get(&e->input, (char *) session_id, 16);
                    189:        response_type = buffer_get_int(&e->input);
                    190:        if (response_type != 1)
                    191:                goto failure;
                    192:
                    193:        private = lookup_private_key(key, NULL, 1);
                    194:        if (private != NULL) {
                    195:                /* Decrypt the challenge using the private key. */
                    196:                rsa_private_decrypt(challenge, challenge, private->rsa);
                    197:
                    198:                /* The response is MD5 of decrypted challenge plus session id. */
                    199:                len = BN_num_bytes(challenge);
                    200:                if (len <= 0 || len > 32) {
                    201:                        log("process_authentication_challenge: bad challenge length %d", len);
                    202:                        goto failure;
                    203:                }
                    204:                memset(buf, 0, 32);
                    205:                BN_bn2bin(challenge, buf + 32 - len);
                    206:                MD5_Init(&md);
                    207:                MD5_Update(&md, buf, 32);
                    208:                MD5_Update(&md, session_id, 16);
                    209:                MD5_Final(mdbuf, &md);
                    210:
                    211:                /* Send the response. */
                    212:                buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
                    213:                for (i = 0; i < 16; i++)
                    214:                        buffer_put_char(&msg, mdbuf[i]);
                    215:                goto send;
                    216:        }
1.21      markus    217:
1.33      markus    218: failure:
                    219:        /* Unknown identity or protocol error.  Send failure. */
1.21      markus    220:        buffer_put_char(&msg, SSH_AGENT_FAILURE);
                    221: send:
                    222:        buffer_put_int(&e->output, buffer_len(&msg));
1.33      markus    223:        buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
                    224:        key_free(key);
                    225:        BN_clear_free(challenge);
                    226:        buffer_free(&msg);
                    227: }
                    228:
                    229: /* ssh2 only */
                    230: void
                    231: process_sign_request2(SocketEntry *e)
                    232: {
                    233:        extern int datafellows;
                    234:        Key *key, *private;
                    235:        unsigned char *blob, *data, *signature = NULL;
                    236:        unsigned int blen, dlen, slen = 0;
1.37      markus    237:        int flags;
1.33      markus    238:        Buffer msg;
                    239:        int ok = -1;
                    240:
                    241:        datafellows = 0;
                    242:
                    243:        blob = buffer_get_string(&e->input, &blen);
                    244:        data = buffer_get_string(&e->input, &dlen);
1.37      markus    245:
                    246:        flags = buffer_get_int(&e->input);
                    247:        if (flags & SSH_AGENT_OLD_SIGNATURE)
                    248:                datafellows = SSH_BUG_SIGBLOB;
1.33      markus    249:
                    250:        key = dsa_key_from_blob(blob, blen);
                    251:        if (key != NULL) {
                    252:                private = lookup_private_key(key, NULL, 2);
                    253:                if (private != NULL)
                    254:                        ok = dsa_sign(private, &signature, &slen, data, dlen);
                    255:        }
                    256:        key_free(key);
                    257:        buffer_init(&msg);
                    258:        if (ok == 0) {
                    259:                buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
                    260:                buffer_put_string(&msg, signature, slen);
                    261:        } else {
                    262:                buffer_put_char(&msg, SSH_AGENT_FAILURE);
                    263:        }
                    264:        buffer_put_int(&e->output, buffer_len(&msg));
1.21      markus    265:        buffer_append(&e->output, buffer_ptr(&msg),
1.33      markus    266:            buffer_len(&msg));
1.21      markus    267:        buffer_free(&msg);
1.33      markus    268:        xfree(data);
                    269:        xfree(blob);
                    270:        if (signature != NULL)
                    271:                xfree(signature);
1.1       deraadt   272: }
                    273:
1.33      markus    274: /* shared */
1.2       provos    275: void
1.33      markus    276: process_remove_identity(SocketEntry *e, int version)
1.1       deraadt   277: {
1.33      markus    278:        Key *key = NULL, *private;
                    279:        unsigned char *blob;
                    280:        unsigned int blen;
1.21      markus    281:        unsigned int bits;
1.33      markus    282:        int success = 0;
1.21      markus    283:
1.33      markus    284:        switch(version){
                    285:        case 1:
                    286:                key = key_new(KEY_RSA);
                    287:                bits = buffer_get_int(&e->input);
                    288:                buffer_get_bignum(&e->input, key->rsa->e);
                    289:                buffer_get_bignum(&e->input, key->rsa->n);
                    290:
                    291:                if (bits != key_size(key))
                    292:                        log("Warning: identity keysize mismatch: actual %d, announced %d",
                    293:                              key_size(key), bits);
                    294:                break;
                    295:        case 2:
                    296:                blob = buffer_get_string(&e->input, &blen);
                    297:                key = dsa_key_from_blob(blob, blen);
                    298:                xfree(blob);
                    299:                break;
                    300:        }
                    301:        if (key != NULL) {
                    302:                int idx;
                    303:                private = lookup_private_key(key, &idx, version);
                    304:                if (private != NULL) {
1.23      markus    305:                        /*
                    306:                         * We have this key.  Free the old key.  Since we
                    307:                         * don\'t want to leave empty slots in the middle of
                    308:                         * the array, we actually free the key there and copy
                    309:                         * data from the last entry.
                    310:                         */
1.33      markus    311:                        Idtab *tab = idtab_lookup(version);
                    312:                        key_free(tab->identities[idx].key);
                    313:                        xfree(tab->identities[idx].comment);
1.38    ! markus    314:                        if (tab->nentries < 1)
        !           315:                                fatal("process_remove_identity: "
        !           316:                                    "internal error: tab->nentries %d",
        !           317:                                    tab->nentries);
        !           318:                        if (idx != tab->nentries - 1)
        !           319:                                tab->identities[idx] = tab->identities[tab->nentries - 1];
1.33      markus    320:                        tab->nentries--;
                    321:                        success = 1;
1.21      markus    322:                }
1.33      markus    323:                key_free(key);
                    324:        }
1.1       deraadt   325:        buffer_put_int(&e->output, 1);
1.33      markus    326:        buffer_put_char(&e->output,
                    327:            success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
1.1       deraadt   328: }
                    329:
1.2       provos    330: void
1.33      markus    331: process_remove_all_identities(SocketEntry *e, int version)
1.1       deraadt   332: {
1.21      markus    333:        unsigned int i;
1.33      markus    334:        Idtab *tab = idtab_lookup(version);
1.21      markus    335:
                    336:        /* Loop over all identities and clear the keys. */
1.33      markus    337:        for (i = 0; i < tab->nentries; i++) {
                    338:                key_free(tab->identities[i].key);
                    339:                xfree(tab->identities[i].comment);
1.21      markus    340:        }
                    341:
                    342:        /* Mark that there are no identities. */
1.33      markus    343:        tab->nentries = 0;
1.21      markus    344:
                    345:        /* Send success. */
                    346:        buffer_put_int(&e->output, 1);
                    347:        buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
                    348:        return;
1.1       deraadt   349: }
                    350:
1.2       provos    351: void
1.33      markus    352: process_add_identity(SocketEntry *e, int version)
1.1       deraadt   353: {
1.33      markus    354:        Key *k = NULL;
                    355:        RSA *rsa;
1.21      markus    356:        BIGNUM *aux;
                    357:        BN_CTX *ctx;
1.33      markus    358:        char *type;
                    359:        char *comment;
                    360:        int success = 0;
                    361:        Idtab *tab = idtab_lookup(version);
                    362:
                    363:        switch (version) {
                    364:        case 1:
                    365:                k = key_new(KEY_RSA);
                    366:                rsa = k->rsa;
                    367:
                    368:                /* allocate mem for private key */
                    369:                /* XXX rsa->n and rsa->e are already allocated */
                    370:                rsa->d = BN_new();
                    371:                rsa->iqmp = BN_new();
                    372:                rsa->q = BN_new();
                    373:                rsa->p = BN_new();
                    374:                rsa->dmq1 = BN_new();
                    375:                rsa->dmp1 = BN_new();
                    376:
                    377:                buffer_get_int(&e->input);               /* ignored */
                    378:
                    379:                buffer_get_bignum(&e->input, rsa->n);
                    380:                buffer_get_bignum(&e->input, rsa->e);
                    381:                buffer_get_bignum(&e->input, rsa->d);
                    382:                buffer_get_bignum(&e->input, rsa->iqmp);
                    383:
                    384:                /* SSH and SSL have p and q swapped */
                    385:                buffer_get_bignum(&e->input, rsa->q);   /* p */
                    386:                buffer_get_bignum(&e->input, rsa->p);   /* q */
                    387:
                    388:                /* Generate additional parameters */
                    389:                aux = BN_new();
                    390:                ctx = BN_CTX_new();
1.21      markus    391:
1.33      markus    392:                BN_sub(aux, rsa->q, BN_value_one());
                    393:                BN_mod(rsa->dmq1, rsa->d, aux, ctx);
                    394:
                    395:                BN_sub(aux, rsa->p, BN_value_one());
                    396:                BN_mod(rsa->dmp1, rsa->d, aux, ctx);
1.21      markus    397:
1.33      markus    398:                BN_clear_free(aux);
                    399:                BN_CTX_free(ctx);
1.21      markus    400:
1.33      markus    401:                break;
                    402:        case 2:
                    403:                type = buffer_get_string(&e->input, NULL);
                    404:                if (strcmp(type, KEX_DSS)) {
                    405:                        buffer_clear(&e->input);
                    406:                        xfree(type);
                    407:                        goto send;
1.21      markus    408:                }
1.33      markus    409:                xfree(type);
1.1       deraadt   410:
1.33      markus    411:                k = key_new(KEY_DSA);
                    412:
                    413:                /* allocate mem for private key */
                    414:                k->dsa->priv_key = BN_new();
                    415:
                    416:                buffer_get_bignum2(&e->input, k->dsa->p);
                    417:                buffer_get_bignum2(&e->input, k->dsa->q);
                    418:                buffer_get_bignum2(&e->input, k->dsa->g);
                    419:                buffer_get_bignum2(&e->input, k->dsa->pub_key);
                    420:                buffer_get_bignum2(&e->input, k->dsa->priv_key);
                    421:
                    422:                break;
                    423:        }
                    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:        /* check if RSA support exists */
                    671:        if (rsa_alive() == 0) {
                    672:                fprintf(stderr,
                    673:                        "%s: no RSA support in libssl and libcrypto.  See ssl(8).\n",
                    674:                        __progname);
                    675:                exit(1);
                    676:        }
                    677:        while ((ch = getopt(ac, av, "cks")) != -1) {
                    678:                switch (ch) {
                    679:                case 'c':
                    680:                        if (s_flag)
                    681:                                usage();
                    682:                        c_flag++;
                    683:                        break;
                    684:                case 'k':
                    685:                        k_flag++;
                    686:                        break;
                    687:                case 's':
                    688:                        if (c_flag)
                    689:                                usage();
                    690:                        s_flag++;
                    691:                        break;
                    692:                default:
                    693:                        usage();
                    694:                }
                    695:        }
                    696:        ac -= optind;
                    697:        av += optind;
                    698:
                    699:        if (ac > 0 && (c_flag || k_flag || s_flag))
                    700:                usage();
                    701:
                    702:        if (ac == 0 && !c_flag && !k_flag && !s_flag) {
                    703:                shell = getenv("SHELL");
                    704:                if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
                    705:                        c_flag = 1;
                    706:        }
                    707:        if (k_flag) {
                    708:                pidstr = getenv(SSH_AGENTPID_ENV_NAME);
                    709:                if (pidstr == NULL) {
                    710:                        fprintf(stderr, "%s not set, cannot kill agent\n",
                    711:                                SSH_AGENTPID_ENV_NAME);
                    712:                        exit(1);
                    713:                }
                    714:                pid = atoi(pidstr);
                    715:                if (pid < 1) {  /* XXX PID_MAX check too */
1.29      deraadt   716:                /* Yes, PID_MAX check please */
1.21      markus    717:                        fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
                    718:                                SSH_AGENTPID_ENV_NAME, pidstr);
                    719:                        exit(1);
                    720:                }
                    721:                if (kill(pid, SIGTERM) == -1) {
                    722:                        perror("kill");
                    723:                        exit(1);
                    724:                }
                    725:                format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
                    726:                printf(format, SSH_AUTHSOCKET_ENV_NAME);
                    727:                printf(format, SSH_AGENTPID_ENV_NAME);
                    728:                printf("echo Agent pid %d killed;\n", pid);
                    729:                exit(0);
                    730:        }
                    731:        parent_pid = getpid();
                    732:
                    733:        /* Create private directory for agent socket */
                    734:        strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
                    735:        if (mkdtemp(socket_dir) == NULL) {
                    736:                perror("mkdtemp: private socket dir");
                    737:                exit(1);
                    738:        }
                    739:        snprintf(socket_name, sizeof socket_name, "%s/agent.%d", socket_dir,
                    740:                 parent_pid);
                    741:
1.23      markus    742:        /*
                    743:         * Create socket early so it will exist before command gets run from
                    744:         * the parent.
                    745:         */
1.21      markus    746:        sock = socket(AF_UNIX, SOCK_STREAM, 0);
                    747:        if (sock < 0) {
                    748:                perror("socket");
                    749:                cleanup_exit(1);
                    750:        }
                    751:        memset(&sunaddr, 0, sizeof(sunaddr));
                    752:        sunaddr.sun_family = AF_UNIX;
                    753:        strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
                    754:        if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
                    755:                perror("bind");
                    756:                cleanup_exit(1);
                    757:        }
                    758:        if (listen(sock, 5) < 0) {
                    759:                perror("listen");
                    760:                cleanup_exit(1);
                    761:        }
1.23      markus    762:        /*
                    763:         * Fork, and have the parent execute the command, if any, or present
                    764:         * the socket data.  The child continues as the authentication agent.
                    765:         */
1.21      markus    766:        pid = fork();
                    767:        if (pid == -1) {
                    768:                perror("fork");
                    769:                exit(1);
                    770:        }
                    771:        if (pid != 0) {         /* Parent - execute the given command. */
                    772:                close(sock);
                    773:                snprintf(pidstrbuf, sizeof pidstrbuf, "%d", pid);
                    774:                if (ac == 0) {
                    775:                        format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
                    776:                        printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
                    777:                               SSH_AUTHSOCKET_ENV_NAME);
                    778:                        printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
                    779:                               SSH_AGENTPID_ENV_NAME);
                    780:                        printf("echo Agent pid %d;\n", pid);
                    781:                        exit(0);
                    782:                }
1.36      deraadt   783:                if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
                    784:                    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
                    785:                        perror("setenv");
                    786:                        exit(1);
                    787:                }
1.21      markus    788:                execvp(av[0], av);
                    789:                perror(av[0]);
                    790:                exit(1);
                    791:        }
                    792:        close(0);
                    793:        close(1);
                    794:        close(2);
                    795:
                    796:        if (setsid() == -1) {
                    797:                perror("setsid");
                    798:                cleanup_exit(1);
                    799:        }
                    800:        if (atexit(cleanup_socket) < 0) {
                    801:                perror("atexit");
                    802:                cleanup_exit(1);
                    803:        }
                    804:        new_socket(AUTH_SOCKET, sock);
                    805:        if (ac > 0) {
                    806:                signal(SIGALRM, check_parent_exists);
                    807:                alarm(10);
                    808:        }
1.33      markus    809:        idtab_init();
1.21      markus    810:        signal(SIGINT, SIG_IGN);
                    811:        signal(SIGPIPE, SIG_IGN);
1.28      markus    812:        signal(SIGHUP, cleanup_exit);
                    813:        signal(SIGTERM, cleanup_exit);
1.21      markus    814:        while (1) {
                    815:                FD_ZERO(&readset);
                    816:                FD_ZERO(&writeset);
                    817:                prepare_select(&readset, &writeset);
                    818:                if (select(max_fd + 1, &readset, &writeset, NULL, NULL) < 0) {
                    819:                        if (errno == EINTR)
                    820:                                continue;
                    821:                        exit(1);
                    822:                }
                    823:                after_select(&readset, &writeset);
1.15      markus    824:        }
1.21      markus    825:        /* NOTREACHED */
1.1       deraadt   826: }