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

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