Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. /*
  2.  *  X.509 certificate parsing and verification
  3.  *
  4.  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  5.  *  SPDX-License-Identifier: GPL-2.0
  6.  *
  7.  *  This program is free software; you can redistribute it and/or modify
  8.  *  it under the terms of the GNU General Public License as published by
  9.  *  the Free Software Foundation; either version 2 of the License, or
  10.  *  (at your option) any later version.
  11.  *
  12.  *  This program is distributed in the hope that it will be useful,
  13.  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15.  *  GNU General Public License for more details.
  16.  *
  17.  *  You should have received a copy of the GNU General Public License along
  18.  *  with this program; if not, write to the Free Software Foundation, Inc.,
  19.  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20.  *
  21.  *  This file is part of mbed TLS (https://tls.mbed.org)
  22.  */
  23. /*
  24.  *  The ITU-T X.509 standard defines a certificate format for PKI.
  25.  *
  26.  *  http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)
  27.  *  http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)
  28.  *  http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)
  29.  *
  30.  *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf
  31.  *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
  32.  *
  33.  *  [SIRO] https://cabforum.org/wp-content/uploads/Chunghwatelecom201503cabforumV4.pdf
  34.  */
  35.  
  36. #if !defined(MBEDTLS_CONFIG_FILE)
  37. #include "mbedtls/config.h"
  38. #else
  39. #include MBEDTLS_CONFIG_FILE
  40. #endif
  41.  
  42. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  43.  
  44. #include "mbedtls/x509_crt.h"
  45. #include "mbedtls/oid.h"
  46. #include "mbedtls/platform_util.h"
  47.  
  48. #include <string.h>
  49.  
  50. #if defined(MBEDTLS_PEM_PARSE_C)
  51. #include "mbedtls/pem.h"
  52. #endif
  53.  
  54. #if defined(MBEDTLS_PLATFORM_C)
  55. #include "mbedtls/platform.h"
  56. #else
  57. #include <stdio.h>
  58. #include <stdlib.h>
  59. #define mbedtls_free       free
  60. #define mbedtls_calloc    calloc
  61. #define mbedtls_snprintf   snprintf
  62. #endif
  63.  
  64. #if defined(MBEDTLS_THREADING_C)
  65. #include "mbedtls/threading.h"
  66. #endif
  67.  
  68. #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
  69. #include <windows.h>
  70. #else
  71. #include <time.h>
  72. #endif
  73.  
  74. #if defined(MBEDTLS_FS_IO)
  75. #include <stdio.h>
  76. #if !defined(_WIN32) || defined(EFIX64) || defined(EFI32)
  77. #include <sys/types.h>
  78. #include <sys/stat.h>
  79. #include <dirent.h>
  80. #endif /* !_WIN32 || EFIX64 || EFI32 */
  81. #endif
  82.  
  83. /*
  84.  * Item in a verification chain: cert and flags for it
  85.  */
  86. typedef struct {
  87.     mbedtls_x509_crt *crt;
  88.     uint32_t flags;
  89. } x509_crt_verify_chain_item;
  90.  
  91. /*
  92.  * Max size of verification chain: end-entity + intermediates + trusted root
  93.  */
  94. #define X509_MAX_VERIFY_CHAIN_SIZE    ( MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2 )
  95.  
  96. /*
  97.  * Default profile
  98.  */
  99. const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default =
  100. {
  101. #if defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES)
  102.     /* Allow SHA-1 (weak, but still safe in controlled environments) */
  103.     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA1 ) |
  104. #endif
  105.     /* Only SHA-2 hashes */
  106.     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 ) |
  107.     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
  108.     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
  109.     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
  110.     0xFFFFFFF, /* Any PK alg    */
  111.     0xFFFFFFF, /* Any curve     */
  112.     2048,
  113. };
  114.  
  115. /*
  116.  * Next-default profile
  117.  */
  118. const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next =
  119. {
  120.     /* Hashes from SHA-256 and above */
  121.     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
  122.     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
  123.     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
  124.     0xFFFFFFF, /* Any PK alg    */
  125. #if defined(MBEDTLS_ECP_C)
  126.     /* Curves at or above 128-bit security level */
  127.     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
  128.     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ) |
  129.     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP521R1 ) |
  130.     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP256R1 ) |
  131.     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP384R1 ) |
  132.     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP512R1 ) |
  133.     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256K1 ),
  134. #else
  135.     0,
  136. #endif
  137.     2048,
  138. };
  139.  
  140. /*
  141.  * NSA Suite B Profile
  142.  */
  143. const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb =
  144. {
  145.     /* Only SHA-256 and 384 */
  146.     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
  147.     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ),
  148.     /* Only ECDSA */
  149.     MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECDSA ) |
  150.     MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECKEY ),
  151. #if defined(MBEDTLS_ECP_C)
  152.     /* Only NIST P-256 and P-384 */
  153.     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
  154.     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ),
  155. #else
  156.     0,
  157. #endif
  158.     0,
  159. };
  160.  
  161. /*
  162.  * Check md_alg against profile
  163.  * Return 0 if md_alg is acceptable for this profile, -1 otherwise
  164.  */
  165. static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile,
  166.                                       mbedtls_md_type_t md_alg )
  167. {
  168.     if( md_alg == MBEDTLS_MD_NONE )
  169.         return( -1 );
  170.  
  171.     if( ( profile->allowed_mds & MBEDTLS_X509_ID_FLAG( md_alg ) ) != 0 )
  172.         return( 0 );
  173.  
  174.     return( -1 );
  175. }
  176.  
  177. /*
  178.  * Check pk_alg against profile
  179.  * Return 0 if pk_alg is acceptable for this profile, -1 otherwise
  180.  */
  181. static int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile,
  182.                                       mbedtls_pk_type_t pk_alg )
  183. {
  184.     if( pk_alg == MBEDTLS_PK_NONE )
  185.         return( -1 );
  186.  
  187.     if( ( profile->allowed_pks & MBEDTLS_X509_ID_FLAG( pk_alg ) ) != 0 )
  188.         return( 0 );
  189.  
  190.     return( -1 );
  191. }
  192.  
  193. /*
  194.  * Check key against profile
  195.  * Return 0 if pk is acceptable for this profile, -1 otherwise
  196.  */
  197. static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile,
  198.                                    const mbedtls_pk_context *pk )
  199. {
  200.     const mbedtls_pk_type_t pk_alg = mbedtls_pk_get_type( pk );
  201.  
  202. #if defined(MBEDTLS_RSA_C)
  203.     if( pk_alg == MBEDTLS_PK_RSA || pk_alg == MBEDTLS_PK_RSASSA_PSS )
  204.     {
  205.         if( mbedtls_pk_get_bitlen( pk ) >= profile->rsa_min_bitlen )
  206.             return( 0 );
  207.  
  208.         return( -1 );
  209.     }
  210. #endif
  211.  
  212. #if defined(MBEDTLS_ECP_C)
  213.     if( pk_alg == MBEDTLS_PK_ECDSA ||
  214.         pk_alg == MBEDTLS_PK_ECKEY ||
  215.         pk_alg == MBEDTLS_PK_ECKEY_DH )
  216.     {
  217.         const mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id;
  218.  
  219.         if( gid == MBEDTLS_ECP_DP_NONE )
  220.             return( -1 );
  221.  
  222.         if( ( profile->allowed_curves & MBEDTLS_X509_ID_FLAG( gid ) ) != 0 )
  223.             return( 0 );
  224.  
  225.         return( -1 );
  226.     }
  227. #endif
  228.  
  229.     return( -1 );
  230. }
  231.  
  232. /*
  233.  * Like memcmp, but case-insensitive and always returns -1 if different
  234.  */
  235. static int x509_memcasecmp( const void *s1, const void *s2, size_t len )
  236. {
  237.     size_t i;
  238.     unsigned char diff;
  239.     const unsigned char *n1 = s1, *n2 = s2;
  240.  
  241.     for( i = 0; i < len; i++ )
  242.     {
  243.         diff = n1[i] ^ n2[i];
  244.  
  245.         if( diff == 0 )
  246.             continue;
  247.  
  248.         if( diff == 32 &&
  249.             ( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||
  250.               ( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )
  251.         {
  252.             continue;
  253.         }
  254.  
  255.         return( -1 );
  256.     }
  257.  
  258.     return( 0 );
  259. }
  260.  
  261. /*
  262.  * Return 0 if name matches wildcard, -1 otherwise
  263.  */
  264. static int x509_check_wildcard( const char *cn, const mbedtls_x509_buf *name )
  265. {
  266.     size_t i;
  267.     size_t cn_idx = 0, cn_len = strlen( cn );
  268.  
  269.     /* We can't have a match if there is no wildcard to match */
  270.     if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' )
  271.         return( -1 );
  272.  
  273.     for( i = 0; i < cn_len; ++i )
  274.     {
  275.         if( cn[i] == '.' )
  276.         {
  277.             cn_idx = i;
  278.             break;
  279.         }
  280.     }
  281.  
  282.     if( cn_idx == 0 )
  283.         return( -1 );
  284.  
  285.     if( cn_len - cn_idx == name->len - 1 &&
  286.         x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
  287.     {
  288.         return( 0 );
  289.     }
  290.  
  291.     return( -1 );
  292. }
  293.  
  294. /*
  295.  * Compare two X.509 strings, case-insensitive, and allowing for some encoding
  296.  * variations (but not all).
  297.  *
  298.  * Return 0 if equal, -1 otherwise.
  299.  */
  300. static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b )
  301. {
  302.     if( a->tag == b->tag &&
  303.         a->len == b->len &&
  304.         memcmp( a->p, b->p, b->len ) == 0 )
  305.     {
  306.         return( 0 );
  307.     }
  308.  
  309.     if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
  310.         ( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
  311.         a->len == b->len &&
  312.         x509_memcasecmp( a->p, b->p, b->len ) == 0 )
  313.     {
  314.         return( 0 );
  315.     }
  316.  
  317.     return( -1 );
  318. }
  319.  
  320. /*
  321.  * Compare two X.509 Names (aka rdnSequence).
  322.  *
  323.  * See RFC 5280 section 7.1, though we don't implement the whole algorithm:
  324.  * we sometimes return unequal when the full algorithm would return equal,
  325.  * but never the other way. (In particular, we don't do Unicode normalisation
  326.  * or space folding.)
  327.  *
  328.  * Return 0 if equal, -1 otherwise.
  329.  */
  330. static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b )
  331. {
  332.     /* Avoid recursion, it might not be optimised by the compiler */
  333.     while( a != NULL || b != NULL )
  334.     {
  335.         if( a == NULL || b == NULL )
  336.             return( -1 );
  337.  
  338.         /* type */
  339.         if( a->oid.tag != b->oid.tag ||
  340.             a->oid.len != b->oid.len ||
  341.             memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )
  342.         {
  343.             return( -1 );
  344.         }
  345.  
  346.         /* value */
  347.         if( x509_string_cmp( &a->val, &b->val ) != 0 )
  348.             return( -1 );
  349.  
  350.         /* structure of the list of sets */
  351.         if( a->next_merged != b->next_merged )
  352.             return( -1 );
  353.  
  354.         a = a->next;
  355.         b = b->next;
  356.     }
  357.  
  358.     /* a == NULL == b */
  359.     return( 0 );
  360. }
  361.  
  362. /*
  363.  * Reset (init or clear) a verify_chain
  364.  */
  365. static void x509_crt_verify_chain_reset(
  366.     mbedtls_x509_crt_verify_chain *ver_chain )
  367. {
  368.     size_t i;
  369.  
  370.     for( i = 0; i < MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE; i++ )
  371.     {
  372.         ver_chain->items[i].crt = NULL;
  373.         ver_chain->items[i].flags = (uint32_t) -1;
  374.     }
  375.  
  376.     ver_chain->len = 0;
  377. }
  378.  
  379. /*
  380.  *  Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
  381.  */
  382. static int x509_get_version( unsigned char **p,
  383.                              const unsigned char *end,
  384.                              int *ver )
  385. {
  386.     int ret;
  387.     size_t len;
  388.  
  389.     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
  390.             MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) != 0 )
  391.     {
  392.         if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
  393.         {
  394.             *ver = 0;
  395.             return( 0 );
  396.         }
  397.  
  398.         return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
  399.     }
  400.  
  401.     end = *p + len;
  402.  
  403.     if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 )
  404.         return( MBEDTLS_ERR_X509_INVALID_VERSION + ret );
  405.  
  406.     if( *p != end )
  407.         return( MBEDTLS_ERR_X509_INVALID_VERSION +
  408.                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  409.  
  410.     return( 0 );
  411. }
  412.  
  413. /*
  414.  *  Validity ::= SEQUENCE {
  415.  *       notBefore      Time,
  416.  *       notAfter       Time }
  417.  */
  418. static int x509_get_dates( unsigned char **p,
  419.                            const unsigned char *end,
  420.                            mbedtls_x509_time *from,
  421.                            mbedtls_x509_time *to )
  422. {
  423.     int ret;
  424.     size_t len;
  425.  
  426.     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
  427.             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  428.         return( MBEDTLS_ERR_X509_INVALID_DATE + ret );
  429.  
  430.     end = *p + len;
  431.  
  432.     if( ( ret = mbedtls_x509_get_time( p, end, from ) ) != 0 )
  433.         return( ret );
  434.  
  435.     if( ( ret = mbedtls_x509_get_time( p, end, to ) ) != 0 )
  436.         return( ret );
  437.  
  438.     if( *p != end )
  439.         return( MBEDTLS_ERR_X509_INVALID_DATE +
  440.                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  441.  
  442.     return( 0 );
  443. }
  444.  
  445. /*
  446.  * X.509 v2/v3 unique identifier (not parsed)
  447.  */
  448. static int x509_get_uid( unsigned char **p,
  449.                          const unsigned char *end,
  450.                          mbedtls_x509_buf *uid, int n )
  451. {
  452.     int ret;
  453.  
  454.     if( *p == end )
  455.         return( 0 );
  456.  
  457.     uid->tag = **p;
  458.  
  459.     if( ( ret = mbedtls_asn1_get_tag( p, end, &uid->len,
  460.             MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | n ) ) != 0 )
  461.     {
  462.         if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
  463.             return( 0 );
  464.  
  465.         return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
  466.     }
  467.  
  468.     uid->p = *p;
  469.     *p += uid->len;
  470.  
  471.     return( 0 );
  472. }
  473.  
  474. static int x509_get_basic_constraints( unsigned char **p,
  475.                                        const unsigned char *end,
  476.                                        int *ca_istrue,
  477.                                        int *max_pathlen )
  478. {
  479.     int ret;
  480.     size_t len;
  481.  
  482.     /*
  483.      * BasicConstraints ::= SEQUENCE {
  484.      *      cA                      BOOLEAN DEFAULT FALSE,
  485.      *      pathLenConstraint       INTEGER (0..MAX) OPTIONAL }
  486.      */
  487.     *ca_istrue = 0; /* DEFAULT FALSE */
  488.     *max_pathlen = 0; /* endless */
  489.  
  490.     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
  491.             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  492.         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  493.  
  494.     if( *p == end )
  495.         return( 0 );
  496.  
  497.     if( ( ret = mbedtls_asn1_get_bool( p, end, ca_istrue ) ) != 0 )
  498.     {
  499.         if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
  500.             ret = mbedtls_asn1_get_int( p, end, ca_istrue );
  501.  
  502.         if( ret != 0 )
  503.             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  504.  
  505.         if( *ca_istrue != 0 )
  506.             *ca_istrue = 1;
  507.     }
  508.  
  509.     if( *p == end )
  510.         return( 0 );
  511.  
  512.     if( ( ret = mbedtls_asn1_get_int( p, end, max_pathlen ) ) != 0 )
  513.         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  514.  
  515.     if( *p != end )
  516.         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  517.                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  518.  
  519.     (*max_pathlen)++;
  520.  
  521.     return( 0 );
  522. }
  523.  
  524. static int x509_get_ns_cert_type( unsigned char **p,
  525.                                        const unsigned char *end,
  526.                                        unsigned char *ns_cert_type)
  527. {
  528.     int ret;
  529.     mbedtls_x509_bitstring bs = { 0, 0, NULL };
  530.  
  531.     if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
  532.         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  533.  
  534.     if( bs.len != 1 )
  535.         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  536.                 MBEDTLS_ERR_ASN1_INVALID_LENGTH );
  537.  
  538.     /* Get actual bitstring */
  539.     *ns_cert_type = *bs.p;
  540.     return( 0 );
  541. }
  542.  
  543. static int x509_get_key_usage( unsigned char **p,
  544.                                const unsigned char *end,
  545.                                unsigned int *key_usage)
  546. {
  547.     int ret;
  548.     size_t i;
  549.     mbedtls_x509_bitstring bs = { 0, 0, NULL };
  550.  
  551.     if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
  552.         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  553.  
  554.     if( bs.len < 1 )
  555.         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  556.                 MBEDTLS_ERR_ASN1_INVALID_LENGTH );
  557.  
  558.     /* Get actual bitstring */
  559.     *key_usage = 0;
  560.     for( i = 0; i < bs.len && i < sizeof( unsigned int ); i++ )
  561.     {
  562.         *key_usage |= (unsigned int) bs.p[i] << (8*i);
  563.     }
  564.  
  565.     return( 0 );
  566. }
  567.  
  568. /*
  569.  * ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
  570.  *
  571.  * KeyPurposeId ::= OBJECT IDENTIFIER
  572.  */
  573. static int x509_get_ext_key_usage( unsigned char **p,
  574.                                const unsigned char *end,
  575.                                mbedtls_x509_sequence *ext_key_usage)
  576. {
  577.     int ret;
  578.  
  579.     if( ( ret = mbedtls_asn1_get_sequence_of( p, end, ext_key_usage, MBEDTLS_ASN1_OID ) ) != 0 )
  580.         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  581.  
  582.     /* Sequence length must be >= 1 */
  583.     if( ext_key_usage->buf.p == NULL )
  584.         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  585.                 MBEDTLS_ERR_ASN1_INVALID_LENGTH );
  586.  
  587.     return( 0 );
  588. }
  589.  
  590. /*
  591.  * SubjectAltName ::= GeneralNames
  592.  *
  593.  * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
  594.  *
  595.  * GeneralName ::= CHOICE {
  596.  *      otherName                       [0]     OtherName,
  597.  *      rfc822Name                      [1]     IA5String,
  598.  *      dNSName                         [2]     IA5String,
  599.  *      x400Address                     [3]     ORAddress,
  600.  *      directoryName                   [4]     Name,
  601.  *      ediPartyName                    [5]     EDIPartyName,
  602.  *      uniformResourceIdentifier       [6]     IA5String,
  603.  *      iPAddress                       [7]     OCTET STRING,
  604.  *      registeredID                    [8]     OBJECT IDENTIFIER }
  605.  *
  606.  * OtherName ::= SEQUENCE {
  607.  *      type-id    OBJECT IDENTIFIER,
  608.  *      value      [0] EXPLICIT ANY DEFINED BY type-id }
  609.  *
  610.  * EDIPartyName ::= SEQUENCE {
  611.  *      nameAssigner            [0]     DirectoryString OPTIONAL,
  612.  *      partyName               [1]     DirectoryString }
  613.  *
  614.  * NOTE: we only parse and use dNSName at this point.
  615.  */
  616. static int x509_get_subject_alt_name( unsigned char **p,
  617.                                       const unsigned char *end,
  618.                                       mbedtls_x509_sequence *subject_alt_name )
  619. {
  620.     int ret;
  621.     size_t len, tag_len;
  622.     mbedtls_asn1_buf *buf;
  623.     unsigned char tag;
  624.     mbedtls_asn1_sequence *cur = subject_alt_name;
  625.  
  626.     /* Get main sequence tag */
  627.     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
  628.             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  629.         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  630.  
  631.     if( *p + len != end )
  632.         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  633.                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  634.  
  635.     while( *p < end )
  636.     {
  637.         if( ( end - *p ) < 1 )
  638.             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  639.                     MBEDTLS_ERR_ASN1_OUT_OF_DATA );
  640.  
  641.         tag = **p;
  642.         (*p)++;
  643.         if( ( ret = mbedtls_asn1_get_len( p, end, &tag_len ) ) != 0 )
  644.             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  645.  
  646.         if( ( tag & MBEDTLS_ASN1_TAG_CLASS_MASK ) !=
  647.                 MBEDTLS_ASN1_CONTEXT_SPECIFIC )
  648.         {
  649.             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  650.                     MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
  651.         }
  652.  
  653.         /* Skip everything but DNS name */
  654.         if( tag != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2 ) )
  655.         {
  656.             *p += tag_len;
  657.             continue;
  658.         }
  659.  
  660.         /* Allocate and assign next pointer */
  661.         if( cur->buf.p != NULL )
  662.         {
  663.             if( cur->next != NULL )
  664.                 return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
  665.  
  666.             cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) );
  667.  
  668.             if( cur->next == NULL )
  669.                 return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  670.                         MBEDTLS_ERR_ASN1_ALLOC_FAILED );
  671.  
  672.             cur = cur->next;
  673.         }
  674.  
  675.         buf = &(cur->buf);
  676.         buf->tag = tag;
  677.         buf->p = *p;
  678.         buf->len = tag_len;
  679.         *p += buf->len;
  680.     }
  681.  
  682.     /* Set final sequence entry's next pointer to NULL */
  683.     cur->next = NULL;
  684.  
  685.     if( *p != end )
  686.         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  687.                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  688.  
  689.     return( 0 );
  690. }
  691.  
  692. /*
  693.  * X.509 v3 extensions
  694.  *
  695.  */
  696. static int x509_get_crt_ext( unsigned char **p,
  697.                              const unsigned char *end,
  698.                              mbedtls_x509_crt *crt )
  699. {
  700.     int ret;
  701.     size_t len;
  702.     unsigned char *end_ext_data, *end_ext_octet;
  703.  
  704.     if( *p == end )
  705.         return( 0 );
  706.  
  707.     if( ( ret = mbedtls_x509_get_ext( p, end, &crt->v3_ext, 3 ) ) != 0 )
  708.         return( ret );
  709.  
  710.     end = crt->v3_ext.p + crt->v3_ext.len;
  711.     while( *p < end )
  712.     {
  713.         /*
  714.          * Extension  ::=  SEQUENCE  {
  715.          *      extnID      OBJECT IDENTIFIER,
  716.          *      critical    BOOLEAN DEFAULT FALSE,
  717.          *      extnValue   OCTET STRING  }
  718.          */
  719.         mbedtls_x509_buf extn_oid = {0, 0, NULL};
  720.         int is_critical = 0; /* DEFAULT FALSE */
  721.         int ext_type = 0;
  722.  
  723.         if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
  724.                 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  725.             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  726.  
  727.         end_ext_data = *p + len;
  728.  
  729.         /* Get extension ID */
  730.         if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &extn_oid.len,
  731.                                           MBEDTLS_ASN1_OID ) ) != 0 )
  732.             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  733.  
  734.         extn_oid.tag = MBEDTLS_ASN1_OID;
  735.         extn_oid.p = *p;
  736.         *p += extn_oid.len;
  737.  
  738.         /* Get optional critical */
  739.         if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 &&
  740.             ( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) )
  741.             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  742.  
  743.         /* Data should be octet string type */
  744.         if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len,
  745.                 MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
  746.             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
  747.  
  748.         end_ext_octet = *p + len;
  749.  
  750.         if( end_ext_octet != end_ext_data )
  751.             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  752.                     MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  753.  
  754.         /*
  755.          * Detect supported extensions
  756.          */
  757.         ret = mbedtls_oid_get_x509_ext_type( &extn_oid, &ext_type );
  758.  
  759.         if( ret != 0 )
  760.         {
  761.             /* No parser found, skip extension */
  762.             *p = end_ext_octet;
  763.  
  764. #if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION)
  765.             if( is_critical )
  766.             {
  767.                 /* Data is marked as critical: fail */
  768.                 return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  769.                         MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
  770.             }
  771. #endif
  772.             continue;
  773.         }
  774.  
  775.         /* Forbid repeated extensions */
  776.         if( ( crt->ext_types & ext_type ) != 0 )
  777.             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
  778.  
  779.         crt->ext_types |= ext_type;
  780.  
  781.         switch( ext_type )
  782.         {
  783.         case MBEDTLS_X509_EXT_BASIC_CONSTRAINTS:
  784.             /* Parse basic constraints */
  785.             if( ( ret = x509_get_basic_constraints( p, end_ext_octet,
  786.                     &crt->ca_istrue, &crt->max_pathlen ) ) != 0 )
  787.                 return( ret );
  788.             break;
  789.  
  790.         case MBEDTLS_X509_EXT_KEY_USAGE:
  791.             /* Parse key usage */
  792.             if( ( ret = x509_get_key_usage( p, end_ext_octet,
  793.                     &crt->key_usage ) ) != 0 )
  794.                 return( ret );
  795.             break;
  796.  
  797.         case MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE:
  798.             /* Parse extended key usage */
  799.             if( ( ret = x509_get_ext_key_usage( p, end_ext_octet,
  800.                     &crt->ext_key_usage ) ) != 0 )
  801.                 return( ret );
  802.             break;
  803.  
  804.         case MBEDTLS_X509_EXT_SUBJECT_ALT_NAME:
  805.             /* Parse subject alt name */
  806.             if( ( ret = x509_get_subject_alt_name( p, end_ext_octet,
  807.                     &crt->subject_alt_names ) ) != 0 )
  808.                 return( ret );
  809.             break;
  810.  
  811.         case MBEDTLS_X509_EXT_NS_CERT_TYPE:
  812.             /* Parse netscape certificate type */
  813.             if( ( ret = x509_get_ns_cert_type( p, end_ext_octet,
  814.                     &crt->ns_cert_type ) ) != 0 )
  815.                 return( ret );
  816.             break;
  817.  
  818.         default:
  819.             return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );
  820.         }
  821.     }
  822.  
  823.     if( *p != end )
  824.         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
  825.                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  826.  
  827.     return( 0 );
  828. }
  829.  
  830. /*
  831.  * Parse and fill a single X.509 certificate in DER format
  832.  */
  833. static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char *buf,
  834.                                     size_t buflen )
  835. {
  836.     int ret;
  837.     size_t len;
  838.     unsigned char *p, *end, *crt_end;
  839.     mbedtls_x509_buf sig_params1, sig_params2, sig_oid2;
  840.  
  841.     memset( &sig_params1, 0, sizeof( mbedtls_x509_buf ) );
  842.     memset( &sig_params2, 0, sizeof( mbedtls_x509_buf ) );
  843.     memset( &sig_oid2, 0, sizeof( mbedtls_x509_buf ) );
  844.  
  845.     /*
  846.      * Check for valid input
  847.      */
  848.     if( crt == NULL || buf == NULL )
  849.         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  850.  
  851.     // Use the original buffer until we figure out actual length
  852.     p = (unsigned char*) buf;
  853.     len = buflen;
  854.     end = p + len;
  855.  
  856.     /*
  857.      * Certificate  ::=  SEQUENCE  {
  858.      *      tbsCertificate       TBSCertificate,
  859.      *      signatureAlgorithm   AlgorithmIdentifier,
  860.      *      signatureValue       BIT STRING  }
  861.      */
  862.     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
  863.             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  864.     {
  865.         mbedtls_x509_crt_free( crt );
  866.         return( MBEDTLS_ERR_X509_INVALID_FORMAT );
  867.     }
  868.  
  869.     if( len > (size_t) ( end - p ) )
  870.     {
  871.         mbedtls_x509_crt_free( crt );
  872.         return( MBEDTLS_ERR_X509_INVALID_FORMAT +
  873.                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  874.     }
  875.     crt_end = p + len;
  876.  
  877.     // Create and populate a new buffer for the raw field
  878.     crt->raw.len = crt_end - buf;
  879.     crt->raw.p = p = mbedtls_calloc( 1, crt->raw.len );
  880.     if( p == NULL )
  881.         return( MBEDTLS_ERR_X509_ALLOC_FAILED );
  882.  
  883.     memcpy( p, buf, crt->raw.len );
  884.  
  885.     // Direct pointers to the new buffer
  886.     p += crt->raw.len - len;
  887.     end = crt_end = p + len;
  888.  
  889.     /*
  890.      * TBSCertificate  ::=  SEQUENCE  {
  891.      */
  892.     crt->tbs.p = p;
  893.  
  894.     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
  895.             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  896.     {
  897.         mbedtls_x509_crt_free( crt );
  898.         return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
  899.     }
  900.  
  901.     end = p + len;
  902.     crt->tbs.len = end - crt->tbs.p;
  903.  
  904.     /*
  905.      * Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
  906.      *
  907.      * CertificateSerialNumber  ::=  INTEGER
  908.      *
  909.      * signature            AlgorithmIdentifier
  910.      */
  911.     if( ( ret = x509_get_version(  &p, end, &crt->version  ) ) != 0 ||
  912.         ( ret = mbedtls_x509_get_serial(   &p, end, &crt->serial   ) ) != 0 ||
  913.         ( ret = mbedtls_x509_get_alg(      &p, end, &crt->sig_oid,
  914.                                             &sig_params1 ) ) != 0 )
  915.     {
  916.         mbedtls_x509_crt_free( crt );
  917.         return( ret );
  918.     }
  919.  
  920.     if( crt->version < 0 || crt->version > 2 )
  921.     {
  922.         mbedtls_x509_crt_free( crt );
  923.         return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );
  924.     }
  925.  
  926.     crt->version++;
  927.  
  928.     if( ( ret = mbedtls_x509_get_sig_alg( &crt->sig_oid, &sig_params1,
  929.                                   &crt->sig_md, &crt->sig_pk,
  930.                                   &crt->sig_opts ) ) != 0 )
  931.     {
  932.         mbedtls_x509_crt_free( crt );
  933.         return( ret );
  934.     }
  935.  
  936.     /*
  937.      * issuer               Name
  938.      */
  939.     crt->issuer_raw.p = p;
  940.  
  941.     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
  942.             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  943.     {
  944.         mbedtls_x509_crt_free( crt );
  945.         return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
  946.     }
  947.  
  948.     if( ( ret = mbedtls_x509_get_name( &p, p + len, &crt->issuer ) ) != 0 )
  949.     {
  950.         mbedtls_x509_crt_free( crt );
  951.         return( ret );
  952.     }
  953.  
  954.     crt->issuer_raw.len = p - crt->issuer_raw.p;
  955.  
  956.     /*
  957.      * Validity ::= SEQUENCE {
  958.      *      notBefore      Time,
  959.      *      notAfter       Time }
  960.      *
  961.      */
  962.     if( ( ret = x509_get_dates( &p, end, &crt->valid_from,
  963.                                          &crt->valid_to ) ) != 0 )
  964.     {
  965.         mbedtls_x509_crt_free( crt );
  966.         return( ret );
  967.     }
  968.  
  969.     /*
  970.      * subject              Name
  971.      */
  972.     crt->subject_raw.p = p;
  973.  
  974.     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
  975.             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
  976.     {
  977.         mbedtls_x509_crt_free( crt );
  978.         return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
  979.     }
  980.  
  981.     if( len && ( ret = mbedtls_x509_get_name( &p, p + len, &crt->subject ) ) != 0 )
  982.     {
  983.         mbedtls_x509_crt_free( crt );
  984.         return( ret );
  985.     }
  986.  
  987.     crt->subject_raw.len = p - crt->subject_raw.p;
  988.  
  989.     /*
  990.      * SubjectPublicKeyInfo
  991.      */
  992.     if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &crt->pk ) ) != 0 )
  993.     {
  994.         mbedtls_x509_crt_free( crt );
  995.         return( ret );
  996.     }
  997.  
  998.     /*
  999.      *  issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
  1000.      *                       -- If present, version shall be v2 or v3
  1001.      *  subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,
  1002.      *                       -- If present, version shall be v2 or v3
  1003.      *  extensions      [3]  EXPLICIT Extensions OPTIONAL
  1004.      *                       -- If present, version shall be v3
  1005.      */
  1006.     if( crt->version == 2 || crt->version == 3 )
  1007.     {
  1008.         ret = x509_get_uid( &p, end, &crt->issuer_id,  1 );
  1009.         if( ret != 0 )
  1010.         {
  1011.             mbedtls_x509_crt_free( crt );
  1012.             return( ret );
  1013.         }
  1014.     }
  1015.  
  1016.     if( crt->version == 2 || crt->version == 3 )
  1017.     {
  1018.         ret = x509_get_uid( &p, end, &crt->subject_id,  2 );
  1019.         if( ret != 0 )
  1020.         {
  1021.             mbedtls_x509_crt_free( crt );
  1022.             return( ret );
  1023.         }
  1024.     }
  1025.  
  1026. #if !defined(MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3)
  1027.     if( crt->version == 3 )
  1028. #endif
  1029.     {
  1030.         ret = x509_get_crt_ext( &p, end, crt );
  1031.         if( ret != 0 )
  1032.         {
  1033.             mbedtls_x509_crt_free( crt );
  1034.             return( ret );
  1035.         }
  1036.     }
  1037.  
  1038.     if( p != end )
  1039.     {
  1040.         mbedtls_x509_crt_free( crt );
  1041.         return( MBEDTLS_ERR_X509_INVALID_FORMAT +
  1042.                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  1043.     }
  1044.  
  1045.     end = crt_end;
  1046.  
  1047.     /*
  1048.      *  }
  1049.      *  -- end of TBSCertificate
  1050.      *
  1051.      *  signatureAlgorithm   AlgorithmIdentifier,
  1052.      *  signatureValue       BIT STRING
  1053.      */
  1054.     if( ( ret = mbedtls_x509_get_alg( &p, end, &sig_oid2, &sig_params2 ) ) != 0 )
  1055.     {
  1056.         mbedtls_x509_crt_free( crt );
  1057.         return( ret );
  1058.     }
  1059.  
  1060.     if( crt->sig_oid.len != sig_oid2.len ||
  1061.         memcmp( crt->sig_oid.p, sig_oid2.p, crt->sig_oid.len ) != 0 ||
  1062.         sig_params1.len != sig_params2.len ||
  1063.         ( sig_params1.len != 0 &&
  1064.           memcmp( sig_params1.p, sig_params2.p, sig_params1.len ) != 0 ) )
  1065.     {
  1066.         mbedtls_x509_crt_free( crt );
  1067.         return( MBEDTLS_ERR_X509_SIG_MISMATCH );
  1068.     }
  1069.  
  1070.     if( ( ret = mbedtls_x509_get_sig( &p, end, &crt->sig ) ) != 0 )
  1071.     {
  1072.         mbedtls_x509_crt_free( crt );
  1073.         return( ret );
  1074.     }
  1075.  
  1076.     if( p != end )
  1077.     {
  1078.         mbedtls_x509_crt_free( crt );
  1079.         return( MBEDTLS_ERR_X509_INVALID_FORMAT +
  1080.                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
  1081.     }
  1082.  
  1083.     return( 0 );
  1084. }
  1085.  
  1086. /*
  1087.  * Parse one X.509 certificate in DER format from a buffer and add them to a
  1088.  * chained list
  1089.  */
  1090. int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf,
  1091.                         size_t buflen )
  1092. {
  1093.     int ret;
  1094.     mbedtls_x509_crt *crt = chain, *prev = NULL;
  1095.  
  1096.     /*
  1097.      * Check for valid input
  1098.      */
  1099.     if( crt == NULL || buf == NULL )
  1100.         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  1101.  
  1102.     while( crt->version != 0 && crt->next != NULL )
  1103.     {
  1104.         prev = crt;
  1105.         crt = crt->next;
  1106.     }
  1107.  
  1108.     /*
  1109.      * Add new certificate on the end of the chain if needed.
  1110.      */
  1111.     if( crt->version != 0 && crt->next == NULL )
  1112.     {
  1113.         crt->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
  1114.  
  1115.         if( crt->next == NULL )
  1116.             return( MBEDTLS_ERR_X509_ALLOC_FAILED );
  1117.  
  1118.         prev = crt;
  1119.         mbedtls_x509_crt_init( crt->next );
  1120.         crt = crt->next;
  1121.     }
  1122.  
  1123.     if( ( ret = x509_crt_parse_der_core( crt, buf, buflen ) ) != 0 )
  1124.     {
  1125.         if( prev )
  1126.             prev->next = NULL;
  1127.  
  1128.         if( crt != chain )
  1129.             mbedtls_free( crt );
  1130.  
  1131.         return( ret );
  1132.     }
  1133.  
  1134.     return( 0 );
  1135. }
  1136.  
  1137. /*
  1138.  * Parse one or more PEM certificates from a buffer and add them to the chained
  1139.  * list
  1140.  */
  1141. int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen )
  1142. {
  1143. #if defined(MBEDTLS_PEM_PARSE_C)
  1144.     int success = 0, first_error = 0, total_failed = 0;
  1145.     int buf_format = MBEDTLS_X509_FORMAT_DER;
  1146. #endif
  1147.  
  1148.     /*
  1149.      * Check for valid input
  1150.      */
  1151.     if( chain == NULL || buf == NULL )
  1152.         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  1153.  
  1154.     /*
  1155.      * Determine buffer content. Buffer contains either one DER certificate or
  1156.      * one or more PEM certificates.
  1157.      */
  1158. #if defined(MBEDTLS_PEM_PARSE_C)
  1159.     if( buflen != 0 && buf[buflen - 1] == '\0' &&
  1160.         strstr( (const char *) buf, "-----BEGIN CERTIFICATE-----" ) != NULL )
  1161.     {
  1162.         buf_format = MBEDTLS_X509_FORMAT_PEM;
  1163.     }
  1164.  
  1165.     if( buf_format == MBEDTLS_X509_FORMAT_DER )
  1166.         return mbedtls_x509_crt_parse_der( chain, buf, buflen );
  1167. #else
  1168.     return mbedtls_x509_crt_parse_der( chain, buf, buflen );
  1169. #endif
  1170.  
  1171. #if defined(MBEDTLS_PEM_PARSE_C)
  1172.     if( buf_format == MBEDTLS_X509_FORMAT_PEM )
  1173.     {
  1174.         int ret;
  1175.         mbedtls_pem_context pem;
  1176.  
  1177.         /* 1 rather than 0 since the terminating NULL byte is counted in */
  1178.         while( buflen > 1 )
  1179.         {
  1180.             size_t use_len;
  1181.             mbedtls_pem_init( &pem );
  1182.  
  1183.             /* If we get there, we know the string is null-terminated */
  1184.             ret = mbedtls_pem_read_buffer( &pem,
  1185.                            "-----BEGIN CERTIFICATE-----",
  1186.                            "-----END CERTIFICATE-----",
  1187.                            buf, NULL, 0, &use_len );
  1188.  
  1189.             if( ret == 0 )
  1190.             {
  1191.                 /*
  1192.                  * Was PEM encoded
  1193.                  */
  1194.                 buflen -= use_len;
  1195.                 buf += use_len;
  1196.             }
  1197.             else if( ret == MBEDTLS_ERR_PEM_BAD_INPUT_DATA )
  1198.             {
  1199.                 return( ret );
  1200.             }
  1201.             else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
  1202.             {
  1203.                 mbedtls_pem_free( &pem );
  1204.  
  1205.                 /*
  1206.                  * PEM header and footer were found
  1207.                  */
  1208.                 buflen -= use_len;
  1209.                 buf += use_len;
  1210.  
  1211.                 if( first_error == 0 )
  1212.                     first_error = ret;
  1213.  
  1214.                 total_failed++;
  1215.                 continue;
  1216.             }
  1217.             else
  1218.                 break;
  1219.  
  1220.             ret = mbedtls_x509_crt_parse_der( chain, pem.buf, pem.buflen );
  1221.  
  1222.             mbedtls_pem_free( &pem );
  1223.  
  1224.             if( ret != 0 )
  1225.             {
  1226.                 /*
  1227.                  * Quit parsing on a memory error
  1228.                  */
  1229.                 if( ret == MBEDTLS_ERR_X509_ALLOC_FAILED )
  1230.                     return( ret );
  1231.  
  1232.                 if( first_error == 0 )
  1233.                     first_error = ret;
  1234.  
  1235.                 total_failed++;
  1236.                 continue;
  1237.             }
  1238.  
  1239.             success = 1;
  1240.         }
  1241.     }
  1242.  
  1243.     if( success )
  1244.         return( total_failed );
  1245.     else if( first_error )
  1246.         return( first_error );
  1247.     else
  1248.         return( MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT );
  1249. #endif /* MBEDTLS_PEM_PARSE_C */
  1250. }
  1251.  
  1252. #if defined(MBEDTLS_FS_IO)
  1253. /*
  1254.  * Load one or more certificates and add them to the chained list
  1255.  */
  1256. int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path )
  1257. {
  1258.     int ret;
  1259.     size_t n;
  1260.     unsigned char *buf;
  1261.  
  1262.     if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )
  1263.         return( ret );
  1264.  
  1265.     ret = mbedtls_x509_crt_parse( chain, buf, n );
  1266.  
  1267.     mbedtls_platform_zeroize( buf, n );
  1268.     mbedtls_free( buf );
  1269.  
  1270.     return( ret );
  1271. }
  1272.  
  1273. int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )
  1274. {
  1275.     int ret = 0;
  1276. #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
  1277.     int w_ret;
  1278.     WCHAR szDir[MAX_PATH];
  1279.     char filename[MAX_PATH];
  1280.     char *p;
  1281.     size_t len = strlen( path );
  1282.  
  1283.     WIN32_FIND_DATAW file_data;
  1284.     HANDLE hFind;
  1285.  
  1286.     if( len > MAX_PATH - 3 )
  1287.         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  1288.  
  1289.     memset( szDir, 0, sizeof(szDir) );
  1290.     memset( filename, 0, MAX_PATH );
  1291.     memcpy( filename, path, len );
  1292.     filename[len++] = '\\';
  1293.     p = filename + len;
  1294.     filename[len++] = '*';
  1295.  
  1296.     w_ret = MultiByteToWideChar( CP_ACP, 0, filename, (int)len, szDir,
  1297.                                  MAX_PATH - 3 );
  1298.     if( w_ret == 0 )
  1299.         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  1300.  
  1301.     hFind = FindFirstFileW( szDir, &file_data );
  1302.     if( hFind == INVALID_HANDLE_VALUE )
  1303.         return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
  1304.  
  1305.     len = MAX_PATH - len;
  1306.     do
  1307.     {
  1308.         memset( p, 0, len );
  1309.  
  1310.         if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
  1311.             continue;
  1312.  
  1313.         w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName,
  1314.                                      lstrlenW( file_data.cFileName ),
  1315.                                      p, (int) len - 1,
  1316.                                      NULL, NULL );
  1317.         if( w_ret == 0 )
  1318.         {
  1319.             ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
  1320.             goto cleanup;
  1321.         }
  1322.  
  1323.         w_ret = mbedtls_x509_crt_parse_file( chain, filename );
  1324.         if( w_ret < 0 )
  1325.             ret++;
  1326.         else
  1327.             ret += w_ret;
  1328.     }
  1329.     while( FindNextFileW( hFind, &file_data ) != 0 );
  1330.  
  1331.     if( GetLastError() != ERROR_NO_MORE_FILES )
  1332.         ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
  1333.  
  1334. cleanup:
  1335.     FindClose( hFind );
  1336. #else /* _WIN32 */
  1337.     int t_ret;
  1338.     int snp_ret;
  1339.     struct stat sb;
  1340.     struct dirent *entry;
  1341.     char entry_name[MBEDTLS_X509_MAX_FILE_PATH_LEN];
  1342.     DIR *dir = opendir( path );
  1343.  
  1344.     if( dir == NULL )
  1345.         return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
  1346.  
  1347. #if defined(MBEDTLS_THREADING_C)
  1348.     if( ( ret = mbedtls_mutex_lock( &mbedtls_threading_readdir_mutex ) ) != 0 )
  1349.     {
  1350.         closedir( dir );
  1351.         return( ret );
  1352.     }
  1353. #endif /* MBEDTLS_THREADING_C */
  1354.  
  1355.     while( ( entry = readdir( dir ) ) != NULL )
  1356.     {
  1357.         snp_ret = mbedtls_snprintf( entry_name, sizeof entry_name,
  1358.                                     "%s/%s", path, entry->d_name );
  1359.  
  1360.         if( snp_ret < 0 || (size_t)snp_ret >= sizeof entry_name )
  1361.         {
  1362.             ret = MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
  1363.             goto cleanup;
  1364.         }
  1365.         else if( stat( entry_name, &sb ) == -1 )
  1366.         {
  1367.             ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
  1368.             goto cleanup;
  1369.         }
  1370.  
  1371.         if( !S_ISREG( sb.st_mode ) )
  1372.             continue;
  1373.  
  1374.         // Ignore parse errors
  1375.         //
  1376.         t_ret = mbedtls_x509_crt_parse_file( chain, entry_name );
  1377.         if( t_ret < 0 )
  1378.             ret++;
  1379.         else
  1380.             ret += t_ret;
  1381.     }
  1382.  
  1383. cleanup:
  1384.     closedir( dir );
  1385.  
  1386. #if defined(MBEDTLS_THREADING_C)
  1387.     if( mbedtls_mutex_unlock( &mbedtls_threading_readdir_mutex ) != 0 )
  1388.         ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR;
  1389. #endif /* MBEDTLS_THREADING_C */
  1390.  
  1391. #endif /* _WIN32 */
  1392.  
  1393.     return( ret );
  1394. }
  1395. #endif /* MBEDTLS_FS_IO */
  1396.  
  1397. static int x509_info_subject_alt_name( char **buf, size_t *size,
  1398.                                        const mbedtls_x509_sequence *subject_alt_name )
  1399. {
  1400.     size_t i;
  1401.     size_t n = *size;
  1402.     char *p = *buf;
  1403.     const mbedtls_x509_sequence *cur = subject_alt_name;
  1404.     const char *sep = "";
  1405.     size_t sep_len = 0;
  1406.  
  1407.     while( cur != NULL )
  1408.     {
  1409.         if( cur->buf.len + sep_len >= n )
  1410.         {
  1411.             *p = '\0';
  1412.             return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
  1413.         }
  1414.  
  1415.         n -= cur->buf.len + sep_len;
  1416.         for( i = 0; i < sep_len; i++ )
  1417.             *p++ = sep[i];
  1418.         for( i = 0; i < cur->buf.len; i++ )
  1419.             *p++ = cur->buf.p[i];
  1420.  
  1421.         sep = ", ";
  1422.         sep_len = 2;
  1423.  
  1424.         cur = cur->next;
  1425.     }
  1426.  
  1427.     *p = '\0';
  1428.  
  1429.     *size = n;
  1430.     *buf = p;
  1431.  
  1432.     return( 0 );
  1433. }
  1434.  
  1435. #define PRINT_ITEM(i)                           \
  1436.     {                                           \
  1437.         ret = mbedtls_snprintf( p, n, "%s" i, sep );    \
  1438.         MBEDTLS_X509_SAFE_SNPRINTF;                        \
  1439.         sep = ", ";                             \
  1440.     }
  1441.  
  1442. #define CERT_TYPE(type,name)                    \
  1443.     if( ns_cert_type & (type) )                 \
  1444.         PRINT_ITEM( name );
  1445.  
  1446. static int x509_info_cert_type( char **buf, size_t *size,
  1447.                                 unsigned char ns_cert_type )
  1448. {
  1449.     int ret;
  1450.     size_t n = *size;
  1451.     char *p = *buf;
  1452.     const char *sep = "";
  1453.  
  1454.     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT,         "SSL Client" );
  1455.     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER,         "SSL Server" );
  1456.     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL,              "Email" );
  1457.     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING,     "Object Signing" );
  1458.     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_RESERVED,           "Reserved" );
  1459.     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CA,             "SSL CA" );
  1460.     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA,           "Email CA" );
  1461.     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA,  "Object Signing CA" );
  1462.  
  1463.     *size = n;
  1464.     *buf = p;
  1465.  
  1466.     return( 0 );
  1467. }
  1468.  
  1469. #define KEY_USAGE(code,name)    \
  1470.     if( key_usage & (code) )    \
  1471.         PRINT_ITEM( name );
  1472.  
  1473. static int x509_info_key_usage( char **buf, size_t *size,
  1474.                                 unsigned int key_usage )
  1475. {
  1476.     int ret;
  1477.     size_t n = *size;
  1478.     char *p = *buf;
  1479.     const char *sep = "";
  1480.  
  1481.     KEY_USAGE( MBEDTLS_X509_KU_DIGITAL_SIGNATURE,    "Digital Signature" );
  1482.     KEY_USAGE( MBEDTLS_X509_KU_NON_REPUDIATION,      "Non Repudiation" );
  1483.     KEY_USAGE( MBEDTLS_X509_KU_KEY_ENCIPHERMENT,     "Key Encipherment" );
  1484.     KEY_USAGE( MBEDTLS_X509_KU_DATA_ENCIPHERMENT,    "Data Encipherment" );
  1485.     KEY_USAGE( MBEDTLS_X509_KU_KEY_AGREEMENT,        "Key Agreement" );
  1486.     KEY_USAGE( MBEDTLS_X509_KU_KEY_CERT_SIGN,        "Key Cert Sign" );
  1487.     KEY_USAGE( MBEDTLS_X509_KU_CRL_SIGN,             "CRL Sign" );
  1488.     KEY_USAGE( MBEDTLS_X509_KU_ENCIPHER_ONLY,        "Encipher Only" );
  1489.     KEY_USAGE( MBEDTLS_X509_KU_DECIPHER_ONLY,        "Decipher Only" );
  1490.  
  1491.     *size = n;
  1492.     *buf = p;
  1493.  
  1494.     return( 0 );
  1495. }
  1496.  
  1497. static int x509_info_ext_key_usage( char **buf, size_t *size,
  1498.                                     const mbedtls_x509_sequence *extended_key_usage )
  1499. {
  1500.     int ret;
  1501.     const char *desc;
  1502.     size_t n = *size;
  1503.     char *p = *buf;
  1504.     const mbedtls_x509_sequence *cur = extended_key_usage;
  1505.     const char *sep = "";
  1506.  
  1507.     while( cur != NULL )
  1508.     {
  1509.         if( mbedtls_oid_get_extended_key_usage( &cur->buf, &desc ) != 0 )
  1510.             desc = "???";
  1511.  
  1512.         ret = mbedtls_snprintf( p, n, "%s%s", sep, desc );
  1513.         MBEDTLS_X509_SAFE_SNPRINTF;
  1514.  
  1515.         sep = ", ";
  1516.  
  1517.         cur = cur->next;
  1518.     }
  1519.  
  1520.     *size = n;
  1521.     *buf = p;
  1522.  
  1523.     return( 0 );
  1524. }
  1525.  
  1526. /*
  1527.  * Return an informational string about the certificate.
  1528.  */
  1529. #define BEFORE_COLON    18
  1530. #define BC              "18"
  1531. int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,
  1532.                    const mbedtls_x509_crt *crt )
  1533. {
  1534.     int ret;
  1535.     size_t n;
  1536.     char *p;
  1537.     char key_size_str[BEFORE_COLON];
  1538.  
  1539.     p = buf;
  1540.     n = size;
  1541.  
  1542.     if( NULL == crt )
  1543.     {
  1544.         ret = mbedtls_snprintf( p, n, "\nCertificate is uninitialised!\n" );
  1545.         MBEDTLS_X509_SAFE_SNPRINTF;
  1546.  
  1547.         return( (int) ( size - n ) );
  1548.     }
  1549.  
  1550.     ret = mbedtls_snprintf( p, n, "%scert. version     : %d\n",
  1551.                                prefix, crt->version );
  1552.     MBEDTLS_X509_SAFE_SNPRINTF;
  1553.     ret = mbedtls_snprintf( p, n, "%sserial number     : ",
  1554.                                prefix );
  1555.     MBEDTLS_X509_SAFE_SNPRINTF;
  1556.  
  1557.     ret = mbedtls_x509_serial_gets( p, n, &crt->serial );
  1558.     MBEDTLS_X509_SAFE_SNPRINTF;
  1559.  
  1560.     ret = mbedtls_snprintf( p, n, "\n%sissuer name       : ", prefix );
  1561.     MBEDTLS_X509_SAFE_SNPRINTF;
  1562.     ret = mbedtls_x509_dn_gets( p, n, &crt->issuer  );
  1563.     MBEDTLS_X509_SAFE_SNPRINTF;
  1564.  
  1565.     ret = mbedtls_snprintf( p, n, "\n%ssubject name      : ", prefix );
  1566.     MBEDTLS_X509_SAFE_SNPRINTF;
  1567.     ret = mbedtls_x509_dn_gets( p, n, &crt->subject );
  1568.     MBEDTLS_X509_SAFE_SNPRINTF;
  1569.  
  1570.     ret = mbedtls_snprintf( p, n, "\n%sissued  on        : " \
  1571.                    "%04d-%02d-%02d %02d:%02d:%02d", prefix,
  1572.                    crt->valid_from.year, crt->valid_from.mon,
  1573.                    crt->valid_from.day,  crt->valid_from.hour,
  1574.                    crt->valid_from.min,  crt->valid_from.sec );
  1575.     MBEDTLS_X509_SAFE_SNPRINTF;
  1576.  
  1577.     ret = mbedtls_snprintf( p, n, "\n%sexpires on        : " \
  1578.                    "%04d-%02d-%02d %02d:%02d:%02d", prefix,
  1579.                    crt->valid_to.year, crt->valid_to.mon,
  1580.                    crt->valid_to.day,  crt->valid_to.hour,
  1581.                    crt->valid_to.min,  crt->valid_to.sec );
  1582.     MBEDTLS_X509_SAFE_SNPRINTF;
  1583.  
  1584.     ret = mbedtls_snprintf( p, n, "\n%ssigned using      : ", prefix );
  1585.     MBEDTLS_X509_SAFE_SNPRINTF;
  1586.  
  1587.     ret = mbedtls_x509_sig_alg_gets( p, n, &crt->sig_oid, crt->sig_pk,
  1588.                              crt->sig_md, crt->sig_opts );
  1589.     MBEDTLS_X509_SAFE_SNPRINTF;
  1590.  
  1591.     /* Key size */
  1592.     if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON,
  1593.                                       mbedtls_pk_get_name( &crt->pk ) ) ) != 0 )
  1594.     {
  1595.         return( ret );
  1596.     }
  1597.  
  1598.     ret = mbedtls_snprintf( p, n, "\n%s%-" BC "s: %d bits", prefix, key_size_str,
  1599.                           (int) mbedtls_pk_get_bitlen( &crt->pk ) );
  1600.     MBEDTLS_X509_SAFE_SNPRINTF;
  1601.  
  1602.     /*
  1603.      * Optional extensions
  1604.      */
  1605.  
  1606.     if( crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS )
  1607.     {
  1608.         ret = mbedtls_snprintf( p, n, "\n%sbasic constraints : CA=%s", prefix,
  1609.                         crt->ca_istrue ? "true" : "false" );
  1610.         MBEDTLS_X509_SAFE_SNPRINTF;
  1611.  
  1612.         if( crt->max_pathlen > 0 )
  1613.         {
  1614.             ret = mbedtls_snprintf( p, n, ", max_pathlen=%d", crt->max_pathlen - 1 );
  1615.             MBEDTLS_X509_SAFE_SNPRINTF;
  1616.         }
  1617.     }
  1618.  
  1619.     if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
  1620.     {
  1621.         ret = mbedtls_snprintf( p, n, "\n%ssubject alt name  : ", prefix );
  1622.         MBEDTLS_X509_SAFE_SNPRINTF;
  1623.  
  1624.         if( ( ret = x509_info_subject_alt_name( &p, &n,
  1625.                                             &crt->subject_alt_names ) ) != 0 )
  1626.             return( ret );
  1627.     }
  1628.  
  1629.     if( crt->ext_types & MBEDTLS_X509_EXT_NS_CERT_TYPE )
  1630.     {
  1631.         ret = mbedtls_snprintf( p, n, "\n%scert. type        : ", prefix );
  1632.         MBEDTLS_X509_SAFE_SNPRINTF;
  1633.  
  1634.         if( ( ret = x509_info_cert_type( &p, &n, crt->ns_cert_type ) ) != 0 )
  1635.             return( ret );
  1636.     }
  1637.  
  1638.     if( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE )
  1639.     {
  1640.         ret = mbedtls_snprintf( p, n, "\n%skey usage         : ", prefix );
  1641.         MBEDTLS_X509_SAFE_SNPRINTF;
  1642.  
  1643.         if( ( ret = x509_info_key_usage( &p, &n, crt->key_usage ) ) != 0 )
  1644.             return( ret );
  1645.     }
  1646.  
  1647.     if( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE )
  1648.     {
  1649.         ret = mbedtls_snprintf( p, n, "\n%sext key usage     : ", prefix );
  1650.         MBEDTLS_X509_SAFE_SNPRINTF;
  1651.  
  1652.         if( ( ret = x509_info_ext_key_usage( &p, &n,
  1653.                                              &crt->ext_key_usage ) ) != 0 )
  1654.             return( ret );
  1655.     }
  1656.  
  1657.     ret = mbedtls_snprintf( p, n, "\n" );
  1658.     MBEDTLS_X509_SAFE_SNPRINTF;
  1659.  
  1660.     return( (int) ( size - n ) );
  1661. }
  1662.  
  1663. struct x509_crt_verify_string {
  1664.     int code;
  1665.     const char *string;
  1666. };
  1667.  
  1668. static const struct x509_crt_verify_string x509_crt_verify_strings[] = {
  1669.     { MBEDTLS_X509_BADCERT_EXPIRED,       "The certificate validity has expired" },
  1670.     { MBEDTLS_X509_BADCERT_REVOKED,       "The certificate has been revoked (is on a CRL)" },
  1671.     { MBEDTLS_X509_BADCERT_CN_MISMATCH,   "The certificate Common Name (CN) does not match with the expected CN" },
  1672.     { MBEDTLS_X509_BADCERT_NOT_TRUSTED,   "The certificate is not correctly signed by the trusted CA" },
  1673.     { MBEDTLS_X509_BADCRL_NOT_TRUSTED,    "The CRL is not correctly signed by the trusted CA" },
  1674.     { MBEDTLS_X509_BADCRL_EXPIRED,        "The CRL is expired" },
  1675.     { MBEDTLS_X509_BADCERT_MISSING,       "Certificate was missing" },
  1676.     { MBEDTLS_X509_BADCERT_SKIP_VERIFY,   "Certificate verification was skipped" },
  1677.     { MBEDTLS_X509_BADCERT_OTHER,         "Other reason (can be used by verify callback)" },
  1678.     { MBEDTLS_X509_BADCERT_FUTURE,        "The certificate validity starts in the future" },
  1679.     { MBEDTLS_X509_BADCRL_FUTURE,         "The CRL is from the future" },
  1680.     { MBEDTLS_X509_BADCERT_KEY_USAGE,     "Usage does not match the keyUsage extension" },
  1681.     { MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, "Usage does not match the extendedKeyUsage extension" },
  1682.     { MBEDTLS_X509_BADCERT_NS_CERT_TYPE,  "Usage does not match the nsCertType extension" },
  1683.     { MBEDTLS_X509_BADCERT_BAD_MD,        "The certificate is signed with an unacceptable hash." },
  1684.     { MBEDTLS_X509_BADCERT_BAD_PK,        "The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
  1685.     { MBEDTLS_X509_BADCERT_BAD_KEY,       "The certificate is signed with an unacceptable key (eg bad curve, RSA too short)." },
  1686.     { MBEDTLS_X509_BADCRL_BAD_MD,         "The CRL is signed with an unacceptable hash." },
  1687.     { MBEDTLS_X509_BADCRL_BAD_PK,         "The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
  1688.     { MBEDTLS_X509_BADCRL_BAD_KEY,        "The CRL is signed with an unacceptable key (eg bad curve, RSA too short)." },
  1689.     { 0, NULL }
  1690. };
  1691.  
  1692. int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
  1693.                           uint32_t flags )
  1694. {
  1695.     int ret;
  1696.     const struct x509_crt_verify_string *cur;
  1697.     char *p = buf;
  1698.     size_t n = size;
  1699.  
  1700.     for( cur = x509_crt_verify_strings; cur->string != NULL ; cur++ )
  1701.     {
  1702.         if( ( flags & cur->code ) == 0 )
  1703.             continue;
  1704.  
  1705.         ret = mbedtls_snprintf( p, n, "%s%s\n", prefix, cur->string );
  1706.         MBEDTLS_X509_SAFE_SNPRINTF;
  1707.         flags ^= cur->code;
  1708.     }
  1709.  
  1710.     if( flags != 0 )
  1711.     {
  1712.         ret = mbedtls_snprintf( p, n, "%sUnknown reason "
  1713.                                        "(this should not happen)\n", prefix );
  1714.         MBEDTLS_X509_SAFE_SNPRINTF;
  1715.     }
  1716.  
  1717.     return( (int) ( size - n ) );
  1718. }
  1719.  
  1720. #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
  1721. int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
  1722.                                       unsigned int usage )
  1723. {
  1724.     unsigned int usage_must, usage_may;
  1725.     unsigned int may_mask = MBEDTLS_X509_KU_ENCIPHER_ONLY
  1726.                           | MBEDTLS_X509_KU_DECIPHER_ONLY;
  1727.  
  1728.     if( ( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) == 0 )
  1729.         return( 0 );
  1730.  
  1731.     usage_must = usage & ~may_mask;
  1732.  
  1733.     if( ( ( crt->key_usage & ~may_mask ) & usage_must ) != usage_must )
  1734.         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  1735.  
  1736.     usage_may = usage & may_mask;
  1737.  
  1738.     if( ( ( crt->key_usage & may_mask ) | usage_may ) != usage_may )
  1739.         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  1740.  
  1741.     return( 0 );
  1742. }
  1743. #endif
  1744.  
  1745. #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
  1746. int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
  1747.                                        const char *usage_oid,
  1748.                                        size_t usage_len )
  1749. {
  1750.     const mbedtls_x509_sequence *cur;
  1751.  
  1752.     /* Extension is not mandatory, absent means no restriction */
  1753.     if( ( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE ) == 0 )
  1754.         return( 0 );
  1755.  
  1756.     /*
  1757.      * Look for the requested usage (or wildcard ANY) in our list
  1758.      */
  1759.     for( cur = &crt->ext_key_usage; cur != NULL; cur = cur->next )
  1760.     {
  1761.         const mbedtls_x509_buf *cur_oid = &cur->buf;
  1762.  
  1763.         if( cur_oid->len == usage_len &&
  1764.             memcmp( cur_oid->p, usage_oid, usage_len ) == 0 )
  1765.         {
  1766.             return( 0 );
  1767.         }
  1768.  
  1769.         if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE, cur_oid ) == 0 )
  1770.             return( 0 );
  1771.     }
  1772.  
  1773.     return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
  1774. }
  1775. #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
  1776.  
  1777. #if defined(MBEDTLS_X509_CRL_PARSE_C)
  1778. /*
  1779.  * Return 1 if the certificate is revoked, or 0 otherwise.
  1780.  */
  1781. int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl )
  1782. {
  1783.     const mbedtls_x509_crl_entry *cur = &crl->entry;
  1784.  
  1785.     while( cur != NULL && cur->serial.len != 0 )
  1786.     {
  1787.         if( crt->serial.len == cur->serial.len &&
  1788.             memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 )
  1789.         {
  1790.             if( mbedtls_x509_time_is_past( &cur->revocation_date ) )
  1791.                 return( 1 );
  1792.         }
  1793.  
  1794.         cur = cur->next;
  1795.     }
  1796.  
  1797.     return( 0 );
  1798. }
  1799.  
  1800. /*
  1801.  * Check that the given certificate is not revoked according to the CRL.
  1802.  * Skip validation if no CRL for the given CA is present.
  1803.  */
  1804. static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
  1805.                                mbedtls_x509_crl *crl_list,
  1806.                                const mbedtls_x509_crt_profile *profile )
  1807. {
  1808.     int flags = 0;
  1809.     unsigned char hash[MBEDTLS_MD_MAX_SIZE];
  1810.     const mbedtls_md_info_t *md_info;
  1811.  
  1812.     if( ca == NULL )
  1813.         return( flags );
  1814.  
  1815.     while( crl_list != NULL )
  1816.     {
  1817.         if( crl_list->version == 0 ||
  1818.             x509_name_cmp( &crl_list->issuer, &ca->subject ) != 0 )
  1819.         {
  1820.             crl_list = crl_list->next;
  1821.             continue;
  1822.         }
  1823.  
  1824.         /*
  1825.          * Check if the CA is configured to sign CRLs
  1826.          */
  1827. #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
  1828.         if( mbedtls_x509_crt_check_key_usage( ca,
  1829.                                               MBEDTLS_X509_KU_CRL_SIGN ) != 0 )
  1830.         {
  1831.             flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
  1832.             break;
  1833.         }
  1834. #endif
  1835.  
  1836.         /*
  1837.          * Check if CRL is correctly signed by the trusted CA
  1838.          */
  1839.         if( x509_profile_check_md_alg( profile, crl_list->sig_md ) != 0 )
  1840.             flags |= MBEDTLS_X509_BADCRL_BAD_MD;
  1841.  
  1842.         if( x509_profile_check_pk_alg( profile, crl_list->sig_pk ) != 0 )
  1843.             flags |= MBEDTLS_X509_BADCRL_BAD_PK;
  1844.  
  1845.         md_info = mbedtls_md_info_from_type( crl_list->sig_md );
  1846.         if( mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash ) != 0 )
  1847.         {
  1848.             /* Note: this can't happen except after an internal error */
  1849.             flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
  1850.             break;
  1851.         }
  1852.  
  1853.         if( x509_profile_check_key( profile, &ca->pk ) != 0 )
  1854.             flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
  1855.  
  1856.         if( mbedtls_pk_verify_ext( crl_list->sig_pk, crl_list->sig_opts, &ca->pk,
  1857.                            crl_list->sig_md, hash, mbedtls_md_get_size( md_info ),
  1858.                            crl_list->sig.p, crl_list->sig.len ) != 0 )
  1859.         {
  1860.             flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
  1861.             break;
  1862.         }
  1863.  
  1864.         /*
  1865.          * Check for validity of CRL (Do not drop out)
  1866.          */
  1867.         if( mbedtls_x509_time_is_past( &crl_list->next_update ) )
  1868.             flags |= MBEDTLS_X509_BADCRL_EXPIRED;
  1869.  
  1870.         if( mbedtls_x509_time_is_future( &crl_list->this_update ) )
  1871.             flags |= MBEDTLS_X509_BADCRL_FUTURE;
  1872.  
  1873.         /*
  1874.          * Check if certificate is revoked
  1875.          */
  1876.         if( mbedtls_x509_crt_is_revoked( crt, crl_list ) )
  1877.         {
  1878.             flags |= MBEDTLS_X509_BADCERT_REVOKED;
  1879.             break;
  1880.         }
  1881.  
  1882.         crl_list = crl_list->next;
  1883.     }
  1884.  
  1885.     return( flags );
  1886. }
  1887. #endif /* MBEDTLS_X509_CRL_PARSE_C */
  1888.  
  1889. /*
  1890.  * Check the signature of a certificate by its parent
  1891.  */
  1892. static int x509_crt_check_signature( const mbedtls_x509_crt *child,
  1893.                                      mbedtls_x509_crt *parent,
  1894.                                      mbedtls_x509_crt_restart_ctx *rs_ctx )
  1895. {
  1896.     const mbedtls_md_info_t *md_info;
  1897.     unsigned char hash[MBEDTLS_MD_MAX_SIZE];
  1898.  
  1899.     md_info = mbedtls_md_info_from_type( child->sig_md );
  1900.     if( mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ) != 0 )
  1901.     {
  1902.         /* Note: this can't happen except after an internal error */
  1903.         return( -1 );
  1904.     }
  1905.  
  1906.     /* Skip expensive computation on obvious mismatch */
  1907.     if( ! mbedtls_pk_can_do( &parent->pk, child->sig_pk ) )
  1908.         return( -1 );
  1909.  
  1910. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  1911.     if( rs_ctx != NULL && child->sig_pk == MBEDTLS_PK_ECDSA )
  1912.     {
  1913.         return( mbedtls_pk_verify_restartable( &parent->pk,
  1914.                     child->sig_md, hash, mbedtls_md_get_size( md_info ),
  1915.                     child->sig.p, child->sig.len, &rs_ctx->pk ) );
  1916.     }
  1917. #else
  1918.     (void) rs_ctx;
  1919. #endif
  1920.  
  1921.     return( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk,
  1922.                 child->sig_md, hash, mbedtls_md_get_size( md_info ),
  1923.                 child->sig.p, child->sig.len ) );
  1924. }
  1925.  
  1926. /*
  1927.  * Check if 'parent' is a suitable parent (signing CA) for 'child'.
  1928.  * Return 0 if yes, -1 if not.
  1929.  *
  1930.  * top means parent is a locally-trusted certificate
  1931.  */
  1932. static int x509_crt_check_parent( const mbedtls_x509_crt *child,
  1933.                                   const mbedtls_x509_crt *parent,
  1934.                                   int top )
  1935. {
  1936.     int need_ca_bit;
  1937.  
  1938.     /* Parent must be the issuer */
  1939.     if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 )
  1940.         return( -1 );
  1941.  
  1942.     /* Parent must have the basicConstraints CA bit set as a general rule */
  1943.     need_ca_bit = 1;
  1944.  
  1945.     /* Exception: v1/v2 certificates that are locally trusted. */
  1946.     if( top && parent->version < 3 )
  1947.         need_ca_bit = 0;
  1948.  
  1949.     if( need_ca_bit && ! parent->ca_istrue )
  1950.         return( -1 );
  1951.  
  1952. #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
  1953.     if( need_ca_bit &&
  1954.         mbedtls_x509_crt_check_key_usage( parent, MBEDTLS_X509_KU_KEY_CERT_SIGN ) != 0 )
  1955.     {
  1956.         return( -1 );
  1957.     }
  1958. #endif
  1959.  
  1960.     return( 0 );
  1961. }
  1962.  
  1963. /*
  1964.  * Find a suitable parent for child in candidates, or return NULL.
  1965.  *
  1966.  * Here suitable is defined as:
  1967.  *  1. subject name matches child's issuer
  1968.  *  2. if necessary, the CA bit is set and key usage allows signing certs
  1969.  *  3. for trusted roots, the signature is correct
  1970.  *     (for intermediates, the signature is checked and the result reported)
  1971.  *  4. pathlen constraints are satisfied
  1972.  *
  1973.  * If there's a suitable candidate which is also time-valid, return the first
  1974.  * such. Otherwise, return the first suitable candidate (or NULL if there is
  1975.  * none).
  1976.  *
  1977.  * The rationale for this rule is that someone could have a list of trusted
  1978.  * roots with two versions on the same root with different validity periods.
  1979.  * (At least one user reported having such a list and wanted it to just work.)
  1980.  * The reason we don't just require time-validity is that generally there is
  1981.  * only one version, and if it's expired we want the flags to state that
  1982.  * rather than NOT_TRUSTED, as would be the case if we required it here.
  1983.  *
  1984.  * The rationale for rule 3 (signature for trusted roots) is that users might
  1985.  * have two versions of the same CA with different keys in their list, and the
  1986.  * way we select the correct one is by checking the signature (as we don't
  1987.  * rely on key identifier extensions). (This is one way users might choose to
  1988.  * handle key rollover, another relies on self-issued certs, see [SIRO].)
  1989.  *
  1990.  * Arguments:
  1991.  *  - [in] child: certificate for which we're looking for a parent
  1992.  *  - [in] candidates: chained list of potential parents
  1993.  *  - [out] r_parent: parent found (or NULL)
  1994.  *  - [out] r_signature_is_good: 1 if child signature by parent is valid, or 0
  1995.  *  - [in] top: 1 if candidates consists of trusted roots, ie we're at the top
  1996.  *         of the chain, 0 otherwise
  1997.  *  - [in] path_cnt: number of intermediates seen so far
  1998.  *  - [in] self_cnt: number of self-signed intermediates seen so far
  1999.  *         (will never be greater than path_cnt)
  2000.  *  - [in-out] rs_ctx: context for restarting operations
  2001.  *
  2002.  * Return value:
  2003.  *  - 0 on success
  2004.  *  - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise
  2005.  */
  2006. static int x509_crt_find_parent_in(
  2007.                         mbedtls_x509_crt *child,
  2008.                         mbedtls_x509_crt *candidates,
  2009.                         mbedtls_x509_crt **r_parent,
  2010.                         int *r_signature_is_good,
  2011.                         int top,
  2012.                         unsigned path_cnt,
  2013.                         unsigned self_cnt,
  2014.                         mbedtls_x509_crt_restart_ctx *rs_ctx )
  2015. {
  2016.     int ret;
  2017.     mbedtls_x509_crt *parent, *fallback_parent;
  2018.     int signature_is_good, fallback_signature_is_good;
  2019.  
  2020. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2021.     /* did we have something in progress? */
  2022.     if( rs_ctx != NULL && rs_ctx->parent != NULL )
  2023.     {
  2024.         /* restore saved state */
  2025.         parent = rs_ctx->parent;
  2026.         fallback_parent = rs_ctx->fallback_parent;
  2027.         fallback_signature_is_good = rs_ctx->fallback_signature_is_good;
  2028.  
  2029.         /* clear saved state */
  2030.         rs_ctx->parent = NULL;
  2031.         rs_ctx->fallback_parent = NULL;
  2032.         rs_ctx->fallback_signature_is_good = 0;
  2033.  
  2034.         /* resume where we left */
  2035.         goto check_signature;
  2036.     }
  2037. #endif
  2038.  
  2039.     fallback_parent = NULL;
  2040.     fallback_signature_is_good = 0;
  2041.  
  2042.     for( parent = candidates; parent != NULL; parent = parent->next )
  2043.     {
  2044.         /* basic parenting skills (name, CA bit, key usage) */
  2045.         if( x509_crt_check_parent( child, parent, top ) != 0 )
  2046.             continue;
  2047.  
  2048.         /* +1 because stored max_pathlen is 1 higher that the actual value */
  2049.         if( parent->max_pathlen > 0 &&
  2050.             (size_t) parent->max_pathlen < 1 + path_cnt - self_cnt )
  2051.         {
  2052.             continue;
  2053.         }
  2054.  
  2055.         /* Signature */
  2056. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2057. check_signature:
  2058. #endif
  2059.         ret = x509_crt_check_signature( child, parent, rs_ctx );
  2060.  
  2061. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2062.         if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
  2063.         {
  2064.             /* save state */
  2065.             rs_ctx->parent = parent;
  2066.             rs_ctx->fallback_parent = fallback_parent;
  2067.             rs_ctx->fallback_signature_is_good = fallback_signature_is_good;
  2068.  
  2069.             return( ret );
  2070.         }
  2071. #else
  2072.         (void) ret;
  2073. #endif
  2074.  
  2075.         signature_is_good = ret == 0;
  2076.         if( top && ! signature_is_good )
  2077.             continue;
  2078.  
  2079.         /* optional time check */
  2080.         if( mbedtls_x509_time_is_past( &parent->valid_to ) ||
  2081.             mbedtls_x509_time_is_future( &parent->valid_from ) )
  2082.         {
  2083.             if( fallback_parent == NULL )
  2084.             {
  2085.                 fallback_parent = parent;
  2086.                 fallback_signature_is_good = signature_is_good;
  2087.             }
  2088.  
  2089.             continue;
  2090.         }
  2091.  
  2092.         *r_parent = parent;
  2093.         *r_signature_is_good = signature_is_good;
  2094.  
  2095.         break;
  2096.     }
  2097.  
  2098.     if( parent == NULL )
  2099.     {
  2100.         *r_parent = fallback_parent;
  2101.         *r_signature_is_good = fallback_signature_is_good;
  2102.     }
  2103.  
  2104.     return( 0 );
  2105. }
  2106.  
  2107. /*
  2108.  * Find a parent in trusted CAs or the provided chain, or return NULL.
  2109.  *
  2110.  * Searches in trusted CAs first, and return the first suitable parent found
  2111.  * (see find_parent_in() for definition of suitable).
  2112.  *
  2113.  * Arguments:
  2114.  *  - [in] child: certificate for which we're looking for a parent, followed
  2115.  *         by a chain of possible intermediates
  2116.  *  - [in] trust_ca: list of locally trusted certificates
  2117.  *  - [out] parent: parent found (or NULL)
  2118.  *  - [out] parent_is_trusted: 1 if returned `parent` is trusted, or 0
  2119.  *  - [out] signature_is_good: 1 if child signature by parent is valid, or 0
  2120.  *  - [in] path_cnt: number of links in the chain so far (EE -> ... -> child)
  2121.  *  - [in] self_cnt: number of self-signed certs in the chain so far
  2122.  *         (will always be no greater than path_cnt)
  2123.  *  - [in-out] rs_ctx: context for restarting operations
  2124.  *
  2125.  * Return value:
  2126.  *  - 0 on success
  2127.  *  - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise
  2128.  */
  2129. static int x509_crt_find_parent(
  2130.                         mbedtls_x509_crt *child,
  2131.                         mbedtls_x509_crt *trust_ca,
  2132.                         mbedtls_x509_crt **parent,
  2133.                         int *parent_is_trusted,
  2134.                         int *signature_is_good,
  2135.                         unsigned path_cnt,
  2136.                         unsigned self_cnt,
  2137.                         mbedtls_x509_crt_restart_ctx *rs_ctx )
  2138. {
  2139.     int ret;
  2140.     mbedtls_x509_crt *search_list;
  2141.  
  2142.     *parent_is_trusted = 1;
  2143.  
  2144. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2145.     /* restore then clear saved state if we have some stored */
  2146.     if( rs_ctx != NULL && rs_ctx->parent_is_trusted != -1 )
  2147.     {
  2148.         *parent_is_trusted = rs_ctx->parent_is_trusted;
  2149.         rs_ctx->parent_is_trusted = -1;
  2150.     }
  2151. #endif
  2152.  
  2153.     while( 1 ) {
  2154.         search_list = *parent_is_trusted ? trust_ca : child->next;
  2155.  
  2156.         ret = x509_crt_find_parent_in( child, search_list,
  2157.                                        parent, signature_is_good,
  2158.                                        *parent_is_trusted,
  2159.                                        path_cnt, self_cnt, rs_ctx );
  2160.  
  2161. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2162.         if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
  2163.         {
  2164.             /* save state */
  2165.             rs_ctx->parent_is_trusted = *parent_is_trusted;
  2166.             return( ret );
  2167.         }
  2168. #else
  2169.         (void) ret;
  2170. #endif
  2171.  
  2172.         /* stop here if found or already in second iteration */
  2173.         if( *parent != NULL || *parent_is_trusted == 0 )
  2174.             break;
  2175.  
  2176.         /* prepare second iteration */
  2177.         *parent_is_trusted = 0;
  2178.     }
  2179.  
  2180.     /* extra precaution against mistakes in the caller */
  2181.     if( *parent == NULL )
  2182.     {
  2183.         *parent_is_trusted = 0;
  2184.         *signature_is_good = 0;
  2185.     }
  2186.  
  2187.     return( 0 );
  2188. }
  2189.  
  2190. /*
  2191.  * Check if an end-entity certificate is locally trusted
  2192.  *
  2193.  * Currently we require such certificates to be self-signed (actually only
  2194.  * check for self-issued as self-signatures are not checked)
  2195.  */
  2196. static int x509_crt_check_ee_locally_trusted(
  2197.                     mbedtls_x509_crt *crt,
  2198.                     mbedtls_x509_crt *trust_ca )
  2199. {
  2200.     mbedtls_x509_crt *cur;
  2201.  
  2202.     /* must be self-issued */
  2203.     if( x509_name_cmp( &crt->issuer, &crt->subject ) != 0 )
  2204.         return( -1 );
  2205.  
  2206.     /* look for an exact match with trusted cert */
  2207.     for( cur = trust_ca; cur != NULL; cur = cur->next )
  2208.     {
  2209.         if( crt->raw.len == cur->raw.len &&
  2210.             memcmp( crt->raw.p, cur->raw.p, crt->raw.len ) == 0 )
  2211.         {
  2212.             return( 0 );
  2213.         }
  2214.     }
  2215.  
  2216.     /* too bad */
  2217.     return( -1 );
  2218. }
  2219.  
  2220. /*
  2221.  * Build and verify a certificate chain
  2222.  *
  2223.  * Given a peer-provided list of certificates EE, C1, ..., Cn and
  2224.  * a list of trusted certs R1, ... Rp, try to build and verify a chain
  2225.  *      EE, Ci1, ... Ciq [, Rj]
  2226.  * such that every cert in the chain is a child of the next one,
  2227.  * jumping to a trusted root as early as possible.
  2228.  *
  2229.  * Verify that chain and return it with flags for all issues found.
  2230.  *
  2231.  * Special cases:
  2232.  * - EE == Rj -> return a one-element list containing it
  2233.  * - EE, Ci1, ..., Ciq cannot be continued with a trusted root
  2234.  *   -> return that chain with NOT_TRUSTED set on Ciq
  2235.  *
  2236.  * Tests for (aspects of) this function should include at least:
  2237.  * - trusted EE
  2238.  * - EE -> trusted root
  2239.  * - EE -> intermediate CA -> trusted root
  2240.  * - if relevant: EE untrusted
  2241.  * - if relevant: EE -> intermediate, untrusted
  2242.  * with the aspect under test checked at each relevant level (EE, int, root).
  2243.  * For some aspects longer chains are required, but usually length 2 is
  2244.  * enough (but length 1 is not in general).
  2245.  *
  2246.  * Arguments:
  2247.  *  - [in] crt: the cert list EE, C1, ..., Cn
  2248.  *  - [in] trust_ca: the trusted list R1, ..., Rp
  2249.  *  - [in] ca_crl, profile: as in verify_with_profile()
  2250.  *  - [out] ver_chain: the built and verified chain
  2251.  *      Only valid when return value is 0, may contain garbage otherwise!
  2252.  *      Restart note: need not be the same when calling again to resume.
  2253.  *  - [in-out] rs_ctx: context for restarting operations
  2254.  *
  2255.  * Return value:
  2256.  *  - non-zero if the chain could not be fully built and examined
  2257.  *  - 0 is the chain was successfully built and examined,
  2258.  *      even if it was found to be invalid
  2259.  */
  2260. static int x509_crt_verify_chain(
  2261.                 mbedtls_x509_crt *crt,
  2262.                 mbedtls_x509_crt *trust_ca,
  2263.                 mbedtls_x509_crl *ca_crl,
  2264.                 const mbedtls_x509_crt_profile *profile,
  2265.                 mbedtls_x509_crt_verify_chain *ver_chain,
  2266.                 mbedtls_x509_crt_restart_ctx *rs_ctx )
  2267. {
  2268.     /* Don't initialize any of those variables here, so that the compiler can
  2269.      * catch potential issues with jumping ahead when restarting */
  2270.     int ret;
  2271.     uint32_t *flags;
  2272.     mbedtls_x509_crt_verify_chain_item *cur;
  2273.     mbedtls_x509_crt *child;
  2274.     mbedtls_x509_crt *parent;
  2275.     int parent_is_trusted;
  2276.     int child_is_trusted;
  2277.     int signature_is_good;
  2278.     unsigned self_cnt;
  2279.  
  2280. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2281.     /* resume if we had an operation in progress */
  2282.     if( rs_ctx != NULL && rs_ctx->in_progress == x509_crt_rs_find_parent )
  2283.     {
  2284.         /* restore saved state */
  2285.         *ver_chain = rs_ctx->ver_chain; /* struct copy */
  2286.         self_cnt = rs_ctx->self_cnt;
  2287.  
  2288.         /* restore derived state */
  2289.         cur = &ver_chain->items[ver_chain->len - 1];
  2290.         child = cur->crt;
  2291.         flags = &cur->flags;
  2292.  
  2293.         goto find_parent;
  2294.     }
  2295. #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
  2296.  
  2297.     child = crt;
  2298.     self_cnt = 0;
  2299.     parent_is_trusted = 0;
  2300.     child_is_trusted = 0;
  2301.  
  2302.     while( 1 ) {
  2303.         /* Add certificate to the verification chain */
  2304.         cur = &ver_chain->items[ver_chain->len];
  2305.         cur->crt = child;
  2306.         cur->flags = 0;
  2307.         ver_chain->len++;
  2308.         flags = &cur->flags;
  2309.  
  2310.         /* Check time-validity (all certificates) */
  2311.         if( mbedtls_x509_time_is_past( &child->valid_to ) )
  2312.             *flags |= MBEDTLS_X509_BADCERT_EXPIRED;
  2313.  
  2314.         if( mbedtls_x509_time_is_future( &child->valid_from ) )
  2315.             *flags |= MBEDTLS_X509_BADCERT_FUTURE;
  2316.  
  2317.         /* Stop here for trusted roots (but not for trusted EE certs) */
  2318.         if( child_is_trusted )
  2319.             return( 0 );
  2320.  
  2321.         /* Check signature algorithm: MD & PK algs */
  2322.         if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
  2323.             *flags |= MBEDTLS_X509_BADCERT_BAD_MD;
  2324.  
  2325.         if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
  2326.             *flags |= MBEDTLS_X509_BADCERT_BAD_PK;
  2327.  
  2328.         /* Special case: EE certs that are locally trusted */
  2329.         if( ver_chain->len == 1 &&
  2330.             x509_crt_check_ee_locally_trusted( child, trust_ca ) == 0 )
  2331.         {
  2332.             return( 0 );
  2333.         }
  2334.  
  2335. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2336. find_parent:
  2337. #endif
  2338.         /* Look for a parent in trusted CAs or up the chain */
  2339.         ret = x509_crt_find_parent( child, trust_ca, &parent,
  2340.                                        &parent_is_trusted, &signature_is_good,
  2341.                                        ver_chain->len - 1, self_cnt, rs_ctx );
  2342.  
  2343. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2344.         if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
  2345.         {
  2346.             /* save state */
  2347.             rs_ctx->in_progress = x509_crt_rs_find_parent;
  2348.             rs_ctx->self_cnt = self_cnt;
  2349.             rs_ctx->ver_chain = *ver_chain; /* struct copy */
  2350.  
  2351.             return( ret );
  2352.         }
  2353. #else
  2354.         (void) ret;
  2355. #endif
  2356.  
  2357.         /* No parent? We're done here */
  2358.         if( parent == NULL )
  2359.         {
  2360.             *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
  2361.             return( 0 );
  2362.         }
  2363.  
  2364.         /* Count intermediate self-issued (not necessarily self-signed) certs.
  2365.          * These can occur with some strategies for key rollover, see [SIRO],
  2366.          * and should be excluded from max_pathlen checks. */
  2367.         if( ver_chain->len != 1 &&
  2368.             x509_name_cmp( &child->issuer, &child->subject ) == 0 )
  2369.         {
  2370.             self_cnt++;
  2371.         }
  2372.  
  2373.         /* path_cnt is 0 for the first intermediate CA,
  2374.          * and if parent is trusted it's not an intermediate CA */
  2375.         if( ! parent_is_trusted &&
  2376.             ver_chain->len > MBEDTLS_X509_MAX_INTERMEDIATE_CA )
  2377.         {
  2378.             /* return immediately to avoid overflow the chain array */
  2379.             return( MBEDTLS_ERR_X509_FATAL_ERROR );
  2380.         }
  2381.  
  2382.         /* signature was checked while searching parent */
  2383.         if( ! signature_is_good )
  2384.             *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
  2385.  
  2386.         /* check size of signing key */
  2387.         if( x509_profile_check_key( profile, &parent->pk ) != 0 )
  2388.             *flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
  2389.  
  2390. #if defined(MBEDTLS_X509_CRL_PARSE_C)
  2391.         /* Check trusted CA's CRL for the given crt */
  2392.         *flags |= x509_crt_verifycrl( child, parent, ca_crl, profile );
  2393. #else
  2394.         (void) ca_crl;
  2395. #endif
  2396.  
  2397.         /* prepare for next iteration */
  2398.         child = parent;
  2399.         parent = NULL;
  2400.         child_is_trusted = parent_is_trusted;
  2401.         signature_is_good = 0;
  2402.     }
  2403. }
  2404.  
  2405. /*
  2406.  * Check for CN match
  2407.  */
  2408. static int x509_crt_check_cn( const mbedtls_x509_buf *name,
  2409.                               const char *cn, size_t cn_len )
  2410. {
  2411.     /* try exact match */
  2412.     if( name->len == cn_len &&
  2413.         x509_memcasecmp( cn, name->p, cn_len ) == 0 )
  2414.     {
  2415.         return( 0 );
  2416.     }
  2417.  
  2418.     /* try wildcard match */
  2419.     if( x509_check_wildcard( cn, name ) == 0 )
  2420.     {
  2421.         return( 0 );
  2422.     }
  2423.  
  2424.     return( -1 );
  2425. }
  2426.  
  2427. /*
  2428.  * Verify the requested CN - only call this if cn is not NULL!
  2429.  */
  2430. static void x509_crt_verify_name( const mbedtls_x509_crt *crt,
  2431.                                   const char *cn,
  2432.                                   uint32_t *flags )
  2433. {
  2434.     const mbedtls_x509_name *name;
  2435.     const mbedtls_x509_sequence *cur;
  2436.     size_t cn_len = strlen( cn );
  2437.  
  2438.     if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
  2439.     {
  2440.         for( cur = &crt->subject_alt_names; cur != NULL; cur = cur->next )
  2441.         {
  2442.             if( x509_crt_check_cn( &cur->buf, cn, cn_len ) == 0 )
  2443.                 break;
  2444.         }
  2445.  
  2446.         if( cur == NULL )
  2447.             *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
  2448.     }
  2449.     else
  2450.     {
  2451.         for( name = &crt->subject; name != NULL; name = name->next )
  2452.         {
  2453.             if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 &&
  2454.                 x509_crt_check_cn( &name->val, cn, cn_len ) == 0 )
  2455.             {
  2456.                 break;
  2457.             }
  2458.         }
  2459.  
  2460.         if( name == NULL )
  2461.             *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
  2462.     }
  2463. }
  2464.  
  2465. /*
  2466.  * Merge the flags for all certs in the chain, after calling callback
  2467.  */
  2468. static int x509_crt_merge_flags_with_cb(
  2469.            uint32_t *flags,
  2470.            const mbedtls_x509_crt_verify_chain *ver_chain,
  2471.            int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  2472.            void *p_vrfy )
  2473. {
  2474.     int ret;
  2475.     unsigned i;
  2476.     uint32_t cur_flags;
  2477.     const mbedtls_x509_crt_verify_chain_item *cur;
  2478.  
  2479.     for( i = ver_chain->len; i != 0; --i )
  2480.     {
  2481.         cur = &ver_chain->items[i-1];
  2482.         cur_flags = cur->flags;
  2483.  
  2484.         if( NULL != f_vrfy )
  2485.             if( ( ret = f_vrfy( p_vrfy, cur->crt, (int) i-1, &cur_flags ) ) != 0 )
  2486.                 return( ret );
  2487.  
  2488.         *flags |= cur_flags;
  2489.     }
  2490.  
  2491.     return( 0 );
  2492. }
  2493.  
  2494. /*
  2495.  * Verify the certificate validity (default profile, not restartable)
  2496.  */
  2497. int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
  2498.                      mbedtls_x509_crt *trust_ca,
  2499.                      mbedtls_x509_crl *ca_crl,
  2500.                      const char *cn, uint32_t *flags,
  2501.                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  2502.                      void *p_vrfy )
  2503. {
  2504.     return( mbedtls_x509_crt_verify_restartable( crt, trust_ca, ca_crl,
  2505.                 &mbedtls_x509_crt_profile_default, cn, flags,
  2506.                 f_vrfy, p_vrfy, NULL ) );
  2507. }
  2508.  
  2509. /*
  2510.  * Verify the certificate validity (user-chosen profile, not restartable)
  2511.  */
  2512. int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
  2513.                      mbedtls_x509_crt *trust_ca,
  2514.                      mbedtls_x509_crl *ca_crl,
  2515.                      const mbedtls_x509_crt_profile *profile,
  2516.                      const char *cn, uint32_t *flags,
  2517.                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  2518.                      void *p_vrfy )
  2519. {
  2520.     return( mbedtls_x509_crt_verify_restartable( crt, trust_ca, ca_crl,
  2521.                 profile, cn, flags, f_vrfy, p_vrfy, NULL ) );
  2522. }
  2523.  
  2524. /*
  2525.  * Verify the certificate validity, with profile, restartable version
  2526.  *
  2527.  * This function:
  2528.  *  - checks the requested CN (if any)
  2529.  *  - checks the type and size of the EE cert's key,
  2530.  *    as that isn't done as part of chain building/verification currently
  2531.  *  - builds and verifies the chain
  2532.  *  - then calls the callback and merges the flags
  2533.  */
  2534. int mbedtls_x509_crt_verify_restartable( mbedtls_x509_crt *crt,
  2535.                      mbedtls_x509_crt *trust_ca,
  2536.                      mbedtls_x509_crl *ca_crl,
  2537.                      const mbedtls_x509_crt_profile *profile,
  2538.                      const char *cn, uint32_t *flags,
  2539.                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  2540.                      void *p_vrfy,
  2541.                      mbedtls_x509_crt_restart_ctx *rs_ctx )
  2542. {
  2543.     int ret;
  2544.     mbedtls_pk_type_t pk_type;
  2545.     mbedtls_x509_crt_verify_chain ver_chain;
  2546.     uint32_t ee_flags;
  2547.  
  2548.     *flags = 0;
  2549.     ee_flags = 0;
  2550.     x509_crt_verify_chain_reset( &ver_chain );
  2551.  
  2552.     if( profile == NULL )
  2553.     {
  2554.         ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;
  2555.         goto exit;
  2556.     }
  2557.  
  2558.     /* check name if requested */
  2559.     if( cn != NULL )
  2560.         x509_crt_verify_name( crt, cn, &ee_flags );
  2561.  
  2562.     /* Check the type and size of the key */
  2563.     pk_type = mbedtls_pk_get_type( &crt->pk );
  2564.  
  2565.     if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
  2566.         ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK;
  2567.  
  2568.     if( x509_profile_check_key( profile, &crt->pk ) != 0 )
  2569.         ee_flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
  2570.  
  2571.     /* Check the chain */
  2572.     ret = x509_crt_verify_chain( crt, trust_ca, ca_crl, profile,
  2573.                                  &ver_chain, rs_ctx );
  2574.  
  2575.     if( ret != 0 )
  2576.         goto exit;
  2577.  
  2578.     /* Merge end-entity flags */
  2579.     ver_chain.items[0].flags |= ee_flags;
  2580.  
  2581.     /* Build final flags, calling callback on the way if any */
  2582.     ret = x509_crt_merge_flags_with_cb( flags, &ver_chain, f_vrfy, p_vrfy );
  2583.  
  2584. exit:
  2585. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2586.     if( rs_ctx != NULL && ret != MBEDTLS_ERR_ECP_IN_PROGRESS )
  2587.         mbedtls_x509_crt_restart_free( rs_ctx );
  2588. #endif
  2589.  
  2590.     /* prevent misuse of the vrfy callback - VERIFY_FAILED would be ignored by
  2591.      * the SSL module for authmode optional, but non-zero return from the
  2592.      * callback means a fatal error so it shouldn't be ignored */
  2593.     if( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED )
  2594.         ret = MBEDTLS_ERR_X509_FATAL_ERROR;
  2595.  
  2596.     if( ret != 0 )
  2597.     {
  2598.         *flags = (uint32_t) -1;
  2599.         return( ret );
  2600.     }
  2601.  
  2602.     if( *flags != 0 )
  2603.         return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
  2604.  
  2605.     return( 0 );
  2606. }
  2607.  
  2608. /*
  2609.  * Initialize a certificate chain
  2610.  */
  2611. void mbedtls_x509_crt_init( mbedtls_x509_crt *crt )
  2612. {
  2613.     memset( crt, 0, sizeof(mbedtls_x509_crt) );
  2614. }
  2615.  
  2616. /*
  2617.  * Unallocate all certificate data
  2618.  */
  2619. void mbedtls_x509_crt_free( mbedtls_x509_crt *crt )
  2620. {
  2621.     mbedtls_x509_crt *cert_cur = crt;
  2622.     mbedtls_x509_crt *cert_prv;
  2623.     mbedtls_x509_name *name_cur;
  2624.     mbedtls_x509_name *name_prv;
  2625.     mbedtls_x509_sequence *seq_cur;
  2626.     mbedtls_x509_sequence *seq_prv;
  2627.  
  2628.     if( crt == NULL )
  2629.         return;
  2630.  
  2631.     do
  2632.     {
  2633.         mbedtls_pk_free( &cert_cur->pk );
  2634.  
  2635. #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
  2636.         mbedtls_free( cert_cur->sig_opts );
  2637. #endif
  2638.  
  2639.         name_cur = cert_cur->issuer.next;
  2640.         while( name_cur != NULL )
  2641.         {
  2642.             name_prv = name_cur;
  2643.             name_cur = name_cur->next;
  2644.             mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
  2645.             mbedtls_free( name_prv );
  2646.         }
  2647.  
  2648.         name_cur = cert_cur->subject.next;
  2649.         while( name_cur != NULL )
  2650.         {
  2651.             name_prv = name_cur;
  2652.             name_cur = name_cur->next;
  2653.             mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
  2654.             mbedtls_free( name_prv );
  2655.         }
  2656.  
  2657.         seq_cur = cert_cur->ext_key_usage.next;
  2658.         while( seq_cur != NULL )
  2659.         {
  2660.             seq_prv = seq_cur;
  2661.             seq_cur = seq_cur->next;
  2662.             mbedtls_platform_zeroize( seq_prv,
  2663.                                       sizeof( mbedtls_x509_sequence ) );
  2664.             mbedtls_free( seq_prv );
  2665.         }
  2666.  
  2667.         seq_cur = cert_cur->subject_alt_names.next;
  2668.         while( seq_cur != NULL )
  2669.         {
  2670.             seq_prv = seq_cur;
  2671.             seq_cur = seq_cur->next;
  2672.             mbedtls_platform_zeroize( seq_prv,
  2673.                                       sizeof( mbedtls_x509_sequence ) );
  2674.             mbedtls_free( seq_prv );
  2675.         }
  2676.  
  2677.         if( cert_cur->raw.p != NULL )
  2678.         {
  2679.             mbedtls_platform_zeroize( cert_cur->raw.p, cert_cur->raw.len );
  2680.             mbedtls_free( cert_cur->raw.p );
  2681.         }
  2682.  
  2683.         cert_cur = cert_cur->next;
  2684.     }
  2685.     while( cert_cur != NULL );
  2686.  
  2687.     cert_cur = crt;
  2688.     do
  2689.     {
  2690.         cert_prv = cert_cur;
  2691.         cert_cur = cert_cur->next;
  2692.  
  2693.         mbedtls_platform_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) );
  2694.         if( cert_prv != crt )
  2695.             mbedtls_free( cert_prv );
  2696.     }
  2697.     while( cert_cur != NULL );
  2698. }
  2699.  
  2700. #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
  2701. /*
  2702.  * Initialize a restart context
  2703.  */
  2704. void mbedtls_x509_crt_restart_init( mbedtls_x509_crt_restart_ctx *ctx )
  2705. {
  2706.     mbedtls_pk_restart_init( &ctx->pk );
  2707.  
  2708.     ctx->parent = NULL;
  2709.     ctx->fallback_parent = NULL;
  2710.     ctx->fallback_signature_is_good = 0;
  2711.  
  2712.     ctx->parent_is_trusted = -1;
  2713.  
  2714.     ctx->in_progress = x509_crt_rs_none;
  2715.     ctx->self_cnt = 0;
  2716.     x509_crt_verify_chain_reset( &ctx->ver_chain );
  2717. }
  2718.  
  2719. /*
  2720.  * Free the components of a restart context
  2721.  */
  2722. void mbedtls_x509_crt_restart_free( mbedtls_x509_crt_restart_ctx *ctx )
  2723. {
  2724.     if( ctx == NULL )
  2725.         return;
  2726.  
  2727.     mbedtls_pk_restart_free( &ctx->pk );
  2728.     mbedtls_x509_crt_restart_init( ctx );
  2729. }
  2730. #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
  2731.  
  2732. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  2733.