RSA BSAFE Micro Edition Suite

Streamlined security for mobile and embedded devices

Search  Print

cm_vfy_strm_cb.c

/* $Id: cm_vfy_strm_cb.c,v 1.21 2005/08/08 05:33:31 jlevander Exp $ */
/*
 * Copyright (C) 1998-2003 RSA Security Inc.
 *
 * This file shall only be used to demonstrate how to interface to an
 * RSA Security Inc. licensed development product.
 *
 * You have a royalty-free right to use, reproduce and distribute this
 * demonstration file, provided that you agree that RSA Security Inc.
 * has no warranty, implied or otherwise, or liability for this
 * demonstration file (including any modified version).  This software
 * is provided "as is" without warranties or representations of any
 * kind. RSA Security disclaims all conditions and warranties, statutory
 * and otherwise, both express and implied, with respect to the software,
 * its quality and performance, including but not limited to, all
 * implied warranties of merchantability, fitness for a particular
 * purpose, title and noninfringement of third party rights. Without
 * limiting the foregoing, RSA Security does not warrant that the
 * software is error-free or that errors in the product will be
 * corrected. You agree that RSA Security shall not be liable for any
 * direct, indirect, incidental, special, consequential, punitive or
 * other damages whatsoever resulting from your use of this software
 * or any modified version.
 *
 *
 */

/*
 * @file cm_vfy_strm_cb.c
 * This sample demonstrates operations with PKCS #7 signed data messages using
 * the streaming interface and a callback to retrieve the certificate for a
 * signer.
 * The operations include verifying the signed data, optionally verifying the
 * signer's certificate, and printing the data and PKCS #7 message components.
 *
 * Streaming is achieved by creating a stack of BIOs. Each BIO in the
 * stack performs a specific task. In this sample a cryptographic message
 * object (R_CM) is created, and in turn a cryptographic message BIO. This BIO
 * is pushed onto the input stream (input BIO) to create a BIO stack with the
 * required functionality.
 *
 * In its simplest form this sample verifies the signature. Optional
 * switches can be applied to print the data and signer information from the
 * signed data message. Verification of the signer certificate can also be
 * executed.
 *
 * For information demonstrating how to generate PKCS #7 signed messages,
 * see cm_sign.c.
 *
 * For example, to:
 *
 * Verify the signature and print the data:
 *   cm_vfy_strm_cb -in signed.data -print_data
 *
 * Verify the signature - certificate not in PKCS7 message (supply signer cert)
 *   cm_vfy_strm_cb -in signed.data -certs signer.cert -print_data
 *
 * Verify the signature and signer certificate (verify cert chain to CA cert)
 *   cm_vfy_strm_cb -in signed.data -certs issuer.cert -print_data -vfy_opts ALL
 *
 * where: signed.data = The output file where pkcs7 data is written.
 *        signer.cert = The signer's certificate (used when the signed data
 *                      was created).
 *        issuer.cert = The trusted issuer of the signer's certificate.
 *
 */

#include "r_prod.h"
#include "cm_com.h"

#ifndef NO_STREAM
/* The length of the buffer into which to read */
#define BUF_LEN        1024
/* The number of stores the user can create */
#define NUM_STORES     5


typedef struct op_cb_arg_st
{
    BIO *bio_err;
    R_CERT_CTX *cert_ctx;
    R_CERT_STORE_CTX **store_ctx;
    R_VERIFY_CTX **vfy_ctx;
    int def;
} OP_CB_ARG;

int bio_cm_op_cb(BIO *bio, R_CM *cm, R_CM_TYPE type, void *cb_arg);


