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

1.46    ! markus      1: /*     $OpenBSD: ssh-agent.c,v 1.45 2000/12/19 23:17:58 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.46    ! markus     40: RCSID("$OpenBSD: ssh-agent.c,v 1.45 2000/12/19 23:17:58 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"
1.46    ! markus     50: #include "includes.h"
1.1       deraadt    51:
1.33      markus     52: #include <openssl/evp.h>
1.27      markus     53: #include <openssl/md5.h>
1.32      markus     54: #include <openssl/dsa.h>
                     55: #include <openssl/rsa.h>
                     56: #include "key.h"
                     57: #include "authfd.h"
1.33      markus     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:
1.45      markus     70: u_int sockets_alloc = 0;
1.1       deraadt    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.46    ! markus     97: int    prepare_select(fd_set **, fd_set **, int *);
        !            98:
1.2       provos     99: void
1.33      markus    100: idtab_init(void)
1.1       deraadt   101: {
1.33      markus    102:        int i;
                    103:        for (i = 0; i <=2; i++){
                    104:                idtable[i].identities = NULL;
                    105:                idtable[i].nentries = 0;
                    106:        }
                    107: }
                    108:
                    109: /* return private key table for requested protocol version */
                    110: Idtab *
                    111: idtab_lookup(int version)
                    112: {
                    113:        if (version < 1 || version > 2)
                    114:                fatal("internal error, bad protocol version %d", version);
                    115:        return &idtable[version];
                    116: }
                    117:
                    118: /* return matching private key for given public key */
                    119: Key *
                    120: lookup_private_key(Key *key, int *idx, int version)
                    121: {
                    122:        int i;
                    123:        Idtab *tab = idtab_lookup(version);
                    124:        for (i = 0; i < tab->nentries; i++) {
                    125:                if (key_equal(key, tab->identities[i].key)) {
                    126:                        if (idx != NULL)
                    127:                                *idx = i;
                    128:                        return tab->identities[i].key;
                    129:                }
                    130:        }
                    131:        return NULL;
                    132: }
                    133:
                    134: /* send list of supported public keys to 'client' */
                    135: void
                    136: process_request_identities(SocketEntry *e, int version)
                    137: {
                    138:        Idtab *tab = idtab_lookup(version);
1.21      markus    139:        Buffer msg;
                    140:        int i;
1.1       deraadt   141:
1.21      markus    142:        buffer_init(&msg);
1.33      markus    143:        buffer_put_char(&msg, (version == 1) ?
                    144:            SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
                    145:        buffer_put_int(&msg, tab->nentries);
                    146:        for (i = 0; i < tab->nentries; i++) {
                    147:                Identity *id = &tab->identities[i];
1.39      markus    148:                if (id->key->type == KEY_RSA1) {
1.33      markus    149:                        buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
                    150:                        buffer_put_bignum(&msg, id->key->rsa->e);
                    151:                        buffer_put_bignum(&msg, id->key->rsa->n);
                    152:                } else {
1.45      markus    153:                        u_char *blob;
                    154:                        u_int blen;
1.39      markus    155:                        key_to_blob(id->key, &blob, &blen);
1.33      markus    156:                        buffer_put_string(&msg, blob, blen);
                    157:                        xfree(blob);
                    158:                }
                    159:                buffer_put_cstring(&msg, id->comment);
1.21      markus    160:        }
                    161:        buffer_put_int(&e->output, buffer_len(&msg));
                    162:        buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
                    163:        buffer_free(&msg);
1.1       deraadt   164: }
                    165:
1.33      markus    166: /* ssh1 only */
1.2       provos    167: void
1.33      markus    168: process_authentication_challenge1(SocketEntry *e)
1.1       deraadt   169: {
1.33      markus    170:        Key *key, *private;
                    171:        BIGNUM *challenge;
                    172:        int i, len;
1.21      markus    173:        Buffer msg;
                    174:        MD5_CTX md;
1.45      markus    175:        u_char buf[32], mdbuf[16], session_id[16];
                    176:        u_int response_type;
1.21      markus    177:
                    178:        buffer_init(&msg);
1.39      markus    179:        key = key_new(KEY_RSA1);
1.21      markus    180:        challenge = BN_new();
1.33      markus    181:
                    182:        buffer_get_int(&e->input);                              /* ignored */
                    183:        buffer_get_bignum(&e->input, key->rsa->e);
                    184:        buffer_get_bignum(&e->input, key->rsa->n);
1.21      markus    185:        buffer_get_bignum(&e->input, challenge);
                    186:
1.33      markus    187:        /* Only protocol 1.1 is supported */
                    188:        if (buffer_len(&e->input) == 0)
                    189:                goto failure;
                    190:        buffer_get(&e->input, (char *) session_id, 16);
                    191:        response_type = buffer_get_int(&e->input);
                    192:        if (response_type != 1)
                    193:                goto failure;
                    194:
                    195:        private = lookup_private_key(key, NULL, 1);
                    196:        if (private != NULL) {
                    197:                /* Decrypt the challenge using the private key. */
                    198:                rsa_private_decrypt(challenge, challenge, private->rsa);
                    199:
                    200:                /* The response is MD5 of decrypted challenge plus session id. */
                    201:                len = BN_num_bytes(challenge);
                    202:                if (len <= 0 || len > 32) {
                    203:                        log("process_authentication_challenge: bad challenge length %d", len);
                    204:                        goto failure;
                    205:                }
                    206:                memset(buf, 0, 32);
                    207:                BN_bn2bin(challenge, buf + 32 - len);
                    208:                MD5_Init(&md);
                    209:                MD5_Update(&md, buf, 32);
                    210:                MD5_Update(&md, session_id, 16);
                    211:                MD5_Final(mdbuf, &md);
                    212:
                    213:                /* Send the response. */
                    214:                buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
                    215:                for (i = 0; i < 16; i++)
                    216:                        buffer_put_char(&msg, mdbuf[i]);
                    217:                goto send;
                    218:        }
1.21      markus    219:
1.33      markus    220: failure:
                    221:        /* Unknown identity or protocol error.  Send failure. */
1.21      markus    222:        buffer_put_char(&msg, SSH_AGENT_FAILURE);
                    223: send:
                    224:        buffer_put_int(&e->output, buffer_len(&msg));
1.33      markus    225:        buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
                    226:        key_free(key);
                    227:        BN_clear_free(challenge);
                    228:        buffer_free(&msg);
                    229: }
                    230:
                    231: /* ssh2 only */
                    232: void
                    233: process_sign_request2(SocketEntry *e)
                    234: {
                    235:        extern int datafellows;
                    236:        Key *key, *private;
1.45      markus    237:        u_char *blob, *data, *signature = NULL;
                    238:        u_int blen, dlen, slen = 0;
1.37      markus    239:        int flags;
1.33      markus    240:        Buffer msg;
                    241:        int ok = -1;
                    242:
                    243:        datafellows = 0;
1.43      markus    244:
1.33      markus    245:        blob = buffer_get_string(&e->input, &blen);
                    246:        data = buffer_get_string(&e->input, &dlen);
1.37      markus    247:
                    248:        flags = buffer_get_int(&e->input);
                    249:        if (flags & SSH_AGENT_OLD_SIGNATURE)
                    250:                datafellows = SSH_BUG_SIGBLOB;
1.33      markus    251:
1.39      markus    252:        key = key_from_blob(blob, blen);
1.33      markus    253:        if (key != NULL) {
                    254:                private = lookup_private_key(key, NULL, 2);
                    255:                if (private != NULL)
1.39      markus    256:                        ok = key_sign(private, &signature, &slen, data, dlen);
1.33      markus    257:        }
                    258:        key_free(key);
                    259:        buffer_init(&msg);
                    260:        if (ok == 0) {
                    261:                buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
                    262:                buffer_put_string(&msg, signature, slen);
                    263:        } else {
                    264:                buffer_put_char(&msg, SSH_AGENT_FAILURE);
                    265:        }
                    266:        buffer_put_int(&e->output, buffer_len(&msg));
1.21      markus    267:        buffer_append(&e->output, buffer_ptr(&msg),
1.33      markus    268:            buffer_len(&msg));
1.21      markus    269:        buffer_free(&msg);
1.33      markus    270:        xfree(data);
                    271:        xfree(blob);
                    272:        if (signature != NULL)
                    273:                xfree(signature);
1.1       deraadt   274: }
                    275:
1.33      markus    276: /* shared */
1.2       provos    277: void
1.33      markus    278: process_remove_identity(SocketEntry *e, int version)
1.1       deraadt   279: {
1.33      markus    280:        Key *key = NULL, *private;
1.45      markus    281:        u_char *blob;
                    282:        u_int blen;
                    283:        u_int bits;
1.33      markus    284:        int success = 0;
1.21      markus    285:
1.33      markus    286:        switch(version){
                    287:        case 1:
1.39      markus    288:                key = key_new(KEY_RSA1);
1.33      markus    289:                bits = buffer_get_int(&e->input);
                    290:                buffer_get_bignum(&e->input, key->rsa->e);
                    291:                buffer_get_bignum(&e->input, key->rsa->n);
                    292:
                    293:                if (bits != key_size(key))
                    294:                        log("Warning: identity keysize mismatch: actual %d, announced %d",
1.46    ! markus    295:                            key_size(key), bits);
1.33      markus    296:                break;
                    297:        case 2:
                    298:                blob = buffer_get_string(&e->input, &blen);
1.39      markus    299:                key = key_from_blob(blob, blen);
1.33      markus    300:                xfree(blob);
                    301:                break;
                    302:        }
                    303:        if (key != NULL) {
                    304:                int idx;
                    305:                private = lookup_private_key(key, &idx, version);
                    306:                if (private != NULL) {
1.23      markus    307:                        /*
                    308:                         * We have this key.  Free the old key.  Since we
                    309:                         * don\'t want to leave empty slots in the middle of
1.40      markus    310:                         * the array, we actually free the key there and move
                    311:                         * all the entries between the empty slot and the end
                    312:                         * of the array.
1.23      markus    313:                         */
1.33      markus    314:                        Idtab *tab = idtab_lookup(version);
                    315:                        key_free(tab->identities[idx].key);
                    316:                        xfree(tab->identities[idx].comment);
1.38      markus    317:                        if (tab->nentries < 1)
                    318:                                fatal("process_remove_identity: "
                    319:                                    "internal error: tab->nentries %d",
                    320:                                    tab->nentries);
1.40      markus    321:                        if (idx != tab->nentries - 1) {
                    322:                                int i;
                    323:                                for (i = idx; i < tab->nentries - 1; i++)
                    324:                                        tab->identities[i] = tab->identities[i+1];
                    325:                        }
                    326:                        tab->identities[tab->nentries - 1].key = NULL;
                    327:                        tab->identities[tab->nentries - 1].comment = NULL;
1.33      markus    328:                        tab->nentries--;
                    329:                        success = 1;
1.21      markus    330:                }
1.33      markus    331:                key_free(key);
                    332:        }
1.1       deraadt   333:        buffer_put_int(&e->output, 1);
1.33      markus    334:        buffer_put_char(&e->output,
                    335:            success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
1.1       deraadt   336: }
                    337:
1.2       provos    338: void
1.33      markus    339: process_remove_all_identities(SocketEntry *e, int version)
1.1       deraadt   340: {
1.45      markus    341:        u_int i;
1.33      markus    342:        Idtab *tab = idtab_lookup(version);
1.21      markus    343:
                    344:        /* Loop over all identities and clear the keys. */
1.33      markus    345:        for (i = 0; i < tab->nentries; i++) {
                    346:                key_free(tab->identities[i].key);
                    347:                xfree(tab->identities[i].comment);
1.21      markus    348:        }
                    349:
                    350:        /* Mark that there are no identities. */
1.33      markus    351:        tab->nentries = 0;
1.21      markus    352:
                    353:        /* Send success. */
                    354:        buffer_put_int(&e->output, 1);
                    355:        buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
                    356:        return;
1.1       deraadt   357: }
                    358:
1.2       provos    359: void
1.39      markus    360: generate_additional_parameters(RSA *rsa)
                    361: {
                    362:        BIGNUM *aux;
                    363:        BN_CTX *ctx;
                    364:        /* Generate additional parameters */
                    365:        aux = BN_new();
                    366:        ctx = BN_CTX_new();
                    367:
                    368:        BN_sub(aux, rsa->q, BN_value_one());
                    369:        BN_mod(rsa->dmq1, rsa->d, aux, ctx);
                    370:
                    371:        BN_sub(aux, rsa->p, BN_value_one());
                    372:        BN_mod(rsa->dmp1, rsa->d, aux, ctx);
                    373:
                    374:        BN_clear_free(aux);
                    375:        BN_CTX_free(ctx);
                    376: }
                    377:
                    378: void
1.33      markus    379: process_add_identity(SocketEntry *e, int version)
1.1       deraadt   380: {
1.33      markus    381:        Key *k = NULL;
1.39      markus    382:        char *type_name;
1.33      markus    383:        char *comment;
1.39      markus    384:        int type, success = 0;
1.33      markus    385:        Idtab *tab = idtab_lookup(version);
                    386:
                    387:        switch (version) {
                    388:        case 1:
1.39      markus    389:                k = key_new_private(KEY_RSA1);
1.46    ! markus    390:                buffer_get_int(&e->input);                      /* ignored */
1.39      markus    391:                buffer_get_bignum(&e->input, k->rsa->n);
                    392:                buffer_get_bignum(&e->input, k->rsa->e);
                    393:                buffer_get_bignum(&e->input, k->rsa->d);
                    394:                buffer_get_bignum(&e->input, k->rsa->iqmp);
1.33      markus    395:
                    396:                /* SSH and SSL have p and q swapped */
1.39      markus    397:                buffer_get_bignum(&e->input, k->rsa->q);        /* p */
                    398:                buffer_get_bignum(&e->input, k->rsa->p);        /* q */
1.33      markus    399:
                    400:                /* Generate additional parameters */
1.39      markus    401:                generate_additional_parameters(k->rsa);
1.33      markus    402:                break;
                    403:        case 2:
1.39      markus    404:                type_name = buffer_get_string(&e->input, NULL);
1.46    ! markus    405:                type = key_type_from_name(type_name);
1.39      markus    406:                xfree(type_name);
                    407:                switch(type) {
                    408:                case KEY_DSA:
                    409:                        k = key_new_private(type);
                    410:                        buffer_get_bignum2(&e->input, k->dsa->p);
                    411:                        buffer_get_bignum2(&e->input, k->dsa->q);
                    412:                        buffer_get_bignum2(&e->input, k->dsa->g);
                    413:                        buffer_get_bignum2(&e->input, k->dsa->pub_key);
                    414:                        buffer_get_bignum2(&e->input, k->dsa->priv_key);
                    415:                        break;
                    416:                case KEY_RSA:
                    417:                        k = key_new_private(type);
                    418:                        buffer_get_bignum2(&e->input, k->rsa->n);
                    419:                        buffer_get_bignum2(&e->input, k->rsa->e);
                    420:                        buffer_get_bignum2(&e->input, k->rsa->d);
                    421:                        buffer_get_bignum2(&e->input, k->rsa->iqmp);
                    422:                        buffer_get_bignum2(&e->input, k->rsa->p);
                    423:                        buffer_get_bignum2(&e->input, k->rsa->q);
                    424:
                    425:                        /* Generate additional parameters */
                    426:                        generate_additional_parameters(k->rsa);
                    427:                        break;
                    428:                default:
1.33      markus    429:                        buffer_clear(&e->input);
                    430:                        goto send;
1.21      markus    431:                }
1.33      markus    432:                break;
                    433:        }
                    434:        comment = buffer_get_string(&e->input, NULL);
                    435:        if (k == NULL) {
                    436:                xfree(comment);
                    437:                goto send;
                    438:        }
                    439:        success = 1;
                    440:        if (lookup_private_key(k, NULL, version) == NULL) {
                    441:                if (tab->nentries == 0)
                    442:                        tab->identities = xmalloc(sizeof(Identity));
                    443:                else
                    444:                        tab->identities = xrealloc(tab->identities,
                    445:                            (tab->nentries + 1) * sizeof(Identity));
                    446:                tab->identities[tab->nentries].key = k;
                    447:                tab->identities[tab->nentries].comment = comment;
                    448:                /* Increment the number of identities. */
                    449:                tab->nentries++;
                    450:        } else {
                    451:                key_free(k);
                    452:                xfree(comment);
                    453:        }
                    454: send:
1.1       deraadt   455:        buffer_put_int(&e->output, 1);
1.33      markus    456:        buffer_put_char(&e->output,
                    457:            success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
1.1       deraadt   458: }
                    459:
1.33      markus    460: /* dispatch incoming messages */
                    461:
1.2       provos    462: void
                    463: process_message(SocketEntry *e)
1.1       deraadt   464: {
1.45      markus    465:        u_int msg_len;
                    466:        u_int type;
                    467:        u_char *cp;
1.21      markus    468:        if (buffer_len(&e->input) < 5)
                    469:                return;         /* Incomplete message. */
1.45      markus    470:        cp = (u_char *) buffer_ptr(&e->input);
1.21      markus    471:        msg_len = GET_32BIT(cp);
                    472:        if (msg_len > 256 * 1024) {
                    473:                shutdown(e->fd, SHUT_RDWR);
                    474:                close(e->fd);
                    475:                e->type = AUTH_UNUSED;
                    476:                return;
                    477:        }
                    478:        if (buffer_len(&e->input) < msg_len + 4)
                    479:                return;
                    480:        buffer_consume(&e->input, 4);
                    481:        type = buffer_get_char(&e->input);
                    482:
                    483:        switch (type) {
1.33      markus    484:        /* ssh1 */
                    485:        case SSH_AGENTC_RSA_CHALLENGE:
                    486:                process_authentication_challenge1(e);
                    487:                break;
1.21      markus    488:        case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
1.33      markus    489:                process_request_identities(e, 1);
1.21      markus    490:                break;
                    491:        case SSH_AGENTC_ADD_RSA_IDENTITY:
1.33      markus    492:                process_add_identity(e, 1);
1.21      markus    493:                break;
                    494:        case SSH_AGENTC_REMOVE_RSA_IDENTITY:
1.33      markus    495:                process_remove_identity(e, 1);
1.21      markus    496:                break;
                    497:        case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1.33      markus    498:                process_remove_all_identities(e, 1);
                    499:                break;
                    500:        /* ssh2 */
                    501:        case SSH2_AGENTC_SIGN_REQUEST:
                    502:                process_sign_request2(e);
                    503:                break;
                    504:        case SSH2_AGENTC_REQUEST_IDENTITIES:
                    505:                process_request_identities(e, 2);
                    506:                break;
                    507:        case SSH2_AGENTC_ADD_IDENTITY:
                    508:                process_add_identity(e, 2);
                    509:                break;
                    510:        case SSH2_AGENTC_REMOVE_IDENTITY:
                    511:                process_remove_identity(e, 2);
                    512:                break;
                    513:        case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
                    514:                process_remove_all_identities(e, 2);
1.21      markus    515:                break;
                    516:        default:
                    517:                /* Unknown message.  Respond with failure. */
                    518:                error("Unknown message %d", type);
                    519:                buffer_clear(&e->input);
                    520:                buffer_put_int(&e->output, 1);
                    521:                buffer_put_char(&e->output, SSH_AGENT_FAILURE);
                    522:                break;
                    523:        }
1.1       deraadt   524: }
                    525:
1.2       provos    526: void
                    527: new_socket(int type, int fd)
1.1       deraadt   528: {
1.45      markus    529:        u_int i, old_alloc;
1.21      markus    530:        if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
                    531:                error("fcntl O_NONBLOCK: %s", strerror(errno));
                    532:
                    533:        if (fd > max_fd)
                    534:                max_fd = fd;
                    535:
                    536:        for (i = 0; i < sockets_alloc; i++)
                    537:                if (sockets[i].type == AUTH_UNUSED) {
                    538:                        sockets[i].fd = fd;
                    539:                        sockets[i].type = type;
                    540:                        buffer_init(&sockets[i].input);
                    541:                        buffer_init(&sockets[i].output);
                    542:                        return;
                    543:                }
                    544:        old_alloc = sockets_alloc;
                    545:        sockets_alloc += 10;
                    546:        if (sockets)
                    547:                sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
                    548:        else
                    549:                sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
                    550:        for (i = old_alloc; i < sockets_alloc; i++)
                    551:                sockets[i].type = AUTH_UNUSED;
                    552:        sockets[old_alloc].type = type;
                    553:        sockets[old_alloc].fd = fd;
                    554:        buffer_init(&sockets[old_alloc].input);
                    555:        buffer_init(&sockets[old_alloc].output);
1.1       deraadt   556: }
                    557:
1.46    ! markus    558: int
        !           559: prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl)
1.1       deraadt   560: {
1.46    ! markus    561:        u_int i, sz;
        !           562:        int n = 0;
        !           563:
        !           564:        for (i = 0; i < sockets_alloc; i++) {
1.21      markus    565:                switch (sockets[i].type) {
                    566:                case AUTH_SOCKET:
                    567:                case AUTH_CONNECTION:
1.46    ! markus    568:                        n = MAX(n, sockets[i].fd);
1.21      markus    569:                        break;
                    570:                case AUTH_UNUSED:
                    571:                        break;
                    572:                default:
                    573:                        fatal("Unknown socket type %d", sockets[i].type);
                    574:                        break;
                    575:                }
1.46    ! markus    576:        }
        !           577:
        !           578:        sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
        !           579:        if (*fdrp == NULL || n > *fdl) {
        !           580:                if (*fdrp)
        !           581:                        free(*fdrp);
        !           582:                if (*fdwp)
        !           583:                        free(*fdwp);
        !           584:                *fdrp = xmalloc(sz);
        !           585:                *fdwp = xmalloc(sz);
        !           586:                *fdl = n;
        !           587:        }
        !           588:        memset(*fdrp, 0, sz);
        !           589:        memset(*fdwp, 0, sz);
        !           590:
        !           591:        for (i = 0; i < sockets_alloc; i++) {
        !           592:                switch (sockets[i].type) {
        !           593:                case AUTH_SOCKET:
        !           594:                case AUTH_CONNECTION:
        !           595:                        FD_SET(sockets[i].fd, *fdrp);
        !           596:                        if (buffer_len(&sockets[i].output) > 0)
        !           597:                                FD_SET(sockets[i].fd, *fdwp);
        !           598:                        break;
        !           599:                default:
        !           600:                        break;
        !           601:                }
        !           602:        }
        !           603:        return (1);
1.21      markus    604: }
                    605:
1.28      markus    606: void
1.21      markus    607: after_select(fd_set *readset, fd_set *writeset)
                    608: {
1.45      markus    609:        u_int i;
1.21      markus    610:        int len, sock;
1.26      markus    611:        socklen_t slen;
1.21      markus    612:        char buf[1024];
                    613:        struct sockaddr_un sunaddr;
                    614:
                    615:        for (i = 0; i < sockets_alloc; i++)
                    616:                switch (sockets[i].type) {
                    617:                case AUTH_UNUSED:
                    618:                        break;
                    619:                case AUTH_SOCKET:
                    620:                        if (FD_ISSET(sockets[i].fd, readset)) {
1.26      markus    621:                                slen = sizeof(sunaddr);
1.46    ! markus    622:                                sock = accept(sockets[i].fd,
        !           623:                                    (struct sockaddr *) &sunaddr, &slen);
1.21      markus    624:                                if (sock < 0) {
                    625:                                        perror("accept from AUTH_SOCKET");
                    626:                                        break;
                    627:                                }
                    628:                                new_socket(AUTH_CONNECTION, sock);
                    629:                        }
                    630:                        break;
                    631:                case AUTH_CONNECTION:
                    632:                        if (buffer_len(&sockets[i].output) > 0 &&
                    633:                            FD_ISSET(sockets[i].fd, writeset)) {
1.46    ! markus    634:                                len = write(sockets[i].fd,
        !           635:                                    buffer_ptr(&sockets[i].output),
        !           636:                                    buffer_len(&sockets[i].output));
1.21      markus    637:                                if (len <= 0) {
                    638:                                        shutdown(sockets[i].fd, SHUT_RDWR);
                    639:                                        close(sockets[i].fd);
                    640:                                        sockets[i].type = AUTH_UNUSED;
1.30      djm       641:                                        buffer_free(&sockets[i].input);
                    642:                                        buffer_free(&sockets[i].output);
1.21      markus    643:                                        break;
                    644:                                }
                    645:                                buffer_consume(&sockets[i].output, len);
                    646:                        }
                    647:                        if (FD_ISSET(sockets[i].fd, readset)) {
                    648:                                len = read(sockets[i].fd, buf, sizeof(buf));
                    649:                                if (len <= 0) {
                    650:                                        shutdown(sockets[i].fd, SHUT_RDWR);
                    651:                                        close(sockets[i].fd);
                    652:                                        sockets[i].type = AUTH_UNUSED;
1.30      djm       653:                                        buffer_free(&sockets[i].input);
                    654:                                        buffer_free(&sockets[i].output);
1.21      markus    655:                                        break;
                    656:                                }
                    657:                                buffer_append(&sockets[i].input, buf, len);
                    658:                                process_message(&sockets[i]);
                    659:                        }
                    660:                        break;
                    661:                default:
                    662:                        fatal("Unknown type %d", sockets[i].type);
                    663:                }
1.1       deraadt   664: }
                    665:
1.6       deraadt   666: void
1.2       provos    667: check_parent_exists(int sig)
1.1       deraadt   668: {
1.46    ! markus    669:        int save_errno = errno;
        !           670:
1.29      deraadt   671:        if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
1.21      markus    672:                /* printf("Parent has died - Authentication agent exiting.\n"); */
                    673:                exit(1);
                    674:        }
                    675:        signal(SIGALRM, check_parent_exists);
                    676:        alarm(10);
1.46    ! markus    677:        errno = save_errno;
1.1       deraadt   678: }
                    679:
1.15      markus    680: void
                    681: cleanup_socket(void)
                    682: {
1.44      markus    683:        unlink(socket_name);
1.21      markus    684:        rmdir(socket_dir);
1.10      markus    685: }
                    686:
1.15      markus    687: void
                    688: cleanup_exit(int i)
                    689: {
1.21      markus    690:        cleanup_socket();
                    691:        exit(i);
1.15      markus    692: }
                    693:
                    694: void
                    695: usage()
                    696: {
1.21      markus    697:        fprintf(stderr, "ssh-agent version %s\n", SSH_VERSION);
                    698:        fprintf(stderr, "Usage: %s [-c | -s] [-k] [command {args...]]\n",
1.46    ! markus    699:            __progname);
1.21      markus    700:        exit(1);
1.15      markus    701: }
                    702:
1.2       provos    703: int
                    704: main(int ac, char **av)
1.1       deraadt   705: {
1.21      markus    706:        int sock, c_flag = 0, k_flag = 0, s_flag = 0, ch;
                    707:        struct sockaddr_un sunaddr;
1.41      markus    708:        struct rlimit rlim;
1.21      markus    709:        pid_t pid;
                    710:        char *shell, *format, *pidstr, pidstrbuf[1 + 3 * sizeof pid];
1.43      markus    711:        extern int optind;
1.46    ! markus    712:        fd_set *readsetp = NULL, *writesetp = NULL;
1.21      markus    713:
                    714:        while ((ch = getopt(ac, av, "cks")) != -1) {
                    715:                switch (ch) {
                    716:                case 'c':
                    717:                        if (s_flag)
                    718:                                usage();
                    719:                        c_flag++;
                    720:                        break;
                    721:                case 'k':
                    722:                        k_flag++;
                    723:                        break;
                    724:                case 's':
                    725:                        if (c_flag)
                    726:                                usage();
                    727:                        s_flag++;
                    728:                        break;
                    729:                default:
                    730:                        usage();
                    731:                }
                    732:        }
                    733:        ac -= optind;
                    734:        av += optind;
                    735:
                    736:        if (ac > 0 && (c_flag || k_flag || s_flag))
                    737:                usage();
                    738:
                    739:        if (ac == 0 && !c_flag && !k_flag && !s_flag) {
                    740:                shell = getenv("SHELL");
                    741:                if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
                    742:                        c_flag = 1;
                    743:        }
                    744:        if (k_flag) {
                    745:                pidstr = getenv(SSH_AGENTPID_ENV_NAME);
                    746:                if (pidstr == NULL) {
                    747:                        fprintf(stderr, "%s not set, cannot kill agent\n",
1.46    ! markus    748:                            SSH_AGENTPID_ENV_NAME);
1.21      markus    749:                        exit(1);
                    750:                }
                    751:                pid = atoi(pidstr);
1.46    ! markus    752:                if (pid < 1) {
1.21      markus    753:                        fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
1.46    ! markus    754:                            SSH_AGENTPID_ENV_NAME, pidstr);
1.21      markus    755:                        exit(1);
                    756:                }
                    757:                if (kill(pid, SIGTERM) == -1) {
                    758:                        perror("kill");
                    759:                        exit(1);
                    760:                }
                    761:                format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
                    762:                printf(format, SSH_AUTHSOCKET_ENV_NAME);
                    763:                printf(format, SSH_AGENTPID_ENV_NAME);
                    764:                printf("echo Agent pid %d killed;\n", pid);
                    765:                exit(0);
                    766:        }
                    767:        parent_pid = getpid();
                    768:
                    769:        /* Create private directory for agent socket */
                    770:        strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
                    771:        if (mkdtemp(socket_dir) == NULL) {
                    772:                perror("mkdtemp: private socket dir");
                    773:                exit(1);
                    774:        }
                    775:        snprintf(socket_name, sizeof socket_name, "%s/agent.%d", socket_dir,
1.46    ! markus    776:            parent_pid);
1.21      markus    777:
1.23      markus    778:        /*
                    779:         * Create socket early so it will exist before command gets run from
                    780:         * the parent.
                    781:         */
1.21      markus    782:        sock = socket(AF_UNIX, SOCK_STREAM, 0);
                    783:        if (sock < 0) {
                    784:                perror("socket");
                    785:                cleanup_exit(1);
                    786:        }
                    787:        memset(&sunaddr, 0, sizeof(sunaddr));
                    788:        sunaddr.sun_family = AF_UNIX;
                    789:        strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
                    790:        if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
                    791:                perror("bind");
                    792:                cleanup_exit(1);
                    793:        }
                    794:        if (listen(sock, 5) < 0) {
                    795:                perror("listen");
                    796:                cleanup_exit(1);
                    797:        }
