RSA BSAFE Micro Edition Suite

Streamlined security for mobile and embedded devices

Search  Print

cm_dgst.c

/* $Id: cm_dgst.c,v 1.9 2005/08/08 05:33:30 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_dgst.c
 * This sample demonstrates operations with PKCS #7 signed data messages.
 * The operations include verifying the signed data, optionally verifying the
 * signer's certificate, and printing the data and PKCS #7 message components.
 * The data is detached from the PKCS #7 signed data message and is
 * streamed. In its simplest form this sample will verify the signature.
 *
 * For information detailing generating PKCS #7 signed messages,
 * see cm_sign.c.
 *
 * For example, to:
 *
 * Verify the signature and print the data:
 *   cm_dgst -cm_msg signed.data -print_data
 *
 * Verify the signature - certificate not in PKCS7 message (supply signer cert)
 *   cm_dgst -cm_msg signed.data -certs signer.cert -print_signers -print_data
 *
 * Verify the signature and signer certificate (verify cert chain to CA cert)
 *   cm_dgst -cm_msg signed.data -certs issuer.cert -print_data -vfy_opts ALL
 *
 * where: signed.data = 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"

/* Usage help message. */
static char *cm_usage[] =
{
    "usage: cm [options]\n",
    "where options are:\n",
    " -cm_msg file          - The file containing the cryptographic message\n",
    " -data_msg file        - The file containing the data if it's not part\n",
    "                         of the cryptographic message first\n",
    "                         followed by the detached data\n",
    " -wrap                 - The detached message is wrapped\n",
    "                         structure and should be unwrapped before use\n",
    " -certs list           - A list of certificates (colon separated)\n",
    " -certtype encoding    - Encoding the certificates - only X509\n",
    "                         (default) supported\n",
#ifdef NO_PEM
    " -certform format      - The format of the certificates (BIN only)\n",
#else
    " -certform format      - The format of the certificates - one of BIN "
    "(default),\n",
    "                         PEM\n",
#endif /* NO_PEM */
    " -vfy_opts option      - The certificate verification options",
    " - one of NONE,\n",
    "                         DEF, ALL, NO_COMPLETE\n",
    " -print_signer         - Print the certificate information for each of\n",
    "                         the signers in the cryptographic message\n",
    " -print_data           - Print the signed 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 */
    " -eg                   - Print some example usages.\n",
    NULL
};

static char *cm_example_usage[] =
{
    "Verify the signature and print the data:\n",
    "cm_dgst -cm_msg signed.data -print_data\n",
    "\n",
    "Verify the signature - certificate not in PKCS7 message",
    " (supply signer cert)\n",
    "cm_dgst -cm_msg signed.data -certs signer.cert -print_signers -print_data\n",
    "\n",
    "Verify the signature and signer certificate",
    " (verify cert chain to CA cert)\n",
    "cm_dgst -cm_msg signed.data -certs issuer.cert -print_data -vfy_opts ALL\n",
    "\n",
    "  where: signed.data = output file where pkcs7 data is written\n",
    "         signer.cert = The signer's certificate",
    " (used when the signed data\n",
    "                       was created).\n",
    "         issuer.cert = The trusted issuer of the signer's certificate.\n",
    "\n",
    NULL
};

/* The length of the buffer into which to read */
#define BUF_LEN        1024
/* max number of different digests  */
#define MAX_NUM_DIGESTS 10


/*
 * Main sample program entry point
 *
 * @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.
 *           See @ref R_ERROR_IDS for valid values.
 */