/* Usage lines for program */
static char *cm_vfy_strm_cb_usage[] =
{
    "usage: cm_vfy_strm_cb [options]\n",
    "where options are:\n",
    " -in arg               - The file containing the cryptographic message\n",
    " -out arg              - The output file\n",
    " -no_ci                - The cryptographic message has no content\n",
    "                         information\n",
    " -certs[n] list        - A list of certificates (colon separated)\n",
    " -certtype encoding    - Encoding of the certificates - only X509\n",
    "                         supported (default)\n",
#ifdef NO_PEM
    " -certform format      - The format of the certificates (BIN only)\n",
#else
    " -certform format      - The format of the certificates\n",
    "                         - one of BIN (default), PEM\n",
#endif /* NO_PEM */
    " -vfy_opts[n] option   - The certificate verification options\n",
    "                         - one of NONE, DEF, ALL, NO_COMPLETE\n",
    " -default_store num    - The number of the store to use when no signing\n",
    "                         certficate was found in a store\n",
    " -print_data           - Print the data of the cryptographic message\n",
    " -time YYYYMMDDHHMMSSZ - Set the verification time rather than use the\n",
    "                         system time\n",
#ifdef NO_SOFTWARE_CRYPTO
    " -no_fips140         - Use non FIPS140 crypto implementations\n",
#endif /* NO_SOFTWARE_CRYPTO */
    NULL
};
#endif /* !NO_STREAM */

/*
 * Main sample program entry point
 *
 * Decodes a PKCS #7 signed data message and attempts to verify the data.
 *
 * @param argc  [In]  The number of arguments typed on the command line.
 * @param argv  [In]  The array of individual arguments from the command line.
 * @returns  R_ERROR_NONE indicates success.<br>
 *           See @ref R_ERROR_IDS for valid values.
 */