1.46    ! markus    798:
1.23      markus    799:        /*
                    800:         * Fork, and have the parent execute the command, if any, or present
                    801:         * the socket data.  The child continues as the authentication agent.
                    802:         */
1.21      markus    803:        pid = fork();
                    804:        if (pid == -1) {
                    805:                perror("fork");
                    806:                exit(1);
                    807:        }
                    808:        if (pid != 0) {         /* Parent - execute the given command. */
                    809:                close(sock);
                    810:                snprintf(pidstrbuf, sizeof pidstrbuf, "%d", pid);
                    811:                if (ac == 0) {
                    812:                        format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
                    813:                        printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1.46    ! markus    814:                            SSH_AUTHSOCKET_ENV_NAME);
1.21      markus    815:                        printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1.46    ! markus    816:                            SSH_AGENTPID_ENV_NAME);
1.21      markus    817:                        printf("echo Agent pid %d;\n", pid);
                    818:                        exit(0);
                    819:                }
1.36      deraadt   820:                if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
                    821:                    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
                    822:                        perror("setenv");
                    823:                        exit(1);
                    824:                }
1.21      markus    825:                execvp(av[0], av);
                    826:                perror(av[0]);
                    827:                exit(1);
                    828:        }
                    829:        close(0);
                    830:        close(1);
                    831:        close(2);
                    832:
1.41      markus    833:        /* deny core dumps, since memory contains unencrypted private keys */
                    834:        rlim.rlim_cur = rlim.rlim_max = 0;
                    835:        if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
                    836:                perror("setrlimit rlimit_core failed");
                    837:                cleanup_exit(1);
                    838:        }
1.21      markus    839:        if (setsid() == -1) {
                    840:                perror("setsid");
                    841:                cleanup_exit(1);
                    842:        }
                    843:        if (atexit(cleanup_socket) < 0) {
                    844:                perror("atexit");
                    845:                cleanup_exit(1);
                    846:        }
                    847:        new_socket(AUTH_SOCKET, sock);
                    848:        if (ac > 0) {
                    849:                signal(SIGALRM, check_parent_exists);
                    850:                alarm(10);
                    851:        }
1.33      markus    852:        idtab_init();
1.21      markus    853:        signal(SIGINT, SIG_IGN);
                    854:        signal(SIGPIPE, SIG_IGN);
1.28      markus    855:        signal(SIGHUP, cleanup_exit);
                    856:        signal(SIGTERM, cleanup_exit);
1.21      markus    857:        while (1) {
1.46    ! markus    858:                prepare_select(&readsetp, &writesetp, &max_fd);
        !           859:                if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
1.21      markus    860:                        if (errno == EINTR)
                    861:                                continue;
                    862:                        exit(1);
                    863:                }
1.46    ! markus    864:                after_select(readsetp, writesetp);
1.15      markus    865:        }
1.21      markus    866:        /* NOTREACHED */
1.1       deraadt   867: }