int main(int argc, char **argv)
{
    R_RES_LIST       *res_list;
    R_LIB_CTX        *lib_ctx   = NULL;
    R_CM_CTX         *ctx       = NULL;
    R_CM             *obj       = NULL;
    R_CM             *data_obj  = NULL;
    R_CERT_CTX       *cert_ctx  = NULL;
    R_CERT_STORE_CTX *store_ctx = NULL;
    R_VERIFY_CTX     *vfy_ctx   = NULL;
    BIO              *bio_out   = NULL;
    BIO              *bio_in    = NULL;
    BIO              *bio_tos    = NULL;
    BIO              *bio_digest = NULL;
    R_INDEXED_INFO    digest_ids = {0,0,0,R_CR_ID_SHA1};
    char             *cm_file;
    char             *datafile;
    char             *certfile;
    char             *certtype;
    char             *certform;
    char             *options;
    unsigned char    *buf = NULL;
    unsigned char    *cm_data   = NULL;
    unsigned int      num_used;
    unsigned int      cm_len;
    int               ret       = R_ERROR_NONE;
    int               is_verified;
    R_CM_TYPE         data_type;
    int               wrap;
    int               print_sig;
    int               print_data;
    int               num_of_signers;
    int               num_of_digests=0;
    char             *vfy_time = NULL;
    int               len, data_len;
    R_INDEXED_INFO    digest_data = {0,0,0,0};
    int               digest_id[MAX_NUM_DIGESTS];
    BIO              *digest_bios[MAX_NUM_DIGESTS];
    int               digest_num;

    /* Set the defaults */
    cm_file    = NULL;
    datafile   = NULL;
    certfile   = NULL;
    certtype   = "X509";
    certform   = "BIN";
    options    = NULL;
    print_sig  = 0;
    print_data = 0;
    wrap       = 0;

    res_list = PRODUCT_DEFAULT_RESOURCE_LIST();

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

    /* Skip the program name */
    argc--;
    argv++;

    /* Parse the command line parameters */
    while (argc >= 1)
    {
        if (Strcmp(*argv, "-cm_msg") == 0)
        {
            if (--argc < 1)
            {
                goto bad;
            }
            cm_file = *(++argv);
        }
        else if (Strcmp(*argv, "-data_msg") == 0)
        {
            if (--argc < 1)
            {
                goto bad;
            }
            datafile = *(++argv);
        }
        else if (Strcmp(*argv, "-wrap") == 0)
        {
            wrap = 1;
        }
        else if (Strcmp(*argv, "-certs") == 0)
        {
            if (--argc < 1)
            {
                goto bad;
            }
            certfile = *(++argv);
        }
        else if (Strcmp(*argv, "-certtype") == 0)
        {
            if (--argc < 1)
            {
                goto bad;
            }
            certtype = *(++argv);
        }
        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;
            }
            options = *(++argv);
        }
        else if (Strcmp(*argv, "-print_signer") == 0)
        {
            print_sig = 1;
        }
        else if (Strcmp(*argv, "-print_data") == 0)
        {
            print_data = 1;
        }
        else if (Strcmp(*argv,"-eg") == 0)
        {
            char **egp;
            for (egp = cm_example_usage; (*egp) != NULL; egp++)
            {
                BIO_printf(bio_out, *egp);
            }
            goto end;
        }
        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_out, "Unknown option %s\n", *argv);
            goto bad;
        }
        argc--;
        argv++;
    }

    /* Simple checks first */
    if (cm_file == NULL)
    {
        BIO_printf(bio_out, "Input file required\n");
        goto bad;
    }

    /* Display the help menu if an invalid command line option was entered */
    if (0)
    {
        char **pp;
bad:
        for (pp = cm_usage; (*pp != NULL); pp++)
        {
            BIO_printf(bio_out, *pp);
        }
        goto end;
    }

    /*
     * 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_out, "Library new failure\n");
        goto end;
    }

    /*
     * Set up the certificate related functionality. If any certificates are
     * specified:
     *    - 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_out, lib_ctx, certfile, certtype, certform,
        &cert_ctx, &store_ctx)) != R_ERROR_NONE)
    {
        goto end;
    }

    /*
     * Set up the verification related functionality. This step creates a
     * verification context and sets the verification options.
     */
    if ((ret = set_verification(bio_out, lib_ctx, options, vfy_time, &vfy_ctx))
        != R_ERROR_NONE)
    {
        goto end;
    }

    /* Create a new cryptographic message context */
    if ((ret = R_CM_CTX_new(lib_ctx, R_RES_FLAG_DEF, R_CM_TYPE_DEFAULT,
        &ctx)) != R_ERROR_NONE)
    {
        BIO_printf(bio_out, "R_CM_CTX_new failure\n");
        goto end;
    }

    /*
     * Read the data from cryptographic message file into the buffer.
     * The cryptographic message is in binary form and simply copied to a
     * buffer pointed to by cm_data.
     */
    if ((ret = data_from_file(bio_out, cm_file, &cm_data, &cm_len)) !=
        R_ERROR_NONE)
    {
        goto end;
    }

    /*
     * Load the cryptographic message buffer into a cryptographic
     * message object.
     */
    if ((ret = R_CM_from_binary(ctx, R_FLAG_SHARE_DATA, R_CM_TYPE_UNKNOWN,
        R_CM_ENCODING_FORMAT_WRAPPED, cm_len,
        cm_data, &num_used, &obj)) != R_ERROR_NONE)
    {
        BIO_printf(bio_out, "R_CM_from_binary failure\n");
        goto end;
    }

    /* Open input data stream */
    if (datafile == NULL)
    {
        BIO_printf(bio_out, "No input file specified\n", datafile);
        goto end;
    }
    else
    {
        /* Open the file name for reading */
        if ((bio_in = BIO_new_file(datafile, "rb")) == NULL)
        {
            BIO_printf(bio_out, "Cannot open file for reading: %s\n", datafile);
            goto end;
        }
    }

    bio_tos = bio_in; /* keep marker to current top of bio stack */

    /*
     * Create the BIO stack for streaming the data to create the
     * required digests.
     *      - Determine the number of different digests.
     *      - Create a digest BIO of each.
     *      - Keep a reference to each digest BIO.
     *      - Push each digest BIO onto the input stream.
     */
    if ((ret = R_CM_get_info(obj, R_CM_INFO_TYPE, &data_type)) != R_ERROR_NONE)
    {
        BIO_printf(bio_out, "Retrieve content type failure\n");
        goto end;
    }
    if ((ret = R_CM_get_info(obj, R_CM_INFO_SIGNER_COUNT, &num_of_signers))
            != R_ERROR_NONE)
    {
        BIO_printf(bio_out, "Retrieve signer count failure\n");
        goto end;
    }

    /* Find the number of digests */
    if ((ret = R_CM_get_info(obj, R_CM_INFO_DIGEST_ALG_COUNT,
                             &num_of_digests)) != R_ERROR_NONE)
    {
        BIO_printf(bio_out, "Retrieve signer count failure\n");
        goto end;
    }

    for(digest_num=0; digest_num<num_of_digests; digest_num++)
    {
      digest_ids.index = digest_num;
      if ((ret = R_CM_get_info(obj, R_CM_INFO_DIGEST_ALG,
                               &digest_ids)) != R_ERROR_NONE)
      {
        BIO_printf(bio_out, "Retrieve digest alg failure\n");
        goto end;
      }

      /* Create the digest BIO and add it to the stack */
      if (BIO_new_init(lib_ctx, 0, BIO_TYPE_CR, R_CR_TYPE_DIGEST,
                       &(digest_ids.value), &bio_digest) != R_ERROR_NONE)
      {
          BIO_printf(bio_out, "Failed create new digest BIO\n");
          goto end;
      }

      /* Create the BIO stack */
      BIO_push(bio_digest, bio_tos);
      bio_tos = bio_digest;
      /*
       * Keep track of all the unique digests as each one will need to be
       * added to the R_CM object before verifying the signatures
       */
      digest_id[digest_num] = digest_ids.value;
      digest_bios[digest_num] = bio_digest;
    }

    /* Read all application data from the input stream */
    /* Allocate memory for the buffer into which to read */
    if ((buf = (unsigned char *)Malloc(BUF_LEN)) == NULL)
    {
        BIO_printf(bio_out, "Failed to allocate memory (%d Bytes)\n", BUF_LEN);
        goto end;
    }

    while ((len = BIO_read(bio_digest, (char *)buf, BUF_LEN)) != 0)
    {
        /* Stop reading data if an unrecoverable error occurs */
        if ((len < -1) || ((len == -1) && (!BIO_should_retry(bio_digest))))
        {
            BIO_printf(bio_out, "Failure while reading data\n");
            ret = R_ERROR_IO;
            break;
        }

        /* Dump out any Bytes that are returned in the buffer */
        if (len > 0)
        {
            if (print_data)
            {
                /*
                 * Application-specific code to use the data. Note that this
                 * data has, as yet, not been verified. This occurs later
                 * when the cryptographic message is verified.
                 */
                BIO_dump(bio_out, buf, len);
            }
        }
    }

    /*
     * Load the digests of the data to be verified into a
     * cryptographic message
     */
    for( digest_data.index=0; digest_data.index<digest_num;
         digest_data.index++ )
    {
      /* Get the digest from the BIO */
      data_len = BUF_LEN;
      data_len = BIO_gets(digest_bios[digest_data.index], (char *)buf,
                          data_len);

      /* Add the digest to the R_CM object. The index of each type of
       * digest has already been established when the BIO stack was
       * created earlier - that is, before streaming the data.
       */
      digest_data.data = buf;
      digest_data.len = data_len;
      R_CM_set_info(obj, R_CM_INFO_DIGEST, &digest_data);
    }

    /* If it is a plain data message then it can only be printed */
    if (data_type == R_CM_TYPE_DATA)
    {
        goto end;
    }

    /* Verify all the signers */
    if ((ret = R_CM_signer_verify(obj, store_ctx, vfy_ctx, R_CM_INDEX_ALL,
        &is_verified)) != R_ERROR_NONE)
    {
        BIO_printf(bio_out, "R_CM_signer_verify failed\n");
        goto end;
    }

    if (!is_verified)
    {
        ret = R_ERROR_FAILED;
        BIO_printf(bio_out, "Verify signer failed\n");
        goto end;
    }

    /* Print all the verification information for the signers */
    if ((ret = print_signer_info(bio_out, obj, cert_ctx, print_sig)) !=
        R_ERROR_NONE)
    {
        goto end;
    }

    /*
     * Verify the data. The actual data is not available, but the
     * digest of this data was calculated earlier and stored in obj.
     * obj contains all the cryptographic information required to perform
     * the verification, such as the signer information. data_obj is set
     * to NULL as it has no information relevant to R_CM_signature_verify()
     * in this usage.
     */
    if ((ret = R_CM_signature_verify(obj, R_CM_INDEX_ALL, data_obj,
        &is_verified)) != R_ERROR_NONE)
    {
        BIO_printf(bio_out, "R_CM_signature_verify failed\n");
        goto end;
    }

    if (!is_verified)
    {
        ret = R_ERROR_FAILED;
        BIO_printf(bio_out, "Verify data failed\n");
        goto end;
    }

end:

    /*
     * 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) && (bio_out != NULL))
    {
        BIO_printf(bio_out, "ERROR: (%d) %s\n", ret,
            R_LIB_CTX_get_error_string(lib_ctx, R_RES_MOD_ID_LIBRARY, ret));
    }

    if (cm_data != NULL)
    {
        Free(cm_data);
    }

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

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

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

    if (vfy_ctx != NULL)
    {
        R_VERIFY_CTX_free(vfy_ctx);
    }

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

    /*
     * The certificate context cannot be freed until the store has been emptied
     * as certificates in the store hold a reference back to the certificate
     * context
     */
    if (cert_ctx != NULL)
    {
        R_CERT_CTX_free(cert_ctx);
    }

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

    for(digest_num=0; digest_num<num_of_digests; digest_num++)
    {
      if (digest_bios[digest_num] != NULL) BIO_free(digest_bios[digest_num]);
    }

    if (buf != NULL)
    {
        Free(buf);
    }

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

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

    return(R_ERROR_EXIT_CODE(ret));
}


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