RSA BSAFE Micro Edition Suite

Streamlined security for mobile and embedded devices

Search  Print

cm_strm.c

/* $Id: cm_strm.c,v 1.35 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_strm.c
 * This sample demonstrates operations with PKCS #7 signed data messages using
 * the streaming interface. 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 we create a Cryptographic Message
 * Object (R_CM) 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 supplied 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_strm -in signed.data -print_data
 *
 * Verify the signature - certificate not in PKCS7 message (supply signer
 * certificate):
 *   cm_strm -in signed.data -certs signer.cert -print_data
 *
 * Verify the signature and signer certificate (verify cert chain to
 * Certification Authority (CA) certificate):
 *   cm_strm -in signed.data -certs issuer.cert -print_data -vfy_opts ALL
 *
 * where: signed.data = The output file where PKCS #7 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

/* Usage lines for program */
static char *cm_strm_usage[] =
{
    "usage: cm_strm [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 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 option      - The certificate verification options\n",
    "                         - one of NONE, DEF, ALL, NO_COMPLETE\n",
    " -print_data           - Print the data of the cryptographic message\n",
    " -print_certs          - Print the certificates 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 = NULL;       /* The verification context */
    R_CERT_CTX *cert_ctx = NULL;        /* The certificate context */
    R_CERT_STORE_CTX *store_ctx = NULL; /* The certificate store */
    char *certfile;                     /* A list of certificate file names */
    char *certtype;                     /* The type of certificates */
    char *certform;                     /* The format of certificates */
    char *vfy_opts;                     /* The verification options */
    int no_ci;
    int print_data;
    int print_certs;
    char *vfy_time = NULL;

    /* Set the defaults */
    certfile    = NULL;
    certtype    = "X509";
    certform    = "BIN";
    vfy_opts    = NULL;
    no_ci       = 0;
    print_data  = 0;
    print_certs = 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 (Strcmp(*argv, "-certs") == 0)
        {
            if (--argc < 1)
            {
                goto bad;
            }
            certfile = *(++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 (Strcmp(*argv, "-vfy_opts") == 0)
        {
            if (--argc < 1)
            {
                goto bad;
            }
            vfy_opts = *(++argv);
        }
        else if (Strcmp(*argv, "-print_data") == 0)
        {
            print_data = 1;
        }
        else if (Strcmp(*argv, "-print_certs") == 0)
        {
            print_certs = 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_strm_usage; (*pp != NULL); pp++)
        {
            BIO_printf(bio_err, *pp);
        }

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


    /*
     * 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 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.
     *
     * In this sample we are assuming the message has type SIGNED_DATA so
     * we do not need an additional call to BIO_set_content_type().
     */
    if (no_ci)
    {
        BIO_set_unwrapped(bio_cm);
    }

    /* Create a verification context and set the verification options */
    ret = set_verification(bio_err, lib_ctx, vfy_opts, vfy_time, &vfy_ctx);
    if (ret != R_ERROR_NONE)
    {
        goto done;
    }

    /*
     * The BIO is now owned by the verification context and does not need to be
     * explicitly freed. Set the verification context to use when verifying the
     * signed data message.
     */
    ret = BIO_set_verification(bio_cm, vfy_ctx);
    if (ret != 1)
    {
        BIO_printf(bio_err, "Failed to set verification against BIO filter\n");
        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).
     */
    if ((ret = load_certificates(bio_err, lib_ctx, certfile, certtype, certform,
        &cert_ctx, &store_ctx)) != R_ERROR_NONE)
    {
        goto done;
    }

    /* Set the store to use when verifying the signed data message */
    if (store_ctx != NULL)
    {
        /*
         * The store context is now owned by the BIO and does not need to be
         * explicitly freed. Load the certificates from the file into the
         * certificate store.
         */
        ret = BIO_set_store(bio_cm, store_ctx);
        if (ret != 1)
        {
            BIO_printf(bio_err,
                "Failed to set certificate store against BIO filter\n");
            ret = R_ERROR_FAILED;
            goto done;
        }

        ret = R_ERROR_NONE;
    }

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

    /*
     * Read 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;
            goto done;
        }

        /* 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);
            }
        }
    }
        /* Print the certificates in text form */
    if (print_certs)
    {
        ret = print_cert_info(bio_err, cm, lib_ctx, cert_ctx);
    }   

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 (vfy_ctx != NULL)
    {
        R_VERIFY_CTX_free(vfy_ctx);
    }

    if (store_ctx != NULL)
    {
        R_CERT_STORE_CTX_free(store_ctx);
    }

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

    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));
}


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