[BACK]Return to ts.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / openssl

Annotation of src/usr.bin/openssl/ts.c, Revision 1.12

1.12    ! semarie     1: /* $OpenBSD: ts.c,v 1.11 2015/10/10 22:28:51 doug Exp $ */
1.1       jsing       2: /* Written by Zoltan Glozik (zglozik@stones.com) for the OpenSSL
                      3:  * project 2002.
                      4:  */
                      5: /* ====================================================================
                      6:  * Copyright (c) 2001 The OpenSSL Project.  All rights reserved.
                      7:  *
                      8:  * Redistribution and use in source and binary forms, with or without
                      9:  * modification, are permitted provided that the following conditions
                     10:  * are met:
                     11:  *
                     12:  * 1. Redistributions of source code must retain the above copyright
                     13:  *    notice, this list of conditions and the following disclaimer.
                     14:  *
                     15:  * 2. Redistributions in binary form must reproduce the above copyright
                     16:  *    notice, this list of conditions and the following disclaimer in
                     17:  *    the documentation and/or other materials provided with the
                     18:  *    distribution.
                     19:  *
                     20:  * 3. All advertising materials mentioning features or use of this
                     21:  *    software must display the following acknowledgment:
                     22:  *    "This product includes software developed by the OpenSSL Project
                     23:  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
                     24:  *
                     25:  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
                     26:  *    endorse or promote products derived from this software without
                     27:  *    prior written permission. For written permission, please contact
                     28:  *    licensing@OpenSSL.org.
                     29:  *
                     30:  * 5. Products derived from this software may not be called "OpenSSL"
                     31:  *    nor may "OpenSSL" appear in their names without prior written
                     32:  *    permission of the OpenSSL Project.
                     33:  *
                     34:  * 6. Redistributions of any form whatsoever must retain the following
                     35:  *    acknowledgment:
                     36:  *    "This product includes software developed by the OpenSSL Project
                     37:  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
                     38:  *
                     39:  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
                     40:  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     41:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
                     42:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
                     43:  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
                     44:  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     45:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
                     46:  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     47:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
                     48:  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
                     49:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
                     50:  * OF THE POSSIBILITY OF SUCH DAMAGE.
                     51:  * ====================================================================
                     52:  *
                     53:  * This product includes cryptographic software written by Eric Young
                     54:  * (eay@cryptsoft.com).  This product includes software written by Tim
                     55:  * Hudson (tjh@cryptsoft.com).
                     56:  *
                     57:  */
                     58:
                     59: #include <stdio.h>
                     60: #include <stdlib.h>
                     61: #include <string.h>
                     62:
                     63: #include "apps.h"
                     64:
                     65: #include <openssl/bio.h>
                     66: #include <openssl/bn.h>
                     67: #include <openssl/err.h>
                     68: #include <openssl/pem.h>
                     69: #include <openssl/ts.h>
                     70:
                     71: /* Length of the nonce of the request in bits (must be a multiple of 8). */
                     72: #define        NONCE_LENGTH            64
                     73:
                     74: /* Macro definitions for the configuration file. */
                     75: #define        ENV_OID_FILE            "oid_file"
                     76:
                     77: /* Local function declarations. */
                     78:
                     79: static ASN1_OBJECT *txt2obj(const char *oid);
                     80: static CONF *load_config_file(const char *configfile);
                     81:
                     82: /* Query related functions. */
                     83: static int query_command(const char *data, char *digest,
                     84:     const EVP_MD * md, const char *policy, int no_nonce,
                     85:     int cert, const char *in, const char *out, int text);
                     86: static BIO *BIO_open_with_default(const char *file, const char *mode,
                     87:     FILE * default_fp);
                     88: static TS_REQ *create_query(BIO * data_bio, char *digest, const EVP_MD * md,
                     89:     const char *policy, int no_nonce, int cert);
                     90: static int create_digest(BIO * input, char *digest,
                     91:     const EVP_MD * md, unsigned char **md_value);
                     92: static ASN1_INTEGER *create_nonce(int bits);
                     93:
                     94: /* Reply related functions. */
1.6       bcook      95: static int reply_command(CONF * conf, char *section,
1.1       jsing      96:     char *queryfile, char *passin, char *inkey,
                     97:     char *signer, char *chain, const char *policy,
                     98:     char *in, int token_in, char *out, int token_out,
                     99:     int text);
                    100: static TS_RESP *read_PKCS7(BIO * in_bio);