int main(int argc, char **argv)
{
    int ret = R_ERROR_NONE;             /* The return value */
#ifndef NO_STREAM
    BIO *bio_in = NULL;                 /* The input stream */
    BIO *bio_out = NULL;                /* The output stream */
    BIO *bio_err = NULL;                /* The error stream */
    BIO *bio_cm = NULL;                 /* The cryptographic message BIO */
    unsigned char *buf = NULL;          /* The buffer into which to read */
    int len = 0;                        /* The length of the buffer */
    R_CM_CTX *cm_ctx = NULL;            /* The cryptographic message context */
    R_CM *cm = NULL;                    /* The cryptographic message object */
    char *in_file = NULL;               /* The name of the file to read */
    char *out_file = NULL;              /* The name of the file to write to */
    int bad_op = 0;                     /* A bad command line option */
    R_RES_LIST *res_list;               /* The resource list */
    R_LIB_CTX *lib_ctx = NULL;          /* The library context */
    R_VERIFY_CTX *vfy_ctx[NUM_STORES];  /* The verification context */
    R_CERT_CTX *cert_ctx = NULL;        /* The certificate context */
    R_CERT_STORE_CTX *store_ctx[NUM_STORES];/* The certificate store */
    char *certfile[NUM_STORES];         /* A list of certificate file names */
    char *certtype;                     /* The type of certificates */
    char *certform;                     /* The format of certificates */
    char *vfy_opts[NUM_STORES];         /* The verification options */
    int default_store;
    int no_ci;
    int print_data;
    BIO_CM_OP_CB cb;
    OP_CB_ARG cb_arg;
    int i;
    char *vfy_time = NULL;


    /* Initialise */
    Memset(vfy_ctx, 0, sizeof(vfy_ctx));
    Memset(store_ctx, 0, sizeof(store_ctx));
    Memset(certfile, 0, sizeof(certfile));
    Memset(vfy_opts, 0, sizeof(certfile));

    /* Set the defaults */
    certtype      = "X509";
    certform      = "BIN";
    no_ci         = 0;
    print_data    = 0;
    default_store = 0;

    res_list = PRODUCT_DEFAULT_RESOURCE_LIST();

    /*
     * Create a BIO to stderr.
     * BIOs are the Basic Input/Output mechanism provided by RSA and are
     * recommended for all input and output from applications.
     */
    if ((bio_err = BIO_new_fp(stderr, BIO_NOCLOSE)) == NULL)
    {
        goto done;
    }

    /*
     * Parse the command line parameters.
     */
    /* Skip over program name */
    argc--;
    argv++;

    /* Process all command line arguments */
    while (argc >= 1)
    {
        /* The file name to read */
        if (Strcmp(*argv, "-in") == 0)
        {
            if ((--argc < 1) || (Strncmp(*(++argv), "-", 1) == 0))
            {
                BIO_printf(bio_err, "Missing IN filename\n");
                goto bad;
            }
            in_file=*argv;
        }
        /* The file name to write */
        else if (Strcmp(*argv, "-out") == 0)
        {
            if ((--argc < 1) || (Strncmp(*(++argv), "-", 1) == 0))
            {
                BIO_printf(bio_err, "Missing OUT file name\n");
                goto bad;
            }
            out_file=*argv;
        }
        /* Indicates the cryptographic message has no content information */
        else if (Strcmp(*argv, "-no_ci") == 0)
        {
            no_ci = 1;
        }
        /* The trusted certificates */
        else if (Strncmp(*argv, "-certs", 6) == 0)
        {
            int cert_cnt = atoi(&((*argv)[6]));

            if ((--argc < 1) || (cert_cnt >= NUM_STORES) || (cert_cnt <= 0))
            {
                goto bad;
            }
            certfile[cert_cnt-1] = *(++argv);
        }
        /* The type of trusted certificates */
        else if (Strcmp(*argv, "-certtype") == 0)
        {
            if (--argc < 1)
            {
                goto bad;
            }
            certtype = *(++argv);
        }
        /* The format of trusted certificates */
        else if (Strcmp(*argv, "-certform") == 0)
        {
            if (--argc < 1)
            {
                goto bad;
            }
            certform = *(++argv);
        }
        else if (Strncmp(*argv, "-vfy_opts", 9) == 0)
        {
            int vfy_cnt = atoi(&((*argv)[9]));

            if ((--argc < 1) || (vfy_cnt >= NUM_STORES) || (vfy_cnt <= 0))
            {
                goto bad;
            }
            vfy_opts[vfy_cnt-1] = *(++argv);
        }
        else if (Strcmp(*argv, "-default_store") == 0)
        {
            if (--argc < 1)
            {
                goto bad;
            }
            default_store = atoi(*(++argv));
            if ((default_store <= 0) || (default_store > NUM_STORES))
            {
                BIO_printf(bio_err, "Invalid store number: %d\n",
                    default_store);
            }
            default_store--;
        }
        else if (Strcmp(*argv, "-print_data") == 0)
        {
            print_data = 1;
        }
        else if (Strcmp(*argv, "-time") == 0)
        {
            if (--argc < 1)
            {
                goto bad;
            }
            vfy_time = *(++argv);
        }
#ifdef NO_SOFTWARE_CRYPTO
        else if (Strcmp(*argv, "-no_fips140") == 0)
        {
            res_list = PRODUCT_NON_FIPS_140_MODE_RESOURCE_LIST();
        }
#endif /* NO_SOFTWARE_CRYPTO */
        else
        {
            BIO_printf(bio_err, "Unknown option: %s\n", *argv);
            bad_op=1;
            break;
        }

        /* Move onto the next command line argument */
        argc--;
        argv++;
    }

    /* Write out usage if there was an error */
    if (bad_op)
    {
        char **pp;  /* A pointer to a line of usage */

bad: ;
        /* Write out all lines of usage */
        for (pp = cm_vfy_strm_cb_usage; (*pp != NULL); pp++)
        {
            BIO_printf(bio_err, *pp);
        }

        /* Return failure */
        ret = R_ERROR_FAILED;
        goto done;
    }


    /*
     * Create the library context.
     * Retrieve the default resource list and create a library context to
     * provide access to all configurable aspects of the library.
     */
    if ((ret = PRODUCT_LIBRARY_NEW(res_list, R_RES_FLAG_DEF, &lib_ctx)) !=
        R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Library new failure\n");
        goto done;
    }

    /*
     * Open the input and output streams, and allocate a buffer for
     * input.
     */
    /* Open the input stream */
    if (in_file == NULL)
    {
        BIO_printf(bio_err, "No input file specified\n", in_file);
        goto done;
    }
    else
    {
        /* Open the file name for reading */
        if ((bio_in = BIO_new_file(in_file, "rb")) == NULL)
        {
            BIO_printf(bio_err, "Cannot open file for reading: %s\n", in_file);
            goto done;
        }
    }

    /* Open the output stream */
    if (out_file != NULL)
    {
        /* Open the file specified on the command line */
        if ((bio_out = BIO_new_file(out_file, "wb")) == NULL)
        {
            BIO_printf(bio_err, "Cannot open file for writing: %s\n", out_file);
        }
    }
    /* Allocate memory for the buffer into which to read */
    if ((buf = (unsigned char *)Malloc(BUF_LEN)) == NULL)
    {
        BIO_printf(bio_err, "Failed to allocate memory (%d Bytes)\n", BUF_LEN);
        goto done;
    }
    Memset(buf, 0, BUF_LEN);

    /*
     * Create a new cryptographic message context.
     */
    ret = R_CM_CTX_new(lib_ctx, R_RES_FLAG_DEF, R_CM_TYPE_SIGNED_DATA,
                       &cm_ctx);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to create cryptographic message context\n");
        goto done;
    }

    /*
     * Create a new cryptographic message object with which to verify.
     */
    ret = R_CM_new(cm_ctx, R_CM_TYPE_SIGNED_DATA, &cm);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err,
            "Failed to create a signed data cryptographic message\n");
        goto done;
    }

    /*
     * Assign the cryptographic message object to the BIO.
     * For streaming, a stack of BIOs is formed and the data streamed through
     * each BIO to perform a specific part of the signing.
     */
    ret = R_CM_to_BIO(cm, R_RES_FLAG_DEF, &bio_cm);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err,
            "Failed to convert a message to the streaming interface\n");
        goto done;
    }

    /*
     * The no_ci option notifies the cryptographic message BIO that the message
     * to verify has no outer ContentInfo. It is supplied so that nested
     * cryptographic messages can be verified, since the nested messages must
     * have the ContentInfo removed.
     *
     * This sample assumes the message has type SIGNED_DATA so an additional
     * call to BIO_set_content_type() is not required.
     */
    if (no_ci)
    {
        BIO_set_unwrapped(bio_cm);
    }

    /*
     * Set up the verification-related functionality.
     * This step creates all the verification contexts.
     */
    for (i = 0; i < NUM_STORES; i++)
    {
        if (certfile[i] != NULL)
        {
            ret = set_verification(bio_err, lib_ctx, vfy_opts[i], vfy_time,
                &(vfy_ctx[i]));
            if (ret != R_ERROR_NONE)
            {
                goto done;
            }
        }
    }

    /*
     * Set up the certificate related functionality.
     * If any certificates are specified then:
     *      - Create a certificate context.
     *      - Create a store context.
     *      - Create a store object.
     * For each certificate:
     *      - Read the certificate from file.
     *      - Set the certificate against the store object.
     *      - Set the certificate trust level.
     *      - Add the certificate to the store (using the store object).
     */
    for (i = 0; i < NUM_STORES; i++)
    {
        if (certfile[i] == NULL)
        {
            continue;
        }
        if ((ret = load_certificates(bio_err, lib_ctx, certfile[i], certtype,
            certform, &cert_ctx, &(store_ctx[i]))) != R_ERROR_NONE)
        {
            /* Throw away any certificate stores that have been created. */
            if (store_ctx[i] != NULL)
            {
                R_CERT_STORE_CTX_free(store_ctx[i]);
                store_ctx[i] = NULL;
            }
            goto done;
        }
    }

    cb.cb = bio_cm_op_cb;
    cb_arg.bio_err = bio_err;
    cb_arg.cert_ctx = cert_ctx;
    cb_arg.store_ctx = store_ctx;
    cb_arg.vfy_ctx = vfy_ctx;
    cb_arg.def = default_store;
    cb.cb_arg = (void *)&cb_arg;

    if (BIO_ctrl(bio_cm, BIO_C_SET_OP_CB, 0, (char *)&cb) == 0)
    {
        ret = R_ERROR_FAILED;
        BIO_printf(bio_err, "Failed to set operation callback.\n");
        goto done;
    }

    /*
     * Push the cryptographic message filter on top of the input
     * stream.
     */
    BIO_push(bio_cm, bio_in);

    /*
     * SRead all application data from the input stream.
     * Note that when using the streaming interface only one signer can
     * be verified at a time.
     */
    while ((len = BIO_read(bio_cm, (char *)buf, BUF_LEN)) != 0)
    {
        /* Stop reading data if an unrecoverable error occurs*/
        if ((len < -1) || ((len == -1) && (!BIO_should_retry(bio_cm))))
        {
            BIO_printf(bio_err, "Failure while reading data\n");
            ret = R_ERROR_IO;
            break;
        }

        /* Dump out any Bytes that are returned in the buffer */
        if (len > 0)
        {
            if (bio_out != NULL)
            {
                BIO_write(bio_out, (char *)buf, len);
            }

            if (print_data)
            {
                BIO_dump(bio_err, buf, len);
            }
        }
    }

