certverify.c Example 'C' code for certificate validation

Introduction
The example 'C' program certverify.c demonstrates how to perform a basic certificate validation against a root certificate authority, using the OpenSSL library functions.

Example Code Listing
/* ------------------------------------------------------------ *
 * file:        certverify.c                                    *
 * purpose:     Example code for OpenSSL certificate validation *
 * author:      06/12/2012 Frank4DD                             *
 *                                                              *
 * gcc -o certverify certverify.c -lssl -lcrypto                *
 * ------------------------------------------------------------ */

#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>

int main() {

  const char ca_bundlestr[] = "./ca-bundle.pem";
  const char cert_filestr[] = "./cert-file.pem";

  BIO              *certbio = NULL;
  BIO               *outbio = NULL;
  X509          *error_cert = NULL;
  X509                *cert = NULL;
  X509_NAME    *certsubject = NULL;
  X509_STORE         *store = NULL;
  X509_STORE_CTX  *vrfy_ctx = NULL;
  int ret;

  /* ---------------------------------------------------------- *
   * These function calls initialize openssl for correct work.  *
   * ---------------------------------------------------------- */
  OpenSSL_add_all_algorithms();
  ERR_load_BIO_strings();
  ERR_load_crypto_strings();

  /* ---------------------------------------------------------- *
   * Create the Input/Output BIO's.                             *
   * ---------------------------------------------------------- */
  certbio = BIO_new(BIO_s_file());
  outbio  = BIO_new_fp(stdout, BIO_NOCLOSE);

  /* ---------------------------------------------------------- *
   * Initialize the global certificate validation store object. *
   * ---------------------------------------------------------- */
  if (!(store=X509_STORE_new()))
     BIO_printf(outbio, "Error creating X509_STORE_CTX object\n");

  /* ---------------------------------------------------------- *
   * Create the context structure for the validation operation. *
   * ---------------------------------------------------------- */
  vrfy_ctx = X509_STORE_CTX_new();

  /* ---------------------------------------------------------- *
   * Load the certificate and cacert chain from file (PEM).     *
   * ---------------------------------------------------------- */
  ret = BIO_read_filename(certbio, cert_filestr);
  if (! (cert = PEM_read_bio_X509(certbio, NULL, 0, NULL))) {
    BIO_printf(outbio, "Error loading cert into memory\n");
    exit(-1);
  }

  ret = X509_STORE_load_locations(store, ca_bundlestr, NULL);
  if (ret != 1)
    BIO_printf(outbio, "Error loading CA cert or chain file\n");

  /* ---------------------------------------------------------- *
   * Initialize the ctx structure for a verification operation: *
   * Set the trusted cert store, the unvalidated cert, and any  *
   * potential certs that could be needed (here we set it NULL) *
   * ---------------------------------------------------------- */
  X509_STORE_CTX_init(vrfy_ctx, store, cert, NULL);

  /* ---------------------------------------------------------- *
   * Check the complete cert chain can be build and validated.  *
   * Returns 1 on success, 0 on verification failures, and -1   *
   * for trouble with the ctx object (i.e. missing certificate) *
   * ---------------------------------------------------------- */
  ret = X509_verify_cert(vrfy_ctx);
  BIO_printf(outbio, "Verification return code: %d\n", ret);

  if(ret == 0 || ret == 1)
  BIO_printf(outbio, "Verification result text: %s\n",
             X509_verify_cert_error_string(vrfy_ctx->error));

  /* ---------------------------------------------------------- *
   * The error handling below shows how to get failure details  *
   * from the offending certificate.                            *
   * ---------------------------------------------------------- */
  if(ret == 0) {
    /*  get the offending certificate causing the failure */
    error_cert  = X509_STORE_CTX_get_current_cert(vrfy_ctx);
    certsubject = X509_NAME_new();
    certsubject = X509_get_subject_name(error_cert);
    BIO_printf(outbio, "Verification failed cert:\n");
    X509_NAME_print_ex(outbio, certsubject, 0, XN_FLAG_MULTILINE);
    BIO_printf(outbio, "\n");
  }

  /* ---------------------------------------------------------- *
   * Free up all structures                                     *
   * ---------------------------------------------------------- */
  X509_STORE_CTX_free(vrfy_ctx);
  X509_STORE_free(store);
  X509_free(cert);
  BIO_free_all(certbio);
  BIO_free_all(outbio);
  exit(0);
}
Compiling the Code
Compile the test program with:

> gcc -o certverify certverify.c -lssl -lcrypto
Example Output
The program expects a certificate file called cert-file.pem and a CA certificate chain file ca-bundle.pem in the same directory. If both the server and root certificates are found and loaded, the following output is produced for a successful validation:

fm@susie114:~> ./certverify
Verification return code: 1
Verification result text: ok
Below is an example for a failed validation. In this particular case, the CA certificate does not match the signature on the server certificate.

fm@susie114:~> ./certverify
Verification return code: 0
Verification result text: unable to get local issuer certificate
Verification failed cert:
countryName               = JP
stateOrProvinceName       = Tokyo
commonName                = nagios.frank4dd.com
If there is an error in loading the certificate, the verification returns a negative number.

fm@susie114:~> ./certverify
Error loading cert into memory
Verification return code: -1
Remarks
The typical error message for a failed verification, " unable to get local issuer certificate", is very vague about the real problem. Consider having a longer chain of certificates, which one is broken? What is the offending key, serial, subject, etc? In the code above, this message is also returned if the CA file does not exist. Careful programming should catch all possible cases, OpenSSL offers to implement a callback function to handle errors individually with great detail.

The OpenSSL manual page for verify explains how the certificate verification process works.

The verification mode can be additionally controlled through 15 flags. Some add debugging options, but most notably are the flags for adding checks of external certificate revocation lists (CRL). These lists are still rarely used, both by CA vendors and SSL clients. That's why we see vendors like Microsoft issuing emergency patches to disable root CA's "trusted" status (MS advisory examples 2607712, 2718704) from their CA certificate lists. With a growing number of CA, signing mistakes, key compromise or collision attacks happen more often lately, resulting in a similar growing list of invalidated root certs. Below is an example screenshot of a recent Windows XP certificate store:

invalidated, untrusted root CA's in Windows XP

In further workarounds, Microsoft developed automatic root update mechanisms for their latest OS versions. Correctly establishing trust is critical, but today it is still rather messy and often far from being timely and fully reliable.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tiny丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值