1.6       bcook     101: static TS_RESP *create_response(CONF * conf, const char *section,
1.1       jsing     102:     char *queryfile, char *passin, char *inkey,
                    103:     char *signer, char *chain, const char *policy);
                    104: static ASN1_INTEGER *serial_cb(TS_RESP_CTX * ctx, void *data);
                    105: static ASN1_INTEGER *next_serial(const char *serialfile);
                    106: static int save_ts_serial(const char *serialfile, ASN1_INTEGER * serial);
                    107:
                    108: /* Verify related functions. */
                    109: static int verify_command(char *data, char *digest, char *queryfile,
                    110:     char *in, int token_in,
                    111:     char *ca_path, char *ca_file, char *untrusted);
                    112: static TS_VERIFY_CTX *create_verify_ctx(char *data, char *digest,
                    113:     char *queryfile,
                    114:     char *ca_path, char *ca_file,
                    115:     char *untrusted);
                    116: static X509_STORE *create_cert_store(char *ca_path, char *ca_file);
                    117: static int verify_cb(int ok, X509_STORE_CTX * ctx);
                    118:
                    119: int
                    120: ts_main(int argc, char **argv)
                    121: {
                    122:        int ret = 1;
                    123:        char *configfile = NULL;
                    124:        char *section = NULL;
                    125:        CONF *conf = NULL;
                    126:        enum mode {
                    127:                CMD_NONE, CMD_QUERY, CMD_REPLY, CMD_VERIFY
                    128:        } mode = CMD_NONE;
                    129:        char *data = NULL;
                    130:        char *digest = NULL;
                    131:        const EVP_MD *md = NULL;
                    132:        char *policy = NULL;
                    133:        int no_nonce = 0;
                    134:        int cert = 0;
                    135:        char *in = NULL;
                    136:        char *out = NULL;
                    137:        int text = 0;
                    138:        char *queryfile = NULL;
                    139:        char *passin = NULL;    /* Password source. */
                    140:        char *password = NULL;  /* Password itself. */
                    141:        char *inkey = NULL;
                    142:        char *signer = NULL;
                    143:        char *chain = NULL;
                    144:        char *ca_path = NULL;
                    145:        char *ca_file = NULL;
                    146:        char *untrusted = NULL;
                    147:        /* Input is ContentInfo instead of TimeStampResp. */
                    148:        int token_in = 0;
                    149:        /* Output is ContentInfo instead of TimeStampResp. */
                    150:        int token_out = 0;
1.11      doug      151:
                    152:        if (single_execution) {
1.12    ! semarie   153:                if (pledge("stdio rpath wpath cpath tty", NULL) == -1)
1.11      doug      154:                        perror("pledge");
                    155:        }
1.1       jsing     156:
                    157:        for (argc--, argv++; argc > 0; argc--, argv++) {
                    158:                if (strcmp(*argv, "-config") == 0) {
                    159:                        if (argc-- < 1)
                    160:                                goto usage;
                    161:                        configfile = *++argv;
                    162:                } else if (strcmp(*argv, "-section") == 0) {
                    163:                        if (argc-- < 1)
                    164:                                goto usage;
                    165:                        section = *++argv;
                    166:                } else if (strcmp(*argv, "-query") == 0) {
                    167:                        if (mode != CMD_NONE)
                    168:                                goto usage;
                    169:                        mode = CMD_QUERY;
                    170:                } else if (strcmp(*argv, "-data") == 0) {
                    171:                        if (argc-- < 1)
                    172:                                goto usage;
                    173:                        data = *++argv;
                    174:                } else if (strcmp(*argv, "-digest") == 0) {
                    175:                        if (argc-- < 1)
                    176:                                goto usage;
                    177:                        digest = *++argv;
                    178:                } else if (strcmp(*argv, "-policy") == 0) {
                    179:                        if (argc-- < 1)
                    180:                                goto usage;
                    181:                        policy = *++argv;
                    182:                } else if (strcmp(*argv, "-no_nonce") == 0) {
                    183:                        no_nonce = 1;
                    184:                } else if (strcmp(*argv, "-cert") == 0) {
                    185:                        cert = 1;
                    186:                } else if (strcmp(*argv, "-in") == 0) {
                    187:                        if (argc-- < 1)
                    188:                                goto usage;
                    189:                        in = *++argv;
                    190:                } else if (strcmp(*argv, "-token_in") == 0) {
                    191:                        token_in = 1;
                    192:                } else if (strcmp(*argv, "-out") == 0) {
                    193:                        if (argc-- < 1)
                    194:                                goto usage;
                    195:                        out = *++argv;
                    196:                } else if (strcmp(*argv, "-token_out") == 0) {
                    197:                        token_out = 1;
                    198:                } else if (strcmp(*argv, "-text") == 0) {
                    199:                        text = 1;
                    200:                } else if (strcmp(*argv, "-reply") == 0) {
                    201:                        if (mode != CMD_NONE)
                    202:                                goto usage;
                    203:                        mode = CMD_REPLY;
                    204:                } else if (strcmp(*argv, "-queryfile") == 0) {
                    205:                        if (argc-- < 1)
                    206:                                goto usage;
                    207:                        queryfile = *++argv;
                    208:                } else if (strcmp(*argv, "-passin") == 0) {
                    209:                        if (argc-- < 1)
                    210:                                goto usage;
                    211:                        passin = *++argv;
                    212:                } else if (strcmp(*argv, "-inkey") == 0) {
                    213:                        if (argc-- < 1)
                    214:                                goto usage;
                    215:                        inkey = *++argv;
                    216:                } else if (strcmp(*argv, "-signer") == 0) {
                    217:                        if (argc-- < 1)
                    218:                                goto usage;
                    219:                        signer = *++argv;
                    220:                } else if (strcmp(*argv, "-chain") == 0) {
                    221:                        if (argc-- < 1)
                    222:                                goto usage;
                    223:                        chain = *++argv;
                    224:                } else if (strcmp(*argv, "-verify") == 0) {
                    225:                        if (mode != CMD_NONE)
                    226:                                goto usage;
                    227:                        mode = CMD_VERIFY;
                    228:                } else if (strcmp(*argv, "-CApath") == 0) {
                    229:                        if (argc-- < 1)
                    230:                                goto usage;
                    231:                        ca_path = *++argv;
                    232:                } else if (strcmp(*argv, "-CAfile") == 0) {
                    233:                        if (argc-- < 1)
                    234:                                goto usage;
                    235:                        ca_file = *++argv;
                    236:                } else if (strcmp(*argv, "-untrusted") == 0) {
                    237:                        if (argc-- < 1)
                    238:                                goto usage;
                    239:                        untrusted = *++argv;
                    240:                } else if ((md = EVP_get_digestbyname(*argv + 1)) != NULL) {
                    241:                        /* empty. */
                    242:                } else
                    243:                        goto usage;
                    244:        }
                    245:
                    246:        /* Get the password if required. */
                    247:        if (mode == CMD_REPLY && passin &&
                    248:            !app_passwd(bio_err, passin, NULL, &password, NULL)) {
                    249:                BIO_printf(bio_err, "Error getting password.\n");
                    250:                goto cleanup;
                    251:        }
                    252:        /*
                    253:         * Check consistency of parameters and execute the appropriate
                    254:         * function.
                    255:         */
                    256:        switch (mode) {
                    257:        case CMD_NONE:
                    258:                goto usage;
                    259:        case CMD_QUERY:
                    260:                /*
                    261:                 * Data file and message imprint cannot be specified at the
                    262:                 * same time.
                    263:                 */
                    264:                ret = data != NULL && digest != NULL;
                    265:                if (ret)
                    266:                        goto usage;
                    267:                /* Load the config file for possible policy OIDs. */
                    268:                conf = load_config_file(configfile);
                    269:                ret = !query_command(data, digest, md, policy, no_nonce, cert,
                    270:                    in, out, text);
                    271:                break;
                    272:        case CMD_REPLY:
                    273:                conf = load_config_file(configfile);
                    274:                if (in == NULL) {
                    275:                        ret = !(queryfile != NULL && conf != NULL && !token_in);
                    276:                        if (ret)
                    277:                                goto usage;
                    278:                } else {
                    279:                        /* 'in' and 'queryfile' are exclusive. */
                    280:                        ret = !(queryfile == NULL);
                    281:                        if (ret)
                    282:                                goto usage;
                    283:                }
                    284:
1.6       bcook     285:                ret = !reply_command(conf, section, queryfile,
1.1       jsing     286:                    password, inkey, signer, chain, policy,
                    287:                    in, token_in, out, token_out, text);
                    288:                break;
                    289:        case CMD_VERIFY:
                    290:                ret = !(((queryfile && !data && !digest) ||
                    291:                    (!queryfile && data && !digest) ||
                    292:                    (!queryfile && !data && digest)) && in != NULL);
                    293:                if (ret)
                    294:                        goto usage;
                    295:
                    296:                ret = !verify_command(data, digest, queryfile, in, token_in,
                    297:                    ca_path, ca_file, untrusted);
                    298:        }
                    299:
                    300:        goto cleanup;
                    301:
                    302: usage:
                    303:        BIO_printf(bio_err, "usage:\n"
                    304:            "ts -query [-config configfile] "
                    305:            "[-data file_to_hash] [-digest digest_bytes]"
1.10      bcook     306:            "[-md4|-md5|-sha1|-ripemd160] "
1.1       jsing     307:            "[-policy object_id] [-no_nonce] [-cert] "
                    308:            "[-in request.tsq] [-out request.tsq] [-text]\n");
                    309:        BIO_printf(bio_err, "or\n"
                    310:            "ts -reply [-config configfile] [-section tsa_section] "
                    311:            "[-queryfile request.tsq] [-passin password] "
                    312:            "[-signer tsa_cert.pem] [-inkey private_key.pem] "
                    313:            "[-chain certs_file.pem] [-policy object_id] "
                    314:            "[-in response.tsr] [-token_in] "
1.6       bcook     315:            "[-out response.tsr] [-token_out] [-text]\n");
1.1       jsing     316:        BIO_printf(bio_err, "or\n"
                    317:            "ts -verify [-data file_to_hash] [-digest digest_bytes] "
                    318:            "[-queryfile request.tsq] "
                    319:            "-in response.tsr [-token_in] "
                    320:            "-CApath ca_path -CAfile ca_file.pem "
                    321:            "-untrusted cert_file.pem\n");
                    322:
                    323: cleanup:
                    324:        /* Clean up. */
                    325:        NCONF_free(conf);
                    326:        free(password);
                    327:        OBJ_cleanup();
                    328:
                    329:        return (ret);
                    330: }
                    331:
                    332: /*
                    333:  * Configuration file-related function definitions.
                    334:  */
                    335:
                    336: static ASN1_OBJECT *
                    337: txt2obj(const char *oid)
                    338: {
                    339:        ASN1_OBJECT *oid_obj = NULL;
                    340:
                    341:        if (!(oid_obj = OBJ_txt2obj(oid, 0)))
                    342:                BIO_printf(bio_err, "cannot convert %s to OID\n", oid);
                    343:
                    344:        return oid_obj;
                    345: }
                    346:
                    347: static CONF *
                    348: load_config_file(const char *configfile)
                    349: {
                    350:        CONF *conf = NULL;
                    351:        long errorline = -1;
                    352:
                    353:        if (!configfile)
                    354:                configfile = getenv("OPENSSL_CONF");
                    355:
                    356:        if (configfile &&
                    357:            (!(conf = NCONF_new(NULL)) ||
                    358:            NCONF_load(conf, configfile, &errorline) <= 0)) {
                    359:                if (errorline <= 0)
                    360:                        BIO_printf(bio_err, "error loading the config file "
                    361:                            "'%s'\n", configfile);
                    362:                else
                    363:                        BIO_printf(bio_err, "error on line %ld of config file "
                    364:                            "'%s'\n", errorline, configfile);
                    365:        }
                    366:        if (conf != NULL) {
                    367:                const char *p;
                    368:
                    369:                BIO_printf(bio_err, "Using configuration from %s\n",
                    370:                    configfile);
                    371:                p = NCONF_get_string(conf, NULL, ENV_OID_FILE);
                    372:                if (p != NULL) {
                    373:                        BIO *oid_bio = BIO_new_file(p, "r");
                    374:                        if (!oid_bio)
                    375:                                ERR_print_errors(bio_err);
                    376:                        else {
                    377:                                OBJ_create_objects(oid_bio);
                    378:                                BIO_free_all(oid_bio);
                    379:                        }
                    380:                } else
                    381:                        ERR_clear_error();
                    382:                if (!add_oid_section(bio_err, conf))
                    383:                        ERR_print_errors(bio_err);
                    384:        }
                    385:        return conf;
                    386: }
                    387:
                    388: /*
                    389:  * Query-related method definitions.
                    390:  */
                    391:
                    392: static int
                    393: query_command(const char *data, char *digest, const EVP_MD * md,
                    394:     const char *policy, int no_nonce, int cert, const char *in,
                    395:     const char *out, int text)
                    396: {
                    397:        int ret = 0;
                    398:        TS_REQ *query = NULL;
                    399:        BIO *in_bio = NULL;
                    400:        BIO *data_bio = NULL;
                    401:        BIO *out_bio = NULL;
                    402:
                    403:        /* Build query object either from file or from scratch. */
                    404:        if (in != NULL) {
                    405:                if ((in_bio = BIO_new_file(in, "rb")) == NULL)
                    406:                        goto end;
                    407:                query = d2i_TS_REQ_bio(in_bio, NULL);
                    408:        } else {
                    409:                /* Open the file if no explicit digest bytes were specified. */
                    410:                if (!digest &&
                    411:                    !(data_bio = BIO_open_with_default(data, "rb", stdin)))
                    412:                        goto end;
                    413:                /* Creating the query object. */
                    414:                query = create_query(data_bio, digest, md,
                    415:                    policy, no_nonce, cert);
                    416:                /* Saving the random number generator state. */
                    417:        }
                    418:        if (query == NULL)
                    419:                goto end;
                    420:
                    421:        /* Write query either in ASN.1 or in text format. */
                    422:        if ((out_bio = BIO_open_with_default(out, "wb", stdout)) == NULL)
                    423:                goto end;
                    424:        if (text) {
                    425:                /* Text output. */
                    426:                if (!TS_REQ_print_bio(out_bio, query))
                    427:                        goto end;
                    428:        } else {
                    429:                /* ASN.1 output. */
                    430:                if (!i2d_TS_REQ_bio(out_bio, query))
                    431:                        goto end;
                    432:        }
                    433:
                    434:        ret = 1;
                    435:
                    436: end:
                    437:        ERR_print_errors(bio_err);
                    438:
                    439:        /* Clean up. */
                    440:        BIO_free_all(in_bio);
                    441:        BIO_free_all(data_bio);
                    442:        BIO_free_all(out_bio);
                    443:        TS_REQ_free(query);
                    444:
                    445:        return ret;
                    446: }
                    447:
                    448: static BIO *
                    449: BIO_open_with_default(const char *file, const char *mode, FILE * default_fp)
                    450: {
                    451:        return file == NULL ? BIO_new_fp(default_fp, BIO_NOCLOSE) :
                    452:            BIO_new_file(file, mode);
                    453: }
                    454:
                    455: static TS_REQ *
                    456: create_query(BIO * data_bio, char *digest, const EVP_MD * md,
                    457:     const char *policy, int no_nonce, int cert)
                    458: {
                    459:        int ret = 0;
                    460:        TS_REQ *ts_req = NULL;
                    461:        int len;
                    462:        TS_MSG_IMPRINT *msg_imprint = NULL;
                    463:        X509_ALGOR *algo = NULL;
                    464:        unsigned char *data = NULL;
                    465:        ASN1_OBJECT *policy_obj = NULL;
                    466:        ASN1_INTEGER *nonce_asn1 = NULL;
                    467:
                    468:        /* Setting default message digest. */
                    469:        if (!md && !(md = EVP_get_digestbyname("sha1")))
                    470:                goto err;
                    471:
                    472:        /* Creating request object. */
                    473:        if (!(ts_req = TS_REQ_new()))
                    474:                goto err;
                    475:
                    476:        /* Setting version. */
                    477:        if (!TS_REQ_set_version(ts_req, 1))
                    478:                goto err;
                    479:
                    480:        /* Creating and adding MSG_IMPRINT object. */
                    481:        if (!(msg_imprint = TS_MSG_IMPRINT_new()))
                    482:                goto err;
                    483:
                    484:        /* Adding algorithm. */
                    485:        if (!(algo = X509_ALGOR_new()))
                    486:                goto err;
                    487:        if (!(algo->algorithm = OBJ_nid2obj(EVP_MD_type(md))))
                    488:                goto err;
                    489:        if (!(algo->parameter = ASN1_TYPE_new()))
                    490:                goto err;
                    491:        algo->parameter->type = V_ASN1_NULL;
                    492:        if (!TS_MSG_IMPRINT_set_algo(msg_imprint, algo))
                    493:                goto err;
                    494:
                    495:        /* Adding message digest. */
                    496:        if ((len = create_digest(data_bio, digest, md, &data)) == 0)
                    497:                goto err;
                    498:        if (!TS_MSG_IMPRINT_set_msg(msg_imprint, data, len))
                    499:                goto err;
                    500:
                    501:        if (!TS_REQ_set_msg_imprint(ts_req, msg_imprint))
                    502:                goto err;
                    503:
                    504:        /* Setting policy if requested. */
                    505:        if (policy && !(policy_obj = txt2obj(policy)))
                    506:                goto err;
                    507:        if (policy_obj && !TS_REQ_set_policy_id(ts_req, policy_obj))
                    508:                goto err;
                    509:
                    510:        /* Setting nonce if requested. */
                    511:        if (!no_nonce && !(nonce_asn1 = create_nonce(NONCE_LENGTH)))
                    512:                goto err;
                    513:        if (nonce_asn1 && !TS_REQ_set_nonce(ts_req, nonce_asn1))
                    514:                goto err;
                    515:
                    516:        /* Setting certificate request flag if requested. */
                    517:        if (!TS_REQ_set_cert_req(ts_req, cert))
                    518:                goto err;
                    519:
                    520:        ret = 1;
                    521:
                    522: err:
                    523:        if (!ret) {
                    524:                TS_REQ_free(ts_req);
                    525:                ts_req = NULL;
                    526:                BIO_printf(bio_err, "could not create query\n");
                    527:        }
                    528:        TS_MSG_IMPRINT_free(msg_imprint);
                    529:        X509_ALGOR_free(algo);
                    530:        free(data);
                    531:        ASN1_OBJECT_free(policy_obj);
                    532:        ASN1_INTEGER_free(nonce_asn1);
                    533:
                    534:        return ts_req;
                    535: }
                    536:
                    537: static int
                    538: create_digest(BIO * input, char *digest, const EVP_MD * md,
                    539:     unsigned char **md_value)
                    540: {
                    541:        int md_value_len;
                    542:
                    543:        md_value_len = EVP_MD_size(md);
                    544:        if (md_value_len < 0)
                    545:                goto err;
                    546:        if (input) {
                    547:                /* Digest must be computed from an input file. */
                    548:                EVP_MD_CTX md_ctx;
                    549:                unsigned char buffer[4096];
                    550:                int length;
                    551:
                    552:                *md_value = malloc(md_value_len);
                    553:                if (*md_value == 0)
                    554:                        goto err;
                    555:
                    556:                EVP_DigestInit(&md_ctx, md);
                    557:                while ((length = BIO_read(input, buffer, sizeof(buffer))) > 0) {
                    558:                        EVP_DigestUpdate(&md_ctx, buffer, length);
                    559:                }
                    560:                EVP_DigestFinal(&md_ctx, *md_value, NULL);
                    561:        } else {
                    562:                /* Digest bytes are specified with digest. */
                    563:                long digest_len;
                    564:                *md_value = string_to_hex(digest, &digest_len);
                    565:                if (!*md_value || md_value_len != digest_len) {
                    566:                        free(*md_value);
                    567:                        *md_value = NULL;
                    568:                        BIO_printf(bio_err, "bad digest, %d bytes "
                    569:                            "must be specified\n", md_value_len);
                    570:                        goto err;
                    571:                }
                    572:        }
                    573:
                    574:        return md_value_len;
                    575: err:
                    576:        return 0;
                    577: }
                    578:
                    579: static ASN1_INTEGER *
                    580: create_nonce(int bits)
                    581: {
                    582:        unsigned char buf[20];
                    583:        ASN1_INTEGER *nonce = NULL;
                    584:        int len = (bits - 1) / 8 + 1;
                    585:        int i;
                    586:
                    587:        /* Generating random byte sequence. */
                    588:        if (len > (int) sizeof(buf))
                    589:                goto err;
1.3       jsing     590:        arc4random_buf(buf, len);
1.1       jsing     591:
                    592:        /* Find the first non-zero byte and creating ASN1_INTEGER object. */
                    593:        for (i = 0; i < len && !buf[i]; ++i)
                    594:                ;
                    595:        if (!(nonce = ASN1_INTEGER_new()))
                    596:                goto err;
                    597:        free(nonce->data);
                    598:        /* Allocate at least one byte. */
                    599:        nonce->length = len - i;
                    600:        if (!(nonce->data = malloc(nonce->length + 1)))
                    601:                goto err;
                    602:        memcpy(nonce->data, buf + i, nonce->length);
                    603:
                    604:        return nonce;
                    605:
                    606: err:
                    607:        BIO_printf(bio_err, "could not create nonce\n");
                    608:        ASN1_INTEGER_free(nonce);
                    609:        return NULL;
                    610: }
                    611: /*
                    612:  * Reply-related method definitions.
                    613:  */
                    614:
                    615: static int