done:
    /*
     * Clean up.
     * Report errors if there is an output stream using both the error and the
     * string representation.
     * Destroy the dynamically allocated objects and return an exit code.
     */
    if (ret != R_ERROR_NONE)
    {
        /* If there is an error stream to write to, return the error
         * code */
        if (bio_err != NULL)
        {
            BIO_printf(bio_err, "ERROR: (%d) %s\n", ret,
                R_LIB_CTX_get_error_string(lib_ctx, R_RES_MOD_ID_LIBRARY, ret));
        }
    }

    /* Free the allocated data */
    if (buf != NULL)
    {
        Free(buf);
    }

    if (bio_cm != NULL)
    {
        BIO_free(bio_cm);
    }

    if (cm != NULL)
    {
        R_CM_free(cm);
    }

    for (i = 0; i < NUM_STORES; i++)
    {
        if (store_ctx[i] != NULL)
        {
            R_CERT_STORE_CTX_free(store_ctx[i]);
        }
        if (vfy_ctx[i] != NULL)
        {
            R_VERIFY_CTX_free(vfy_ctx[i]);
        }
    }

    if (cert_ctx != NULL)
    {
        R_CERT_CTX_free(cert_ctx);
    }

    if (cm_ctx != NULL)
    {
        R_CM_CTX_free(cm_ctx);
    }

    if (bio_in != NULL)
    {
        BIO_free(bio_in);
    }

    if (bio_out != NULL)
    {
        BIO_free(bio_out);
    }

    if (lib_ctx != NULL)
    {
        PRODUCT_LIBRARY_FREE(lib_ctx);
    }

    if (bio_err != NULL)
    {
        BIO_free(bio_err);
    }

