Example program to test AES-GCM functionality. Used for a workshop

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers x509_crt.h Source File

x509_crt.h

Go to the documentation of this file.
00001 /**
00002  * \file x509_crt.h
00003  *
00004  * \brief X.509 certificate parsing and writing
00005  *
00006  *  Copyright (C) 2006-2013, Brainspark B.V.
00007  *
00008  *  This file is part of PolarSSL (http://www.polarssl.org)
00009  *  Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
00010  *
00011  *  All rights reserved.
00012  *
00013  *  This program is free software; you can redistribute it and/or modify
00014  *  it under the terms of the GNU General Public License as published by
00015  *  the Free Software Foundation; either version 2 of the License, or
00016  *  (at your option) any later version.
00017  *
00018  *  This program is distributed in the hope that it will be useful,
00019  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00020  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00021  *  GNU General Public License for more details.
00022  *
00023  *  You should have received a copy of the GNU General Public License along
00024  *  with this program; if not, write to the Free Software Foundation, Inc.,
00025  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
00026  */
00027 #ifndef POLARSSL_X509_CRT_H
00028 #define POLARSSL_X509_CRT_H
00029 
00030 #if !defined(POLARSSL_CONFIG_FILE)
00031 #include "config.h"
00032 #else
00033 #include POLARSSL_CONFIG_FILE
00034 #endif
00035 
00036 #include "x509.h"
00037 
00038 #include "x509_crl.h"
00039 
00040 /**
00041  * \addtogroup x509_module
00042  * \{
00043  */
00044 
00045 #ifdef __cplusplus
00046 extern "C" {
00047 #endif
00048 
00049 /**
00050  * \name Structures and functions for parsing and writing X.509 certificates
00051  * \{
00052  */
00053 
00054 /**
00055  * Container for an X.509 certificate. The certificate may be chained.
00056  */
00057 typedef struct _x509_crt
00058 {
00059     x509_buf raw;               /**< The raw certificate data (DER). */
00060     x509_buf tbs;               /**< The raw certificate body (DER). The part that is To Be Signed. */
00061 
00062     int version;                /**< The X.509 version. (0=v1, 1=v2, 2=v3) */
00063     x509_buf serial;            /**< Unique id for certificate issued by a specific CA. */
00064     x509_buf sig_oid1;          /**< Signature algorithm, e.g. sha1RSA */
00065 
00066     x509_buf issuer_raw;        /**< The raw issuer data (DER). Used for quick comparison. */
00067     x509_buf subject_raw;       /**< The raw subject data (DER). Used for quick comparison. */
00068 
00069     x509_name issuer;           /**< The parsed issuer data (named information object). */
00070     x509_name subject;          /**< The parsed subject data (named information object). */
00071 
00072     x509_time valid_from;       /**< Start time of certificate validity. */
00073     x509_time valid_to;         /**< End time of certificate validity. */
00074 
00075     pk_context pk;              /**< Container for the public key context. */
00076 
00077     x509_buf issuer_id;         /**< Optional X.509 v2/v3 issuer unique identifier. */
00078     x509_buf subject_id;        /**< Optional X.509 v2/v3 subject unique identifier. */
00079     x509_buf v3_ext;            /**< Optional X.509 v3 extensions.  */
00080     x509_sequence subject_alt_names;    /**< Optional list of Subject Alternative Names (Only dNSName supported). */
00081 
00082     int ext_types;              /**< Bit string containing detected and parsed extensions */
00083     int ca_istrue;              /**< Optional Basic Constraint extension value: 1 if this certificate belongs to a CA, 0 otherwise. */
00084     int max_pathlen;            /**< Optional Basic Constraint extension value: The maximum path length to the root certificate. Path length is 1 higher than RFC 5280 'meaning', so 1+ */
00085 
00086     unsigned char key_usage;    /**< Optional key usage extension value: See the values in x509.h */
00087 
00088     x509_sequence ext_key_usage; /**< Optional list of extended key usage OIDs. */
00089 
00090     unsigned char ns_cert_type; /**< Optional Netscape certificate type extension value: See the values in x509.h */
00091 
00092     x509_buf sig_oid2;          /**< Signature algorithm. Must match sig_oid1. */
00093     x509_buf sig;               /**< Signature: hash of the tbs part signed with the private key. */
00094     md_type_t sig_md;           /**< Internal representation of the MD algorithm of the signature algorithm, e.g. POLARSSL_MD_SHA256 */
00095     pk_type_t sig_pk            /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. POLARSSL_PK_RSA */;
00096 
00097     struct _x509_crt *next;     /**< Next certificate in the CA-chain. */
00098 }
00099 x509_crt;
00100 
00101 #define X509_CRT_VERSION_1              0
00102 #define X509_CRT_VERSION_2              1
00103 #define X509_CRT_VERSION_3              2
00104 
00105 #define X509_RFC5280_MAX_SERIAL_LEN 32
00106 #define X509_RFC5280_UTC_TIME_LEN   15
00107 
00108 /**
00109  * Container for writing a certificate (CRT)
00110  */
00111 typedef struct _x509write_cert
00112 {
00113     int version;
00114     mpi serial;
00115     pk_context *subject_key;
00116     pk_context *issuer_key;
00117     asn1_named_data *subject;
00118     asn1_named_data *issuer;
00119     md_type_t md_alg;
00120     char not_before[X509_RFC5280_UTC_TIME_LEN + 1];
00121     char not_after[X509_RFC5280_UTC_TIME_LEN + 1];
00122     asn1_named_data *extensions;
00123 }
00124 x509write_cert;
00125 
00126 #if defined(POLARSSL_X509_CRT_PARSE_C)
00127 /**
00128  * \brief          Parse a single DER formatted certificate and add it
00129  *                 to the chained list.
00130  *
00131  * \param chain    points to the start of the chain
00132  * \param buf      buffer holding the certificate DER data
00133  * \param buflen   size of the buffer
00134  *
00135  * \return         0 if successful, or a specific X509 or PEM error code
00136  */
00137 int x509_crt_parse_der( x509_crt *chain, const unsigned char *buf,
00138                         size_t buflen );
00139 
00140 /**
00141  * \brief          Parse one or more certificates and add them
00142  *                 to the chained list. Parses permissively. If some
00143  *                 certificates can be parsed, the result is the number
00144  *                 of failed certificates it encountered. If none complete
00145  *                 correctly, the first error is returned.
00146  *
00147  * \param chain    points to the start of the chain
00148  * \param buf      buffer holding the certificate data
00149  * \param buflen   size of the buffer
00150  *
00151  * \return         0 if all certificates parsed successfully, a positive number
00152  *                 if partly successful or a specific X509 or PEM error code
00153  */
00154 int x509_crt_parse( x509_crt *chain, const unsigned char *buf, size_t buflen );
00155 
00156 #if defined(POLARSSL_FS_IO)
00157 /**
00158  * \brief          Load one or more certificates and add them
00159  *                 to the chained list. Parses permissively. If some
00160  *                 certificates can be parsed, the result is the number
00161  *                 of failed certificates it encountered. If none complete
00162  *                 correctly, the first error is returned.
00163  *
00164  * \param chain    points to the start of the chain
00165  * \param path     filename to read the certificates from
00166  *
00167  * \return         0 if all certificates parsed successfully, a positive number
00168  *                 if partly successful or a specific X509 or PEM error code
00169  */
00170 int x509_crt_parse_file( x509_crt *chain, const char *path );
00171 
00172 /**
00173  * \brief          Load one or more certificate files from a path and add them
00174  *                 to the chained list. Parses permissively. If some
00175  *                 certificates can be parsed, the result is the number
00176  *                 of failed certificates it encountered. If none complete
00177  *                 correctly, the first error is returned.
00178  *
00179  * \warning        This function is NOT thread-safe unless
00180  *                 POLARSSL_THREADING_PTHREADS is defined. If you're using an
00181  *                 alternative threading implementation, you should either use
00182  *                 this function only in the main thread, or mutex it.
00183  *
00184  * \param chain    points to the start of the chain
00185  * \param path     directory / folder to read the certificate files from
00186  *
00187  * \return         0 if all certificates parsed successfully, a positive number
00188  *                 if partly successful or a specific X509 or PEM error code
00189  */
00190 int x509_crt_parse_path( x509_crt *chain, const char *path );
00191 #endif /* POLARSSL_FS_IO */
00192 
00193 /**
00194  * \brief          Returns an informational string about the
00195  *                 certificate.
00196  *
00197  * \param buf      Buffer to write to
00198  * \param size     Maximum size of buffer
00199  * \param prefix   A line prefix
00200  * \param crt      The X509 certificate to represent
00201  *
00202  * \return         The amount of data written to the buffer, or -1 in
00203  *                 case of an error.
00204  */
00205 int x509_crt_info( char *buf, size_t size, const char *prefix,
00206                    const x509_crt *crt );
00207 
00208 /**
00209  * \brief          Verify the certificate signature
00210  *
00211  *                 The verify callback is a user-supplied callback that
00212  *                 can clear / modify / add flags for a certificate. If set,
00213  *                 the verification callback is called for each
00214  *                 certificate in the chain (from the trust-ca down to the
00215  *                 presented crt). The parameters for the callback are:
00216  *                 (void *parameter, x509_crt *crt, int certificate_depth,
00217  *                 int *flags). With the flags representing current flags for
00218  *                 that specific certificate and the certificate depth from
00219  *                 the bottom (Peer cert depth = 0).
00220  *
00221  *                 All flags left after returning from the callback
00222  *                 are also returned to the application. The function should
00223  *                 return 0 for anything but a fatal error.
00224  *
00225  * \param crt      a certificate to be verified
00226  * \param trust_ca the trusted CA chain
00227  * \param ca_crl   the CRL chain for trusted CA's
00228  * \param cn       expected Common Name (can be set to
00229  *                 NULL if the CN must not be verified)
00230  * \param flags    result of the verification
00231  * \param f_vrfy   verification function
00232  * \param p_vrfy   verification parameter
00233  *
00234  * \return         0 if successful or POLARSSL_ERR_X509_SIG_VERIFY_FAILED,
00235  *                 in which case *flags will have one or more of
00236  *                 the following values set:
00237  *                      BADCERT_EXPIRED --
00238  *                      BADCERT_REVOKED --
00239  *                      BADCERT_CN_MISMATCH --
00240  *                      BADCERT_NOT_TRUSTED
00241  *                 or another error in case of a fatal error encountered
00242  *                 during the verification process.
00243  */
00244 int x509_crt_verify( x509_crt *crt,
00245                      x509_crt *trust_ca,
00246                      x509_crl *ca_crl,
00247                      const char *cn, int *flags,
00248                      int (*f_vrfy)(void *, x509_crt *, int, int *),
00249                      void *p_vrfy );
00250 
00251 #if defined(POLARSSL_X509_CHECK_KEY_USAGE)
00252 /**
00253  * \brief          Check usage of certificate against keyUsage extension.
00254  *
00255  * \param crt      Leaf certificate used.
00256  * \param usage    Intended usage(s) (eg KU_KEY_ENCIPHERMENT before using the
00257  *                 certificate to perform an RSA key exchange).
00258  *
00259  * \return         0 is these uses of the certificate are allowed,
00260  *                 POLARSSL_ERR_X509_BAD_INPUT_DATA if the keyUsage extension
00261  *                 is present but does not contain all the bits set in the
00262  *                 usage argument.
00263  *
00264  * \note           You should only call this function on leaf certificates, on
00265  *                 (intermediate) CAs the keyUsage extension is automatically
00266  *                 checked by \c x509_crt_verify().
00267  */
00268 int x509_crt_check_key_usage( const x509_crt *crt, int usage );
00269 #endif /* POLARSSL_X509_CHECK_KEY_USAGE) */
00270 
00271 #if defined(POLARSSL_X509_CHECK_EXTENDED_KEY_USAGE)
00272 /**
00273  * \brief          Check usage of certificate against extentedJeyUsage.
00274  *
00275  * \param crt      Leaf certificate used.
00276  * \param usage_oid Intended usage (eg OID_SERVER_AUTH or OID_CLIENT_AUTH).
00277  * \param usage_len Length of usage_oid (eg given by OID_SIZE()).
00278  *
00279  * \return         0 is this use of the certificate is allowed,
00280  *                 POLARSSL_ERR_X509_BAD_INPUT_DATA if not.
00281  *
00282  * \note           Usually only makes sense on leaf certificates.
00283  */
00284 int x509_crt_check_extended_key_usage( const x509_crt *crt,
00285                                        const char *usage_oid,
00286                                        size_t usage_len );
00287 #endif /* POLARSSL_X509_CHECK_EXTENDED_KEY_USAGE) */
00288 
00289 #if defined(POLARSSL_X509_CRL_PARSE_C)
00290 /**
00291  * \brief          Verify the certificate revocation status
00292  *
00293  * \param crt      a certificate to be verified
00294  * \param crl      the CRL to verify against
00295  *
00296  * \return         1 if the certificate is revoked, 0 otherwise
00297  *
00298  */
00299 int x509_crt_revoked( const x509_crt *crt, const x509_crl *crl );
00300 #endif /* POLARSSL_X509_CRL_PARSE_C */
00301 
00302 /**
00303  * \brief          Initialize a certificate (chain)
00304  *
00305  * \param crt      Certificate chain to initialize
00306  */
00307 void x509_crt_init( x509_crt *crt );
00308 
00309 /**
00310  * \brief          Unallocate all certificate data
00311  *
00312  * \param crt      Certificate chain to free
00313  */
00314 void x509_crt_free( x509_crt *crt );
00315 #endif /* POLARSSL_X509_CRT_PARSE_C */
00316 
00317 /* \} name */
00318 /* \} addtogroup x509_module */
00319 
00320 #if defined(POLARSSL_X509_CRT_WRITE_C)
00321 /**
00322  * \brief           Initialize a CRT writing context
00323  *
00324  * \param ctx       CRT context to initialize
00325  */
00326 void x509write_crt_init( x509write_cert *ctx );
00327 
00328 /**
00329  * \brief           Set the verion for a Certificate
00330  *                  Default: X509_CRT_VERSION_3
00331  *
00332  * \param ctx       CRT context to use
00333  * \param version   version to set (X509_CRT_VERSION_1, X509_CRT_VERSION_2 or
00334  *                                  X509_CRT_VERSION_3)
00335  */
00336 void x509write_crt_set_version( x509write_cert *ctx, int version );
00337 
00338 /**
00339  * \brief           Set the serial number for a Certificate.
00340  *
00341  * \param ctx       CRT context to use
00342  * \param serial    serial number to set
00343  *
00344  * \return          0 if successful
00345  */
00346 int x509write_crt_set_serial( x509write_cert *ctx, const mpi *serial );
00347 
00348 /**
00349  * \brief           Set the validity period for a Certificate
00350  *                  Timestamps should be in string format for UTC timezone
00351  *                  i.e. "YYYYMMDDhhmmss"
00352  *                  e.g. "20131231235959" for December 31st 2013
00353  *                       at 23:59:59
00354  *
00355  * \param ctx       CRT context to use
00356  * \param not_before    not_before timestamp
00357  * \param not_after     not_after timestamp
00358  *
00359  * \return          0 if timestamp was parsed successfully, or
00360  *                  a specific error code
00361  */
00362 int x509write_crt_set_validity( x509write_cert *ctx, const char *not_before,
00363                                 const char *not_after );
00364 
00365 /**
00366  * \brief           Set the issuer name for a Certificate
00367  *                  Issuer names should contain a comma-separated list
00368  *                  of OID types and values:
00369  *                  e.g. "C=NL,O=Offspark,CN=PolarSSL CA"
00370  *
00371  * \param ctx           CRT context to use
00372  * \param issuer_name   issuer name to set
00373  *
00374  * \return          0 if issuer name was parsed successfully, or
00375  *                  a specific error code
00376  */
00377 int x509write_crt_set_issuer_name( x509write_cert *ctx,
00378                                    const char *issuer_name );
00379 
00380 /**
00381  * \brief           Set the subject name for a Certificate
00382  *                  Subject names should contain a comma-separated list
00383  *                  of OID types and values:
00384  *                  e.g. "C=NL,O=Offspark,CN=PolarSSL Server 1"
00385  *
00386  * \param ctx           CRT context to use
00387  * \param subject_name  subject name to set
00388  *
00389  * \return          0 if subject name was parsed successfully, or
00390  *                  a specific error code
00391  */
00392 int x509write_crt_set_subject_name( x509write_cert *ctx,
00393                                     const char *subject_name );
00394 
00395 /**
00396  * \brief           Set the subject public key for the certificate
00397  *
00398  * \param ctx       CRT context to use
00399  * \param key       public key to include
00400  */
00401 void x509write_crt_set_subject_key( x509write_cert *ctx, pk_context *key );
00402 
00403 /**
00404  * \brief           Set the issuer key used for signing the certificate
00405  *
00406  * \param ctx       CRT context to use
00407  * \param key       private key to sign with
00408  */
00409 void x509write_crt_set_issuer_key( x509write_cert *ctx, pk_context *key );
00410 
00411 /**
00412  * \brief           Set the MD algorithm to use for the signature
00413  *                  (e.g. POLARSSL_MD_SHA1)
00414  *
00415  * \param ctx       CRT context to use
00416  * \param md_alg    MD algorithm to use
00417  */
00418 void x509write_crt_set_md_alg( x509write_cert *ctx, md_type_t md_alg );
00419 
00420 /**
00421  * \brief           Generic function to add to or replace an extension in the
00422  *                  CRT
00423  *
00424  * \param ctx       CRT context to use
00425  * \param oid       OID of the extension
00426  * \param oid_len   length of the OID
00427  * \param critical  if the extension is critical (per the RFC's definition)
00428  * \param val       value of the extension OCTET STRING
00429  * \param val_len   length of the value data
00430  *
00431  * \return          0 if successful, or a POLARSSL_ERR_X509WRITE_MALLOC_FAILED
00432  */
00433 int x509write_crt_set_extension( x509write_cert *ctx,
00434                                  const char *oid, size_t oid_len,
00435                                  int critical,
00436                                  const unsigned char *val, size_t val_len );
00437 
00438 /**
00439  * \brief           Set the basicConstraints extension for a CRT
00440  *
00441  * \param ctx       CRT context to use
00442  * \param is_ca     is this a CA certificate
00443  * \param max_pathlen   maximum length of certificate chains below this
00444  *                      certificate (only for CA certificates, -1 is
00445  *                      inlimited)
00446  *
00447  * \return          0 if successful, or a POLARSSL_ERR_X509WRITE_MALLOC_FAILED
00448  */
00449 int x509write_crt_set_basic_constraints( x509write_cert *ctx,
00450                                          int is_ca, int max_pathlen );
00451 
00452 #if defined(POLARSSL_SHA1_C)
00453 /**
00454  * \brief           Set the subjectKeyIdentifier extension for a CRT
00455  *                  Requires that x509write_crt_set_subject_key() has been
00456  *                  called before
00457  *
00458  * \param ctx       CRT context to use
00459  *
00460  * \return          0 if successful, or a POLARSSL_ERR_X509WRITE_MALLOC_FAILED
00461  */
00462 int x509write_crt_set_subject_key_identifier( x509write_cert *ctx );
00463 
00464 /**
00465  * \brief           Set the authorityKeyIdentifier extension for a CRT
00466  *                  Requires that x509write_crt_set_issuer_key() has been
00467  *                  called before
00468  *
00469  * \param ctx       CRT context to use
00470  *
00471  * \return          0 if successful, or a POLARSSL_ERR_X509WRITE_MALLOC_FAILED
00472  */
00473 int x509write_crt_set_authority_key_identifier( x509write_cert *ctx );
00474 #endif /* POLARSSL_SHA1_C */
00475 
00476 /**
00477  * \brief           Set the Key Usage Extension flags
00478  *                  (e.g. KU_DIGITAL_SIGNATURE | KU_KEY_CERT_SIGN)
00479  *
00480  * \param ctx       CRT context to use
00481  * \param key_usage key usage flags to set
00482  *
00483  * \return          0 if successful, or POLARSSL_ERR_X509WRITE_MALLOC_FAILED
00484  */
00485 int x509write_crt_set_key_usage( x509write_cert *ctx, unsigned char key_usage );
00486 
00487 /**
00488  * \brief           Set the Netscape Cert Type flags
00489  *                  (e.g. NS_CERT_TYPE_SSL_CLIENT | NS_CERT_TYPE_EMAIL)
00490  *
00491  * \param ctx           CRT context to use
00492  * \param ns_cert_type  Netscape Cert Type flags to set
00493  *
00494  * \return          0 if successful, or POLARSSL_ERR_X509WRITE_MALLOC_FAILED
00495  */
00496 int x509write_crt_set_ns_cert_type( x509write_cert *ctx,
00497                                     unsigned char ns_cert_type );
00498 
00499 /**
00500  * \brief           Free the contents of a CRT write context
00501  *
00502  * \param ctx       CRT context to free
00503  */
00504 void x509write_crt_free( x509write_cert *ctx );
00505 
00506 /**
00507  * \brief           Write a built up certificate to a X509 DER structure
00508  *                  Note: data is written at the end of the buffer! Use the
00509  *                        return value to determine where you should start
00510  *                        using the buffer
00511  *
00512  * \param ctx       certificate to write away
00513  * \param buf       buffer to write to
00514  * \param size      size of the buffer
00515  * \param f_rng     RNG function (for signature, see note)
00516  * \param p_rng     RNG parameter
00517  *
00518  * \return          length of data written if successful, or a specific
00519  *                  error code
00520  *
00521  * \note            f_rng may be NULL if RSA is used for signature and the
00522  *                  signature is made offline (otherwise f_rng is desirable
00523  *                  for countermeasures against timing attacks).
00524  *                  ECDSA signatures always require a non-NULL f_rng.
00525  */
00526 int x509write_crt_der( x509write_cert *ctx, unsigned char *buf, size_t size,
00527                        int (*f_rng)(void *, unsigned char *, size_t),
00528                        void *p_rng );
00529 
00530 #if defined(POLARSSL_PEM_WRITE_C)
00531 /**
00532  * \brief           Write a built up certificate to a X509 PEM string
00533  *
00534  * \param ctx       certificate to write away
00535  * \param buf       buffer to write to
00536  * \param size      size of the buffer
00537  * \param f_rng     RNG function (for signature, see note)
00538  * \param p_rng     RNG parameter
00539  *
00540  * \return          0 successful, or a specific error code
00541  *
00542  * \note            f_rng may be NULL if RSA is used for signature and the
00543  *                  signature is made offline (otherwise f_rng is desirable
00544  *                  for countermeasures against timing attacks).
00545  *                  ECDSA signatures always require a non-NULL f_rng.
00546  */
00547 int x509write_crt_pem( x509write_cert *ctx, unsigned char *buf, size_t size,
00548                        int (*f_rng)(void *, unsigned char *, size_t),
00549                        void *p_rng );
00550 #endif /* POLARSSL_PEM_WRITE_C */
00551 #endif /* POLARSSL_X509_CRT_WRITE_C */
00552 
00553 #ifdef __cplusplus
00554 }
00555 #endif
00556 
00557 #endif /* x509_crt.h */
00558 
00559