1.6       bcook     616: reply_command(CONF * conf, char *section, char *queryfile,
1.1       jsing     617:     char *passin, char *inkey, char *signer, char *chain, const char *policy,
                    618:     char *in, int token_in, char *out, int token_out, int text)
                    619: {
                    620:        int ret = 0;
                    621:        TS_RESP *response = NULL;
                    622:        BIO *in_bio = NULL;
                    623:        BIO *query_bio = NULL;
                    624:        BIO *inkey_bio = NULL;
                    625:        BIO *signer_bio = NULL;
                    626:        BIO *out_bio = NULL;
                    627:
                    628:        /* Build response object either from response or query. */
                    629:        if (in != NULL) {
                    630:                if ((in_bio = BIO_new_file(in, "rb")) == NULL)
                    631:                        goto end;
                    632:                if (token_in) {
                    633:                        /*
                    634:                         * We have a ContentInfo (PKCS7) object, add
                    635:                         * 'granted' status info around it.
                    636:                         */
                    637:                        response = read_PKCS7(in_bio);
                    638:                } else {
                    639:                        /* We have a ready-made TS_RESP object. */
                    640:                        response = d2i_TS_RESP_bio(in_bio, NULL);
                    641:                }
                    642:        } else {
1.6       bcook     643:                response = create_response(conf, section, queryfile,
1.1       jsing     644:                    passin, inkey, signer, chain,
                    645:                    policy);
                    646:                if (response)
                    647:                        BIO_printf(bio_err, "Response has been generated.\n");
                    648:                else
                    649:                        BIO_printf(bio_err, "Response is not generated.\n");
                    650:        }
                    651:        if (response == NULL)
                    652:                goto end;
                    653:
                    654:        /* Write response either in ASN.1 or text format. */
                    655:        if ((out_bio = BIO_open_with_default(out, "wb", stdout)) == NULL)
                    656:                goto end;
                    657:        if (text) {
                    658:                /* Text output. */
                    659:                if (token_out) {
                    660:                        TS_TST_INFO *tst_info = TS_RESP_get_tst_info(response);
                    661:                        if (!TS_TST_INFO_print_bio(out_bio, tst_info))
                    662:                                goto end;
                    663:                } else {
                    664:                        if (!TS_RESP_print_bio(out_bio, response))
                    665:                                goto end;
                    666:                }
                    667:        } else {
                    668:                /* ASN.1 DER output. */
                    669:                if (token_out) {
                    670:                        PKCS7 *token = TS_RESP_get_token(response);
                    671:                        if (!i2d_PKCS7_bio(out_bio, token))
                    672:                                goto end;
                    673:                } else {
                    674:                        if (!i2d_TS_RESP_bio(out_bio, response))
                    675:                                goto end;
                    676:                }
                    677:        }
                    678:
                    679:        ret = 1;
                    680:
                    681: end:
                    682:        ERR_print_errors(bio_err);
                    683:
                    684:        /* Clean up. */
                    685:        BIO_free_all(in_bio);
                    686:        BIO_free_all(query_bio);
                    687:        BIO_free_all(inkey_bio);
                    688:        BIO_free_all(signer_bio);
                    689:        BIO_free_all(out_bio);
                    690:        TS_RESP_free(response);
                    691:
                    692:        return ret;
                    693: }
                    694:
                    695: /* Reads a PKCS7 token and adds default 'granted' status info to it. */
                    696: static TS_RESP *
                    697: read_PKCS7(BIO * in_bio)
                    698: {
                    699:        int ret = 0;
                    700:        PKCS7 *token = NULL;
                    701:        TS_TST_INFO *tst_info = NULL;
                    702:        TS_RESP *resp = NULL;
                    703:        TS_STATUS_INFO *si = NULL;
                    704:
                    705:        /* Read PKCS7 object and extract the signed time stamp info. */
                    706:        if (!(token = d2i_PKCS7_bio(in_bio, NULL)))
                    707:                goto end;
                    708:        if (!(tst_info = PKCS7_to_TS_TST_INFO(token)))
                    709:                goto end;
                    710:
                    711:        /* Creating response object. */
                    712:        if (!(resp = TS_RESP_new()))
                    713:                goto end;
                    714:
                    715:        /* Create granted status info. */
                    716:        if (!(si = TS_STATUS_INFO_new()))
                    717:                goto end;
                    718:        if (!(ASN1_INTEGER_set(si->status, TS_STATUS_GRANTED)))
                    719:                goto end;
                    720:        if (!TS_RESP_set_status_info(resp, si))
                    721:                goto end;
                    722:
                    723:        /* Setting encapsulated token. */
                    724:        TS_RESP_set_tst_info(resp, token, tst_info);
                    725:        token = NULL;           /* Ownership is lost. */
                    726:        tst_info = NULL;        /* Ownership is lost. */
                    727:
                    728:        ret = 1;
                    729: end:
                    730:        PKCS7_free(token);
                    731:        TS_TST_INFO_free(tst_info);
                    732:        if (!ret) {
                    733:                TS_RESP_free(resp);
                    734:                resp = NULL;
                    735:        }
                    736:        TS_STATUS_INFO_free(si);
                    737:        return resp;
                    738: }
                    739:
                    740: static TS_RESP *