#endif /* !NO_STREAM */

    return(R_ERROR_EXIT_CODE(ret));
}

/*
 * Attempts to find a certificate that matches the details in a signer.
 *
 * @param  bio     [In]  The #BIO filter.
 * @param  cm      [In]  The cryptographic message.
 * @param  type    [In]  The type of cryptographic message.
 * @param  cb_arg  [In]  The callback argument from the application.
 *
 * @return   #R_ERROR_NONE indicates success.<br>
 *           See @ref R_ERROR_IDS for valid values.
 */
int bio_cm_op_cb(BIO *bio, R_CM *cm, R_CM_TYPE type, void *cb_arg)
{
    int ret = R_ERROR_NONE;
    int err;
    OP_CB_ARG *arg = (OP_CB_ARG *)cb_arg;
    BIO *bio_err;
    R_CERT_CTX *cert_ctx;
    R_CERT_STORE_CTX **store_ctx;
    R_CERT_STORE *store[NUM_STORES];
    R_VERIFY_CTX **vfy_ctx;
    R_CERT_NAME *name = NULL;
    R_INDEXED_INFO info;
    R_ITEM serial;
    int default_store;
    int count;
    int i;
    int j = 0;

    /* Ensure there is a callback argument. */
    if (arg == NULL)
    {
        ret = R_ERROR_NULL_ARG;
        goto done;
    }

    /* Obtain a reference to the fields of the callback argument. */
    bio_err = arg->bio_err;
    cert_ctx = arg->cert_ctx;
    store_ctx = arg->store_ctx;
    vfy_ctx = arg->vfy_ctx;
    default_store = arg->def;

    /* Initialize the array of store objects. One store object is required to
     * look into each of the stores.
     */
    Memset(store, 0, sizeof(store));

    /* Retrieve the count of signers in the cryptographic message. */
    ret = R_CM_get_signer_count(cm, &count);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to get signer count\n");
        goto done;
    }

    if (count == 0)
    {
        BIO_printf(bio_err, "No signers!\n");
        ret = R_ERROR_FAILED;
        goto done;
    }

    /* Look up the details of each of the signers until a match is found or
     * there are no more signers.
     */
    for (i = 0; i < count; i++)
    {
        /* Retrieve the certificate issuer and serial number from the signer. */
        info.index = i;
        ret = R_CM_get_info(cm, R_CM_INFO_SIGNER_ISSUER_NAME, &info);
        if (ret != R_ERROR_NONE)
        {
            goto done;
        }

        ret = R_CERT_NAME_from_binary(cert_ctx, R_FLAG_SHARE_DATA, info.len,
            (const unsigned char *)info.data, NULL, &name);
        if (ret != R_ERROR_NONE)
        {
            goto done;
        }

        info.index = i;
        ret = R_CM_get_info(cm, R_CM_INFO_SIGNER_SERIAL_NUMBER, &info);
        if (ret != R_ERROR_NONE)
        {
            goto done;
        }

        serial.data = (unsigned char *)info.data;
        serial.len = info.len;

        /* Look for the certificate in the stores. */
        for (j = 0; j < NUM_STORES; j++)
        {
            /* Skip the blank stores. */
            if (store_ctx[j] == NULL)
            {
                continue;
            }
            /* Create a store object for the store if one does not exist. */
            if (store[j] == NULL)
            {
                ret = R_CERT_STORE_new(store_ctx[j], &(store[j]));
                if (ret != R_ERROR_NONE)
                {
                    BIO_printf(bio_err, "Failed to create certificate store\n");
                    goto done;
                }
            }

            /* Look for the certificate in the store. */
            ret = R_CERT_STORE_find_entry_by_issuer_and_serial(store[j], name,
                &serial, R_CERT_STORE_ANY_CERTIFICATE);
            if (ret == R_ERROR_NONE)
            {
                break;
            }
            if (ret != R_ERROR_NOT_FOUND)
            {
                goto done;
            }
        }

        if (name != NULL)
        {
            R_CERT_NAME_free(name);
            name = NULL;
        }

        /* Stop looking if the certificate was found for this signer. */
        if (ret == R_ERROR_NONE)
        {
            break;
        }
    }

    /* The return value will indicate not found if no signer's certificate was
     * found in any of the stores.
     */
    if (ret == R_ERROR_NOT_FOUND)
    {
        BIO_printf(bio_err, "Failed to find a store with signing certificates"
            " - using default [%d]\n", default_store + 1);
        j = default_store;
        ret = R_ERROR_NONE;
    }
    /* Report which store the certificate was found in. */
    else
    {
        BIO_printf(bio_err, "Found store to use [%d]\n", j + 1);
    }

    /* Set the store against the cryptographic message BIO filter. */
    err = BIO_set_store(bio, store_ctx[j]);
    if (err != 1)
    {
        BIO_printf(bio_err,
            "Failed to set certificate store against BIO filter\n");
        ret = R_ERROR_FAILED;
        goto done;
    }

    /* Set the verification mechanism associated with this store against the
     * cryptographic message BIO filter.
     */
    err = BIO_set_verification(bio, vfy_ctx[j]);
    if (err != 1)
    {
        ret = R_ERROR_FAILED;
        BIO_printf(bio_err, "Failed to set verification against BIO filter\n");
        goto done;
    }

done:
    if (name != NULL)
    {
        R_CERT_NAME_free(name);
    }
    for (i = 0; i < NUM_STORES; i++)
    {
        if (store[i] != NULL)
        {
            R_CERT_STORE_free(store[i]);
        }
    }

    return(ret);
}


Copyright (c) 1999-2005 RSA Security Inc. All rights reserved. 072-001001-2100-001-000 - 2.1