1.6       bcook     741: create_response(CONF * conf, const char *section,
1.1       jsing     742:     char *queryfile, char *passin, char *inkey,
                    743:     char *signer, char *chain, const char *policy)
                    744: {
                    745:        int ret = 0;
                    746:        TS_RESP *response = NULL;
                    747:        BIO *query_bio = NULL;
                    748:        TS_RESP_CTX *resp_ctx = NULL;
                    749:
                    750:        if (!(query_bio = BIO_new_file(queryfile, "rb")))
                    751:                goto end;
                    752:
                    753:        /* Getting TSA configuration section. */
                    754:        if (!(section = TS_CONF_get_tsa_section(conf, section)))
                    755:                goto end;
                    756:
                    757:        /* Setting up response generation context. */
                    758:        if (!(resp_ctx = TS_RESP_CTX_new()))
                    759:                goto end;
                    760:
                    761:        /* Setting serial number provider callback. */
                    762:        if (!TS_CONF_set_serial(conf, section, serial_cb, resp_ctx))
                    763:                goto end;
                    764:
                    765:        /* Setting TSA signer certificate. */
                    766:        if (!TS_CONF_set_signer_cert(conf, section, signer, resp_ctx))
                    767:                goto end;
                    768:
                    769:        /* Setting TSA signer certificate chain. */
                    770:        if (!TS_CONF_set_certs(conf, section, chain, resp_ctx))
                    771:                goto end;
                    772:
                    773:        /* Setting TSA signer private key. */
                    774:        if (!TS_CONF_set_signer_key(conf, section, inkey, passin, resp_ctx))
                    775:                goto end;
                    776:
                    777:        /* Setting default policy OID. */
                    778:        if (!TS_CONF_set_def_policy(conf, section, policy, resp_ctx))
                    779:                goto end;
                    780:
                    781:        /* Setting acceptable policy OIDs. */
                    782:        if (!TS_CONF_set_policies(conf, section, resp_ctx))
                    783:                goto end;
                    784:
                    785:        /* Setting the acceptable one-way hash algorithms. */
                    786:        if (!TS_CONF_set_digests(conf, section, resp_ctx))
                    787:                goto end;
                    788:
                    789:        /* Setting guaranteed time stamp accuracy. */
                    790:        if (!TS_CONF_set_accuracy(conf, section, resp_ctx))
                    791:                goto end;
                    792:
                    793:        /* Setting the precision of the time. */
                    794:        if (!TS_CONF_set_clock_precision_digits(conf, section, resp_ctx))
                    795:                goto end;
                    796:
                    797:        /* Setting the ordering flaf if requested. */
                    798:        if (!TS_CONF_set_ordering(conf, section, resp_ctx))
                    799:                goto end;
                    800:
                    801:        /* Setting the TSA name required flag if requested. */
                    802:        if (!TS_CONF_set_tsa_name(conf, section, resp_ctx))
                    803:                goto end;
                    804:
                    805:        /* Setting the ESS cert id chain flag if requested. */
                    806:        if (!TS_CONF_set_ess_cert_id_chain(conf, section, resp_ctx))
                    807:                goto end;
                    808:
                    809:        /* Creating the response. */
                    810:        if (!(response = TS_RESP_create_response(resp_ctx, query_bio)))
                    811:                goto end;
                    812:
                    813:        ret = 1;
                    814: end:
                    815:        if (!ret) {
                    816:                TS_RESP_free(response);
                    817:                response = NULL;
                    818:        }
                    819:        TS_RESP_CTX_free(resp_ctx);
                    820:        BIO_free_all(query_bio);
                    821:
                    822:        return response;
                    823: }
                    824:
                    825: static ASN1_INTEGER *
                    826: serial_cb(TS_RESP_CTX * ctx, void *data)
                    827: {
                    828:        const char *serial_file = (const char *) data;
                    829:        ASN1_INTEGER *serial = next_serial(serial_file);
                    830:
                    831:        if (!serial) {
                    832:                TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
                    833:                    "Error during serial number "
                    834:                    "generation.");
                    835:                TS_RESP_CTX_add_failure_info(ctx,
                    836:                    TS_INFO_ADD_INFO_NOT_AVAILABLE);
                    837:        } else
                    838:                save_ts_serial(serial_file, serial);
                    839:
                    840:        return serial;
                    841: }
                    842:
                    843: static ASN1_INTEGER *
                    844: next_serial(const char *serialfile)
                    845: {
                    846:        int ret = 0;
                    847:        BIO *in = NULL;
                    848:        ASN1_INTEGER *serial = NULL;
                    849:        BIGNUM *bn = NULL;
                    850:
                    851:        if (!(serial = ASN1_INTEGER_new()))
                    852:                goto err;
                    853:
                    854:        if (!(in = BIO_new_file(serialfile, "r"))) {
                    855:                ERR_clear_error();
                    856:                BIO_printf(bio_err, "Warning: could not open file %s for "
                    857:                    "reading, using serial number: 1\n", serialfile);
                    858:                if (!ASN1_INTEGER_set(serial, 1))
                    859:                        goto err;
                    860:        } else {
                    861:                char buf[1024];
                    862:                if (!a2i_ASN1_INTEGER(in, serial, buf, sizeof(buf))) {
                    863:                        BIO_printf(bio_err, "unable to load number from %s\n",
                    864:                            serialfile);
                    865:                        goto err;
                    866:                }
                    867:                if (!(bn = ASN1_INTEGER_to_BN(serial, NULL)))
                    868:                        goto err;
                    869:                ASN1_INTEGER_free(serial);
                    870:                serial = NULL;
                    871:                if (!BN_add_word(bn, 1))
                    872:                        goto err;
                    873:                if (!(serial = BN_to_ASN1_INTEGER(bn, NULL)))
                    874:                        goto err;
                    875:        }
                    876:        ret = 1;
                    877: err:
                    878:        if (!ret) {
                    879:                ASN1_INTEGER_free(serial);
                    880:                serial = NULL;
                    881:        }
                    882:        BIO_free_all(in);
                    883:        BN_free(bn);
                    884:        return serial;
                    885: }
                    886:
                    887: static int
                    888: save_ts_serial(const char *serialfile, ASN1_INTEGER * serial)
                    889: {
                    890:        int ret = 0;
                    891:        BIO *out = NULL;
                    892:
                    893:        if (!(out = BIO_new_file(serialfile, "w")))
                    894:                goto err;
                    895:        if (i2a_ASN1_INTEGER(out, serial) <= 0)
                    896:                goto err;
                    897:        if (BIO_puts(out, "\n") <= 0)
                    898:                goto err;
                    899:        ret = 1;
                    900: err:
                    901:        if (!ret)
                    902:                BIO_printf(bio_err, "could not save serial number to %s\n",
                    903:                    serialfile);
                    904:        BIO_free_all(out);
                    905:        return ret;
                    906: }
                    907:
                    908: /*
                    909:  * Verify-related method definitions.
                    910:  */
                    911:
                    912: static int
                    913: verify_command(char *data, char *digest, char *queryfile, char *in,
                    914:     int token_in, char *ca_path, char *ca_file, char *untrusted)
                    915: {
                    916:        BIO *in_bio = NULL;
                    917:        PKCS7 *token = NULL;
                    918:        TS_RESP *response = NULL;
                    919:        TS_VERIFY_CTX *verify_ctx = NULL;
                    920:        int ret = 0;
                    921:
                    922:        /* Decode the token (PKCS7) or response (TS_RESP) files. */
                    923:        if (!(in_bio = BIO_new_file(in, "rb")))
                    924:                goto end;
                    925:        if (token_in) {
                    926:                if (!(token = d2i_PKCS7_bio(in_bio, NULL)))
                    927:                        goto end;
                    928:        } else {
                    929:                if (!(response = d2i_TS_RESP_bio(in_bio, NULL)))
                    930:                        goto end;
                    931:        }
                    932:
                    933:        if (!(verify_ctx = create_verify_ctx(data, digest, queryfile,
                    934:            ca_path, ca_file, untrusted)))
                    935:                goto end;
                    936:
                    937:        /* Checking the token or response against the request. */
                    938:        ret = token_in ?
                    939:            TS_RESP_verify_token(verify_ctx, token) :
                    940:            TS_RESP_verify_response(verify_ctx, response);
                    941:
                    942: end:
                    943:        printf("Verification: ");
                    944:        if (ret)
                    945:                printf("OK\n");
                    946:        else {
                    947:                printf("FAILED\n");
                    948:                /* Print errors, if there are any. */
                    949:                ERR_print_errors(bio_err);
                    950:        }
                    951:
                    952:        /* Clean up. */
                    953:        BIO_free_all(in_bio);
                    954:        PKCS7_free(token);
                    955:        TS_RESP_free(response);
                    956:        TS_VERIFY_CTX_free(verify_ctx);
                    957:        return ret;
                    958: }
                    959:
                    960: static TS_VERIFY_CTX *
                    961: create_verify_ctx(char *data, char *digest, char *queryfile, char *ca_path,
                    962:     char *ca_file, char *untrusted)
                    963: {
                    964:        TS_VERIFY_CTX *ctx = NULL;
                    965:        BIO *input = NULL;
                    966:        TS_REQ *request = NULL;
                    967:        int ret = 0;
                    968:
                    969:        if (data != NULL || digest != NULL) {
                    970:                if (!(ctx = TS_VERIFY_CTX_new()))
                    971:                        goto err;
                    972:                ctx->flags = TS_VFY_VERSION | TS_VFY_SIGNER;
                    973:                if (data != NULL) {
                    974:                        ctx->flags |= TS_VFY_DATA;
                    975:                        if (!(ctx->data = BIO_new_file(data, "rb")))
                    976:                                goto err;
                    977:                } else if (digest != NULL) {
                    978:                        long imprint_len;
                    979:                        ctx->flags |= TS_VFY_IMPRINT;
                    980:                        if (!(ctx->imprint = string_to_hex(digest,
                    981:                                    &imprint_len))) {
                    982:                                BIO_printf(bio_err, "invalid digest string\n");
                    983:                                goto err;
                    984:                        }
                    985:                        ctx->imprint_len = imprint_len;
                    986:                }
                    987:        } else if (queryfile != NULL) {
                    988:                /*
                    989:                 * The request has just to be read, decoded and converted to
                    990:                 * a verify context object.
                    991:                 */
                    992:                if (!(input = BIO_new_file(queryfile, "rb")))
                    993:                        goto err;
                    994:                if (!(request = d2i_TS_REQ_bio(input, NULL)))
                    995:                        goto err;
                    996:                if (!(ctx = TS_REQ_to_TS_VERIFY_CTX(request, NULL)))
                    997:                        goto err;
                    998:        } else
                    999:                return NULL;
                   1000:
                   1001:        /* Add the signature verification flag and arguments. */
                   1002:        ctx->flags |= TS_VFY_SIGNATURE;
                   1003:
                   1004:        /* Initialising the X509_STORE object. */
                   1005:        if (!(ctx->store = create_cert_store(ca_path, ca_file)))
                   1006:                goto err;
                   1007:
                   1008:        /* Loading untrusted certificates. */
                   1009:        if (untrusted && !(ctx->certs = TS_CONF_load_certs(untrusted)))
                   1010:                goto err;
                   1011:
                   1012:        ret = 1;
                   1013: err:
                   1014:        if (!ret) {
                   1015:                TS_VERIFY_CTX_free(ctx);
                   1016:                ctx = NULL;
                   1017:        }
                   1018:        BIO_free_all(input);
                   1019:        TS_REQ_free(request);
                   1020:        return ctx;
                   1021: }
                   1022:
                   1023: static X509_STORE *
                   1024: create_cert_store(char *ca_path, char *ca_file)
                   1025: {
                   1026:        X509_STORE *cert_ctx = NULL;
                   1027:        X509_LOOKUP *lookup = NULL;
                   1028:        int i;
                   1029:
                   1030:        /* Creating the X509_STORE object. */
                   1031:        cert_ctx = X509_STORE_new();
                   1032:
                   1033:        /* Setting the callback for certificate chain verification. */
                   1034:        X509_STORE_set_verify_cb(cert_ctx, verify_cb);
                   1035:
                   1036:        /* Adding a trusted certificate directory source. */
                   1037:        if (ca_path) {
                   1038:                lookup = X509_STORE_add_lookup(cert_ctx,
                   1039:                    X509_LOOKUP_hash_dir());
                   1040:                if (lookup == NULL) {
                   1041:                        BIO_printf(bio_err, "memory allocation failure\n");
                   1042:                        goto err;
                   1043:                }
                   1044:                i = X509_LOOKUP_add_dir(lookup, ca_path, X509_FILETYPE_PEM);
                   1045:                if (!i) {
                   1046:                        BIO_printf(bio_err, "Error loading directory %s\n",
                   1047:                            ca_path);
                   1048:                        goto err;
                   1049:                }
                   1050:        }
                   1051:        /* Adding a trusted certificate file source. */
                   1052:        if (ca_file) {
                   1053:                lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
                   1054:                if (lookup == NULL) {
                   1055:                        BIO_printf(bio_err, "memory allocation failure\n");
                   1056:                        goto err;
                   1057:                }
                   1058:                i = X509_LOOKUP_load_file(lookup, ca_file, X509_FILETYPE_PEM);
                   1059:                if (!i) {
                   1060:                        BIO_printf(bio_err, "Error loading file %s\n", ca_file);
                   1061:                        goto err;
                   1062:                }
                   1063:        }
                   1064:        return cert_ctx;
                   1065: err:
                   1066:        X509_STORE_free(cert_ctx);
                   1067:        return NULL;
                   1068: }
                   1069:
                   1070: static int
                   1071: verify_cb(int ok, X509_STORE_CTX * ctx)
                   1072: {
                   1073:        /*
                   1074:        char buf[256];
                   1075:
                   1076:        if (!ok)
                   1077:                {
                   1078:                X509_NAME_oneline(X509_get_subject_name(ctx->current_cert),
                   1079:                                  buf, sizeof(buf));
                   1080:                printf("%s\n", buf);
                   1081:                printf("error %d at %d depth lookup: %s\n",
                   1082:                       ctx->error, ctx->error_depth,
                   1083:                        X509_verify_cert_error_string(ctx->error));
                   1084:                }
                   1085:        */
                   1086:
                   1087:        return ok;
                   1088: }