• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  X.509 certificate parsing and verification
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19 /*
20  *  The ITU-T X.509 standard defines a certificate format for PKI.
21  *
22  *  http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)
23  *  http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)
24  *  http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)
25  *
26  *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf
27  *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
28  *
29  *  [SIRO] https://cabforum.org/wp-content/uploads/Chunghwatelecom201503cabforumV4.pdf
30  */
31 
32 #include "common.h"
33 
34 #if defined(MBEDTLS_X509_CRT_PARSE_C)
35 
36 #include "mbedtls/x509_crt.h"
37 #include "mbedtls/error.h"
38 #include "mbedtls/oid.h"
39 #include "mbedtls/platform_util.h"
40 
41 #include <string.h>
42 
43 #if defined(MBEDTLS_PEM_PARSE_C)
44 #include "mbedtls/pem.h"
45 #endif
46 
47 #if defined(MBEDTLS_USE_PSA_CRYPTO)
48 #include "psa/crypto.h"
49 #include "mbedtls/psa_util.h"
50 #endif
51 
52 #if defined(MBEDTLS_PLATFORM_C)
53 #include "mbedtls/platform.h"
54 #else
55 #include <stdio.h>
56 #include <stdlib.h>
57 #define mbedtls_free       free
58 #define mbedtls_calloc    calloc
59 #define mbedtls_snprintf   snprintf
60 #endif
61 
62 #if defined(MBEDTLS_THREADING_C)
63 #include "mbedtls/threading.h"
64 #endif
65 
66 #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
67 #include <windows.h>
68 #else
69 #include <time.h>
70 #endif
71 
72 #if defined(MBEDTLS_FS_IO)
73 #include <stdio.h>
74 #if !defined(_WIN32) || defined(EFIX64) || defined(EFI32)
75 #include <sys/types.h>
76 #include <sys/stat.h>
77 #if defined(__MBED__)
78 #include <platform/mbed_retarget.h>
79 #else
80 #ifndef ESCP_MBDTLS_CUSTOMIZATION
81 #include <dirent.h>
82 #endif
83 #endif /* __MBED__ */
84 #endif /* !_WIN32 || EFIX64 || EFI32 */
85 #endif
86 
87 /*****************************************************************************
88  * @brief 定制特性:支持证书、CRL有效期的有条件忽略。具体的条件由产品自己实现。
89  *
90 ******************************************************************************/
91 #if defined(VENDOR_CUSTOMISE_CHECK_CERT_DATE_C)
92 
93 /*****************************************************************************
94  * @brief 定制特性,有条件忽略证书有效期,产品注册回调函数校验。
95  *
96 ******************************************************************************/
97 hw_mbedtls_cert_date_checker g_mbedtls_customize_cert_date_checker = NULL;
98 
99 /*****************************************************************************
100  * @brief 定制特性,有条件忽略CRL有效期,产品注册回调函数校验。
101  *
102 ******************************************************************************/
103 hw_mbedtls_crl_date_checker g_mbedtls_customize_crl_date_checker = NULL;
104 
105 /*****************************************************************************
106  * @brief
107  *
108  * @param checker
109  * @return int
110 ******************************************************************************/
hw_mbedtls_regist_cert_date_chcker(hw_mbedtls_cert_date_checker checker)111 int hw_mbedtls_regist_cert_date_chcker(hw_mbedtls_cert_date_checker checker)
112 {
113     g_mbedtls_customize_cert_date_checker = checker;
114     return 0;
115 }
116 
117 /*****************************************************************************
118  * \brief
119  *
120  * \param checker
121  * \return int
122 ******************************************************************************/
hw_mbedtls_regist_crl_date_chcker(hw_mbedtls_crl_date_checker checker)123 int hw_mbedtls_regist_crl_date_chcker(hw_mbedtls_crl_date_checker checker)
124 {
125     g_mbedtls_customize_crl_date_checker = checker;
126     return 0;
127 }
128 #endif
129 
130 /*
131  * Item in a verification chain: cert and flags for it
132  */
133 typedef struct {
134     mbedtls_x509_crt *crt;
135     uint32_t flags;
136 } x509_crt_verify_chain_item;
137 
138 /*
139  * Max size of verification chain: end-entity + intermediates + trusted root
140  */
141 #define X509_MAX_VERIFY_CHAIN_SIZE    ( MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2 )
142 
143 /* Default profile. Do not remove items unless there are serious security
144  * concerns. */
145 const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default =
146 {
147     /* Hashes from SHA-256 and above. Note that this selection
148      * should be aligned with ssl_preset_default_hashes in ssl_tls.c. */
149     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
150     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
151     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
152     0xFFFFFFF, /* Any PK alg    */
153 #if defined(MBEDTLS_ECP_C)
154     /* Curves at or above 128-bit security level. Note that this selection
155      * should be aligned with ssl_preset_default_curves in ssl_tls.c. */
156     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
157     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ) |
158     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP521R1 ) |
159     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP256R1 ) |
160     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP384R1 ) |
161     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP512R1 ) |
162     0,
163 #else
164     0,
165 #endif
166     2048,
167 };
168 
169 /* Next-generation profile. Currently identical to the default, but may
170  * be tightened at any time. */
171 const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next =
172 {
173     /* Hashes from SHA-256 and above. */
174     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
175     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
176     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
177     0xFFFFFFF, /* Any PK alg    */
178 #if defined(MBEDTLS_ECP_C)
179     /* Curves at or above 128-bit security level. */
180     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
181     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ) |
182     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP521R1 ) |
183     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP256R1 ) |
184     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP384R1 ) |
185     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP512R1 ) |
186     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256K1 ),
187 #else
188     0,
189 #endif
190     2048,
191 };
192 
193 /*
194  * NSA Suite B Profile
195  */
196 const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb =
197 {
198     /* Only SHA-256 and 384 */
199     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
200     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ),
201     /* Only ECDSA */
202     MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECDSA ) |
203     MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECKEY ),
204 #if defined(MBEDTLS_ECP_C)
205     /* Only NIST P-256 and P-384 */
206     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
207     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ),
208 #else
209     0,
210 #endif
211     0,
212 };
213 
214 /*
215  * Empty / all-forbidden profile
216  */
217 const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_none =
218 {
219     0,
220     0,
221     0,
222     (uint32_t) -1,
223 };
224 
225 /*
226  * Check md_alg against profile
227  * Return 0 if md_alg is acceptable for this profile, -1 otherwise
228  */
x509_profile_check_md_alg(const mbedtls_x509_crt_profile * profile,mbedtls_md_type_t md_alg)229 static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile,
230                                       mbedtls_md_type_t md_alg )
231 {
232     if( md_alg == MBEDTLS_MD_NONE )
233         return( -1 );
234 
235     if( ( profile->allowed_mds & MBEDTLS_X509_ID_FLAG( md_alg ) ) != 0 )
236         return( 0 );
237 
238     return( -1 );
239 }
240 
241 /*
242  * Check pk_alg against profile
243  * Return 0 if pk_alg is acceptable for this profile, -1 otherwise
244  */
x509_profile_check_pk_alg(const mbedtls_x509_crt_profile * profile,mbedtls_pk_type_t pk_alg)245 static int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile,
246                                       mbedtls_pk_type_t pk_alg )
247 {
248     if( pk_alg == MBEDTLS_PK_NONE )
249         return( -1 );
250 
251     if( ( profile->allowed_pks & MBEDTLS_X509_ID_FLAG( pk_alg ) ) != 0 )
252         return( 0 );
253 
254     return( -1 );
255 }
256 
257 /*
258  * Check key against profile
259  * Return 0 if pk is acceptable for this profile, -1 otherwise
260  */
x509_profile_check_key(const mbedtls_x509_crt_profile * profile,const mbedtls_pk_context * pk)261 static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile,
262                                    const mbedtls_pk_context *pk )
263 {
264     const mbedtls_pk_type_t pk_alg = mbedtls_pk_get_type( pk );
265 
266 #if defined(MBEDTLS_RSA_C)
267     if( pk_alg == MBEDTLS_PK_RSA || pk_alg == MBEDTLS_PK_RSASSA_PSS )
268     {
269         if( mbedtls_pk_get_bitlen( pk ) >= profile->rsa_min_bitlen )
270             return( 0 );
271 
272         return( -1 );
273     }
274 #endif
275 
276 #if defined(MBEDTLS_ECP_C)
277     if( pk_alg == MBEDTLS_PK_ECDSA ||
278         pk_alg == MBEDTLS_PK_ECKEY ||
279         pk_alg == MBEDTLS_PK_ECKEY_DH )
280     {
281         const mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id;
282 
283         if( gid == MBEDTLS_ECP_DP_NONE )
284             return( -1 );
285 
286         if( ( profile->allowed_curves & MBEDTLS_X509_ID_FLAG( gid ) ) != 0 )
287             return( 0 );
288 
289         return( -1 );
290     }
291 #endif
292 
293     return( -1 );
294 }
295 
296 /*
297  * Like memcmp, but case-insensitive and always returns -1 if different
298  */
x509_memcasecmp(const void * s1,const void * s2,size_t len)299 static int x509_memcasecmp( const void *s1, const void *s2, size_t len )
300 {
301     size_t i;
302     unsigned char diff;
303     const unsigned char *n1 = s1, *n2 = s2;
304 
305     for( i = 0; i < len; i++ )
306     {
307         diff = n1[i] ^ n2[i];
308 
309         if( diff == 0 )
310             continue;
311 
312         if( diff == 32 &&
313             ( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||
314               ( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )
315         {
316             continue;
317         }
318 
319         return( -1 );
320     }
321 
322     return( 0 );
323 }
324 
325 /*
326  * Return 0 if name matches wildcard, -1 otherwise
327  */
x509_check_wildcard(const char * cn,const mbedtls_x509_buf * name)328 static int x509_check_wildcard( const char *cn, const mbedtls_x509_buf *name )
329 {
330     size_t i;
331     size_t cn_idx = 0, cn_len = strlen( cn );
332 
333     /* We can't have a match if there is no wildcard to match */
334     if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' )
335         return( -1 );
336 
337     for( i = 0; i < cn_len; ++i )
338     {
339         if( cn[i] == '.' )
340         {
341             cn_idx = i;
342             break;
343         }
344     }
345 
346     if( cn_idx == 0 )
347         return( -1 );
348 
349     if( cn_len - cn_idx == name->len - 1 &&
350         x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
351     {
352         return( 0 );
353     }
354 
355     return( -1 );
356 }
357 
358 /*
359  * Compare two X.509 strings, case-insensitive, and allowing for some encoding
360  * variations (but not all).
361  *
362  * Return 0 if equal, -1 otherwise.
363  */
x509_string_cmp(const mbedtls_x509_buf * a,const mbedtls_x509_buf * b)364 static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b )
365 {
366     if( a->tag == b->tag &&
367         a->len == b->len &&
368         memcmp( a->p, b->p, b->len ) == 0 )
369     {
370         return( 0 );
371     }
372 
373     if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
374         ( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
375         a->len == b->len &&
376         x509_memcasecmp( a->p, b->p, b->len ) == 0 )
377     {
378         return( 0 );
379     }
380 
381     return( -1 );
382 }
383 
384 /*
385  * Compare two X.509 Names (aka rdnSequence).
386  *
387  * See RFC 5280 section 7.1, though we don't implement the whole algorithm:
388  * we sometimes return unequal when the full algorithm would return equal,
389  * but never the other way. (In particular, we don't do Unicode normalisation
390  * or space folding.)
391  *
392  * Return 0 if equal, -1 otherwise.
393  */
x509_name_cmp(const mbedtls_x509_name * a,const mbedtls_x509_name * b)394 static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b )
395 {
396     /* Avoid recursion, it might not be optimised by the compiler */
397     while( a != NULL || b != NULL )
398     {
399         if( a == NULL || b == NULL )
400             return( -1 );
401 
402         /* type */
403         if( a->oid.tag != b->oid.tag ||
404             a->oid.len != b->oid.len ||
405             memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )
406         {
407             return( -1 );
408         }
409 
410         /* value */
411         if( x509_string_cmp( &a->val, &b->val ) != 0 )
412             return( -1 );
413 
414         /* structure of the list of sets */
415         if( a->next_merged != b->next_merged )
416             return( -1 );
417 
418         a = a->next;
419         b = b->next;
420     }
421 
422     /* a == NULL == b */
423     return( 0 );
424 }
425 
426 /*
427  * Reset (init or clear) a verify_chain
428  */
x509_crt_verify_chain_reset(mbedtls_x509_crt_verify_chain * ver_chain)429 static void x509_crt_verify_chain_reset(
430     mbedtls_x509_crt_verify_chain *ver_chain )
431 {
432     size_t i;
433 
434     for( i = 0; i < MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE; i++ )
435     {
436         ver_chain->items[i].crt = NULL;
437         ver_chain->items[i].flags = (uint32_t) -1;
438     }
439 
440     ver_chain->len = 0;
441 
442 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
443     ver_chain->trust_ca_cb_result = NULL;
444 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
445 }
446 
447 /*
448  *  Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
449  */
x509_get_version(unsigned char ** p,const unsigned char * end,int * ver)450 static int x509_get_version( unsigned char **p,
451                              const unsigned char *end,
452                              int *ver )
453 {
454     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
455     size_t len;
456 
457     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
458             MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) != 0 )
459     {
460         if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
461         {
462             *ver = 0;
463             return( 0 );
464         }
465 
466         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_FORMAT, ret ) );
467     }
468 
469     end = *p + len;
470 
471     if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 )
472         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_VERSION, ret ) );
473 
474     if( *p != end )
475         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_VERSION,
476                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
477 
478     return( 0 );
479 }
480 
481 /*
482  *  Validity ::= SEQUENCE {
483  *       notBefore      Time,
484  *       notAfter       Time }
485  */
x509_get_dates(unsigned char ** p,const unsigned char * end,mbedtls_x509_time * from,mbedtls_x509_time * to)486 static int x509_get_dates( unsigned char **p,
487                            const unsigned char *end,
488                            mbedtls_x509_time *from,
489                            mbedtls_x509_time *to )
490 {
491     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
492     size_t len;
493 
494     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
495             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
496         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_DATE, ret ) );
497 
498     end = *p + len;
499 
500     if( ( ret = mbedtls_x509_get_time( p, end, from ) ) != 0 )
501         return( ret );
502 
503     if( ( ret = mbedtls_x509_get_time( p, end, to ) ) != 0 )
504         return( ret );
505 
506     if( *p != end )
507         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_DATE,
508                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
509 
510     return( 0 );
511 }
512 
513 /*
514  * X.509 v2/v3 unique identifier (not parsed)
515  */
x509_get_uid(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * uid,int n)516 static int x509_get_uid( unsigned char **p,
517                          const unsigned char *end,
518                          mbedtls_x509_buf *uid, int n )
519 {
520     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
521 
522     if( *p == end )
523         return( 0 );
524 
525     uid->tag = **p;
526 
527     if( ( ret = mbedtls_asn1_get_tag( p, end, &uid->len,
528             MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | n ) ) != 0 )
529     {
530         if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
531             return( 0 );
532 
533         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_FORMAT, ret ) );
534     }
535 
536     uid->p = *p;
537     *p += uid->len;
538 
539     return( 0 );
540 }
541 
x509_get_basic_constraints(unsigned char ** p,const unsigned char * end,int * ca_istrue,int * max_pathlen)542 static int x509_get_basic_constraints( unsigned char **p,
543                                        const unsigned char *end,
544                                        int *ca_istrue,
545                                        int *max_pathlen )
546 {
547     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
548     size_t len;
549 
550     /*
551      * BasicConstraints ::= SEQUENCE {
552      *      cA                      BOOLEAN DEFAULT FALSE,
553      *      pathLenConstraint       INTEGER (0..MAX) OPTIONAL }
554      */
555     *ca_istrue = 0; /* DEFAULT FALSE */
556     *max_pathlen = 0; /* endless */
557 
558     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
559             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
560         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
561 
562     if( *p == end )
563         return( 0 );
564 
565     if( ( ret = mbedtls_asn1_get_bool( p, end, ca_istrue ) ) != 0 )
566     {
567         if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
568             ret = mbedtls_asn1_get_int( p, end, ca_istrue );
569 
570         if( ret != 0 )
571             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
572 
573         if( *ca_istrue != 0 )
574             *ca_istrue = 1;
575     }
576 
577     if( *p == end )
578         return( 0 );
579 
580     if( ( ret = mbedtls_asn1_get_int( p, end, max_pathlen ) ) != 0 )
581         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
582 
583     if( *p != end )
584         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
585                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
586 
587     /* Do not accept max_pathlen equal to INT_MAX to avoid a signed integer
588      * overflow, which is an undefined behavior. */
589     if( *max_pathlen == INT_MAX )
590         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
591                 MBEDTLS_ERR_ASN1_INVALID_LENGTH ) );
592 
593     (*max_pathlen)++;
594 
595     return( 0 );
596 }
597 
x509_get_ns_cert_type(unsigned char ** p,const unsigned char * end,unsigned char * ns_cert_type)598 static int x509_get_ns_cert_type( unsigned char **p,
599                                        const unsigned char *end,
600                                        unsigned char *ns_cert_type)
601 {
602     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
603     mbedtls_x509_bitstring bs = { 0, 0, NULL };
604 
605     if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
606         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
607 
608     if( bs.len != 1 )
609         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
610                 MBEDTLS_ERR_ASN1_INVALID_LENGTH ) );
611 
612     /* Get actual bitstring */
613     *ns_cert_type = *bs.p;
614     return( 0 );
615 }
616 
x509_get_key_usage(unsigned char ** p,const unsigned char * end,unsigned int * key_usage)617 static int x509_get_key_usage( unsigned char **p,
618                                const unsigned char *end,
619                                unsigned int *key_usage)
620 {
621     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
622     size_t i;
623     mbedtls_x509_bitstring bs = { 0, 0, NULL };
624 
625     if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
626         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
627 
628     if( bs.len < 1 )
629         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
630                 MBEDTLS_ERR_ASN1_INVALID_LENGTH ) );
631 
632     /* Get actual bitstring */
633     *key_usage = 0;
634     for( i = 0; i < bs.len && i < sizeof( unsigned int ); i++ )
635     {
636         *key_usage |= (unsigned int) bs.p[i] << (8*i);
637     }
638 
639     return( 0 );
640 }
641 
642 /*
643  * ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
644  *
645  * KeyPurposeId ::= OBJECT IDENTIFIER
646  */
x509_get_ext_key_usage(unsigned char ** p,const unsigned char * end,mbedtls_x509_sequence * ext_key_usage)647 static int x509_get_ext_key_usage( unsigned char **p,
648                                const unsigned char *end,
649                                mbedtls_x509_sequence *ext_key_usage)
650 {
651     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
652 
653     if( ( ret = mbedtls_asn1_get_sequence_of( p, end, ext_key_usage, MBEDTLS_ASN1_OID ) ) != 0 )
654         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
655 
656     /* Sequence length must be >= 1 */
657     if( ext_key_usage->buf.p == NULL )
658         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
659                 MBEDTLS_ERR_ASN1_INVALID_LENGTH ) );
660 
661     return( 0 );
662 }
663 
664 /*
665  * SubjectAltName ::= GeneralNames
666  *
667  * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
668  *
669  * GeneralName ::= CHOICE {
670  *      otherName                       [0]     OtherName,
671  *      rfc822Name                      [1]     IA5String,
672  *      dNSName                         [2]     IA5String,
673  *      x400Address                     [3]     ORAddress,
674  *      directoryName                   [4]     Name,
675  *      ediPartyName                    [5]     EDIPartyName,
676  *      uniformResourceIdentifier       [6]     IA5String,
677  *      iPAddress                       [7]     OCTET STRING,
678  *      registeredID                    [8]     OBJECT IDENTIFIER }
679  *
680  * OtherName ::= SEQUENCE {
681  *      type-id    OBJECT IDENTIFIER,
682  *      value      [0] EXPLICIT ANY DEFINED BY type-id }
683  *
684  * EDIPartyName ::= SEQUENCE {
685  *      nameAssigner            [0]     DirectoryString OPTIONAL,
686  *      partyName               [1]     DirectoryString }
687  *
688  * NOTE: we list all types, but only use dNSName and otherName
689  * of type HwModuleName, as defined in RFC 4108, at this point.
690  */
x509_get_subject_alt_name(unsigned char ** p,const unsigned char * end,mbedtls_x509_sequence * subject_alt_name)691 static int x509_get_subject_alt_name( unsigned char **p,
692                                       const unsigned char *end,
693                                       mbedtls_x509_sequence *subject_alt_name )
694 {
695     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
696     size_t len, tag_len;
697     mbedtls_asn1_buf *buf;
698     unsigned char tag;
699     mbedtls_asn1_sequence *cur = subject_alt_name;
700 
701     /* Get main sequence tag */
702     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
703             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
704         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
705 
706     if( *p + len != end )
707         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
708                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
709 
710     while( *p < end )
711     {
712         mbedtls_x509_subject_alternative_name dummy_san_buf;
713         memset( &dummy_san_buf, 0, sizeof( dummy_san_buf ) );
714 
715         tag = **p;
716         (*p)++;
717         if( ( ret = mbedtls_asn1_get_len( p, end, &tag_len ) ) != 0 )
718             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
719 
720         if( ( tag & MBEDTLS_ASN1_TAG_CLASS_MASK ) !=
721                 MBEDTLS_ASN1_CONTEXT_SPECIFIC )
722         {
723             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
724                     MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
725         }
726 
727         /*
728          * Check that the SAN is structured correctly.
729          */
730         ret = mbedtls_x509_parse_subject_alt_name( &(cur->buf), &dummy_san_buf );
731         /*
732          * In case the extension is malformed, return an error,
733          * and clear the allocated sequences.
734          */
735         if( ret != 0 && ret != MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE )
736         {
737             mbedtls_x509_sequence *seq_cur = subject_alt_name->next;
738             mbedtls_x509_sequence *seq_prv;
739             while( seq_cur != NULL )
740             {
741                 seq_prv = seq_cur;
742                 seq_cur = seq_cur->next;
743                 mbedtls_platform_zeroize( seq_prv,
744                                           sizeof( mbedtls_x509_sequence ) );
745                 mbedtls_free( seq_prv );
746             }
747             subject_alt_name->next = NULL;
748             return( ret );
749         }
750 
751         /* Allocate and assign next pointer */
752         if( cur->buf.p != NULL )
753         {
754             if( cur->next != NULL )
755                 return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
756 
757             cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) );
758 
759             if( cur->next == NULL )
760                 return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
761                         MBEDTLS_ERR_ASN1_ALLOC_FAILED ) );
762 
763             cur = cur->next;
764         }
765 
766         buf = &(cur->buf);
767         buf->tag = tag;
768         buf->p = *p;
769         buf->len = tag_len;
770         *p += buf->len;
771     }
772 
773     /* Set final sequence entry's next pointer to NULL */
774     cur->next = NULL;
775 
776     if( *p != end )
777         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
778                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
779 
780     return( 0 );
781 }
782 
783 /*
784  * id-ce-certificatePolicies OBJECT IDENTIFIER ::=  { id-ce 32 }
785  *
786  * anyPolicy OBJECT IDENTIFIER ::= { id-ce-certificatePolicies 0 }
787  *
788  * certificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation
789  *
790  * PolicyInformation ::= SEQUENCE {
791  *     policyIdentifier   CertPolicyId,
792  *     policyQualifiers   SEQUENCE SIZE (1..MAX) OF
793  *                             PolicyQualifierInfo OPTIONAL }
794  *
795  * CertPolicyId ::= OBJECT IDENTIFIER
796  *
797  * PolicyQualifierInfo ::= SEQUENCE {
798  *      policyQualifierId  PolicyQualifierId,
799  *      qualifier          ANY DEFINED BY policyQualifierId }
800  *
801  * -- policyQualifierIds for Internet policy qualifiers
802  *
803  * id-qt          OBJECT IDENTIFIER ::=  { id-pkix 2 }
804  * id-qt-cps      OBJECT IDENTIFIER ::=  { id-qt 1 }
805  * id-qt-unotice  OBJECT IDENTIFIER ::=  { id-qt 2 }
806  *
807  * PolicyQualifierId ::= OBJECT IDENTIFIER ( id-qt-cps | id-qt-unotice )
808  *
809  * Qualifier ::= CHOICE {
810  *      cPSuri           CPSuri,
811  *      userNotice       UserNotice }
812  *
813  * CPSuri ::= IA5String
814  *
815  * UserNotice ::= SEQUENCE {
816  *      noticeRef        NoticeReference OPTIONAL,
817  *      explicitText     DisplayText OPTIONAL }
818  *
819  * NoticeReference ::= SEQUENCE {
820  *      organization     DisplayText,
821  *      noticeNumbers    SEQUENCE OF INTEGER }
822  *
823  * DisplayText ::= CHOICE {
824  *      ia5String        IA5String      (SIZE (1..200)),
825  *      visibleString    VisibleString  (SIZE (1..200)),
826  *      bmpString        BMPString      (SIZE (1..200)),
827  *      utf8String       UTF8String     (SIZE (1..200)) }
828  *
829  * NOTE: we only parse and use anyPolicy without qualifiers at this point
830  * as defined in RFC 5280.
831  */
x509_get_certificate_policies(unsigned char ** p,const unsigned char * end,mbedtls_x509_sequence * certificate_policies)832 static int x509_get_certificate_policies( unsigned char **p,
833                                           const unsigned char *end,
834                                           mbedtls_x509_sequence *certificate_policies )
835 {
836     int ret, parse_ret = 0;
837     size_t len;
838     mbedtls_asn1_buf *buf;
839     mbedtls_asn1_sequence *cur = certificate_policies;
840 
841     /* Get main sequence tag */
842     ret = mbedtls_asn1_get_tag( p, end, &len,
843                              MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE );
844     if( ret != 0 )
845         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
846 
847     if( *p + len != end )
848         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
849                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
850 
851     /*
852      * Cannot be an empty sequence.
853      */
854     if( len == 0 )
855         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
856                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
857 
858     while( *p < end )
859     {
860         mbedtls_x509_buf policy_oid;
861         const unsigned char *policy_end;
862 
863         /*
864          * Get the policy sequence
865          */
866         if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
867                 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
868             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
869 
870         policy_end = *p + len;
871 
872         if( ( ret = mbedtls_asn1_get_tag( p, policy_end, &len,
873                                           MBEDTLS_ASN1_OID ) ) != 0 )
874             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
875 
876         policy_oid.tag = MBEDTLS_ASN1_OID;
877         policy_oid.len = len;
878         policy_oid.p = *p;
879 
880         /*
881          * Only AnyPolicy is currently supported when enforcing policy.
882          */
883         if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_POLICY, &policy_oid ) != 0 )
884         {
885             /*
886              * Set the parsing return code but continue parsing, in case this
887              * extension is critical.
888              */
889             parse_ret = MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE;
890         }
891 
892         /* Allocate and assign next pointer */
893         if( cur->buf.p != NULL )
894         {
895             if( cur->next != NULL )
896                 return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
897 
898             cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) );
899 
900             if( cur->next == NULL )
901                 return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
902                         MBEDTLS_ERR_ASN1_ALLOC_FAILED ) );
903 
904             cur = cur->next;
905         }
906 
907         buf = &( cur->buf );
908         buf->tag = policy_oid.tag;
909         buf->p = policy_oid.p;
910         buf->len = policy_oid.len;
911 
912         *p += len;
913 
914        /*
915         * If there is an optional qualifier, then *p < policy_end
916         * Check the Qualifier len to verify it doesn't exceed policy_end.
917         */
918         if( *p < policy_end )
919         {
920             if( ( ret = mbedtls_asn1_get_tag( p, policy_end, &len,
921                      MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
922                 return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
923             /*
924              * Skip the optional policy qualifiers.
925              */
926             *p += len;
927         }
928 
929         if( *p != policy_end )
930             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
931                     MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
932     }
933 
934     /* Set final sequence entry's next pointer to NULL */
935     cur->next = NULL;
936 
937     if( *p != end )
938         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
939                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
940 
941     return( parse_ret );
942 }
943 
944 /*
945  * X.509 v3 extensions
946  *
947  */
x509_get_crt_ext(unsigned char ** p,const unsigned char * end,mbedtls_x509_crt * crt,mbedtls_x509_crt_ext_cb_t cb,void * p_ctx)948 static int x509_get_crt_ext( unsigned char **p,
949                              const unsigned char *end,
950                              mbedtls_x509_crt *crt,
951                              mbedtls_x509_crt_ext_cb_t cb,
952                              void *p_ctx )
953 {
954     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
955     size_t len;
956     unsigned char *end_ext_data, *start_ext_octet, *end_ext_octet;
957 
958     if( *p == end )
959         return( 0 );
960 
961     if( ( ret = mbedtls_x509_get_ext( p, end, &crt->v3_ext, 3 ) ) != 0 )
962         return( ret );
963 
964     end = crt->v3_ext.p + crt->v3_ext.len;
965     while( *p < end )
966     {
967         /*
968          * Extension  ::=  SEQUENCE  {
969          *      extnID      OBJECT IDENTIFIER,
970          *      critical    BOOLEAN DEFAULT FALSE,
971          *      extnValue   OCTET STRING  }
972          */
973         mbedtls_x509_buf extn_oid = {0, 0, NULL};
974         int is_critical = 0; /* DEFAULT FALSE */
975         int ext_type = 0;
976 
977         if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
978                 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
979             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
980 
981         end_ext_data = *p + len;
982 
983         /* Get extension ID */
984         if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &extn_oid.len,
985                                           MBEDTLS_ASN1_OID ) ) != 0 )
986             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
987 
988         extn_oid.tag = MBEDTLS_ASN1_OID;
989         extn_oid.p = *p;
990         *p += extn_oid.len;
991 
992         /* Get optional critical */
993         if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 &&
994             ( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) )
995             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
996 
997         /* Data should be octet string type */
998         if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len,
999                 MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
1000             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
1001 
1002         start_ext_octet = *p;
1003         end_ext_octet = *p + len;
1004 
1005         if( end_ext_octet != end_ext_data )
1006             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1007                     MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
1008 
1009         /*
1010          * Detect supported extensions
1011          */
1012         ret = mbedtls_oid_get_x509_ext_type( &extn_oid, &ext_type );
1013 
1014         if( ret != 0 )
1015         {
1016             /* Give the callback (if any) a chance to handle the extension */
1017             if( cb != NULL )
1018             {
1019                 ret = cb( p_ctx, crt, &extn_oid, is_critical, *p, end_ext_octet );
1020                 if( ret != 0 && is_critical )
1021                     return( ret );
1022                 *p = end_ext_octet;
1023                 continue;
1024             }
1025 
1026             /* No parser found, skip extension */
1027             *p = end_ext_octet;
1028 
1029             if( is_critical )
1030             {
1031                 /* Data is marked as critical: fail */
1032                 return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1033                         MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
1034             }
1035             continue;
1036         }
1037 
1038         /* Forbid repeated extensions */
1039         if( ( crt->ext_types & ext_type ) != 0 )
1040             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
1041 
1042         crt->ext_types |= ext_type;
1043 
1044         switch( ext_type )
1045         {
1046         case MBEDTLS_X509_EXT_BASIC_CONSTRAINTS:
1047             /* Parse basic constraints */
1048             if( ( ret = x509_get_basic_constraints( p, end_ext_octet,
1049                     &crt->ca_istrue, &crt->max_pathlen ) ) != 0 )
1050                 return( ret );
1051             break;
1052 
1053         case MBEDTLS_X509_EXT_KEY_USAGE:
1054             /* Parse key usage */
1055             if( ( ret = x509_get_key_usage( p, end_ext_octet,
1056                     &crt->key_usage ) ) != 0 )
1057                 return( ret );
1058             break;
1059 
1060         case MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE:
1061             /* Parse extended key usage */
1062             if( ( ret = x509_get_ext_key_usage( p, end_ext_octet,
1063                     &crt->ext_key_usage ) ) != 0 )
1064                 return( ret );
1065             break;
1066 
1067         case MBEDTLS_X509_EXT_SUBJECT_ALT_NAME:
1068             /* Parse subject alt name */
1069             if( ( ret = x509_get_subject_alt_name( p, end_ext_octet,
1070                     &crt->subject_alt_names ) ) != 0 )
1071                 return( ret );
1072             break;
1073 
1074         case MBEDTLS_X509_EXT_NS_CERT_TYPE:
1075             /* Parse netscape certificate type */
1076             if( ( ret = x509_get_ns_cert_type( p, end_ext_octet,
1077                     &crt->ns_cert_type ) ) != 0 )
1078                 return( ret );
1079             break;
1080 
1081         case MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES:
1082             /* Parse certificate policies type */
1083             if( ( ret = x509_get_certificate_policies( p, end_ext_octet,
1084                     &crt->certificate_policies ) ) != 0 )
1085             {
1086                 /* Give the callback (if any) a chance to handle the extension
1087                  * if it contains unsupported policies */
1088                 if( ret == MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE && cb != NULL &&
1089                     cb( p_ctx, crt, &extn_oid, is_critical,
1090                         start_ext_octet, end_ext_octet ) == 0 )
1091                     break;
1092 
1093                 if( is_critical )
1094                     return( ret );
1095                 else
1096                 /*
1097                  * If MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE is returned, then we
1098                  * cannot interpret or enforce the policy. However, it is up to
1099                  * the user to choose how to enforce the policies,
1100                  * unless the extension is critical.
1101                  */
1102                 if( ret != MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE )
1103                     return( ret );
1104             }
1105             break;
1106 
1107         default:
1108             /*
1109              * If this is a non-critical extension, which the oid layer
1110              * supports, but there isn't an x509 parser for it,
1111              * skip the extension.
1112              */
1113             if( is_critical )
1114                 return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );
1115             else
1116                 *p = end_ext_octet;
1117         }
1118     }
1119 
1120     if( *p != end )
1121         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1122                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
1123 
1124     return( 0 );
1125 }
1126 
1127 /*
1128  * Parse and fill a single X.509 certificate in DER format
1129  */
x509_crt_parse_der_core(mbedtls_x509_crt * crt,const unsigned char * buf,size_t buflen,int make_copy,mbedtls_x509_crt_ext_cb_t cb,void * p_ctx)1130 static int x509_crt_parse_der_core( mbedtls_x509_crt *crt,
1131                                     const unsigned char *buf,
1132                                     size_t buflen,
1133                                     int make_copy,
1134                                     mbedtls_x509_crt_ext_cb_t cb,
1135                                     void *p_ctx )
1136 {
1137     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1138     size_t len;
1139     unsigned char *p, *end, *crt_end;
1140     mbedtls_x509_buf sig_params1, sig_params2, sig_oid2;
1141 
1142     memset( &sig_params1, 0, sizeof( mbedtls_x509_buf ) );
1143     memset( &sig_params2, 0, sizeof( mbedtls_x509_buf ) );
1144     memset( &sig_oid2, 0, sizeof( mbedtls_x509_buf ) );
1145 
1146     /*
1147      * Check for valid input
1148      */
1149     if( crt == NULL || buf == NULL )
1150         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
1151 
1152     /* Use the original buffer until we figure out actual length. */
1153     p = (unsigned char*) buf;
1154     len = buflen;
1155     end = p + len;
1156 
1157     /*
1158      * Certificate  ::=  SEQUENCE  {
1159      *      tbsCertificate       TBSCertificate,
1160      *      signatureAlgorithm   AlgorithmIdentifier,
1161      *      signatureValue       BIT STRING  }
1162      */
1163     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
1164             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
1165     {
1166         mbedtls_x509_crt_free( crt );
1167         return( MBEDTLS_ERR_X509_INVALID_FORMAT );
1168     }
1169 
1170     end = crt_end = p + len;
1171     crt->raw.len = crt_end - buf;
1172     if( make_copy != 0 )
1173     {
1174         /* Create and populate a new buffer for the raw field. */
1175         crt->raw.p = p = mbedtls_calloc( 1, crt->raw.len );
1176         if( crt->raw.p == NULL )
1177             return( MBEDTLS_ERR_X509_ALLOC_FAILED );
1178 
1179         memcpy( crt->raw.p, buf, crt->raw.len );
1180         crt->own_buffer = 1;
1181 
1182         p += crt->raw.len - len;
1183         end = crt_end = p + len;
1184     }
1185     else
1186     {
1187         crt->raw.p = (unsigned char*) buf;
1188         crt->own_buffer = 0;
1189     }
1190 
1191     /*
1192      * TBSCertificate  ::=  SEQUENCE  {
1193      */
1194     crt->tbs.p = p;
1195 
1196     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
1197             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
1198     {
1199         mbedtls_x509_crt_free( crt );
1200         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_FORMAT, ret ) );
1201     }
1202 
1203     end = p + len;
1204     crt->tbs.len = end - crt->tbs.p;
1205 
1206     /*
1207      * Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
1208      *
1209      * CertificateSerialNumber  ::=  INTEGER
1210      *
1211      * signature            AlgorithmIdentifier
1212      */
1213     if( ( ret = x509_get_version(  &p, end, &crt->version  ) ) != 0 ||
1214         ( ret = mbedtls_x509_get_serial(   &p, end, &crt->serial   ) ) != 0 ||
1215         ( ret = mbedtls_x509_get_alg(      &p, end, &crt->sig_oid,
1216                                             &sig_params1 ) ) != 0 )
1217     {
1218         mbedtls_x509_crt_free( crt );
1219         return( ret );
1220     }
1221 
1222     if( crt->version < 0 || crt->version > 2 )
1223     {
1224         mbedtls_x509_crt_free( crt );
1225         return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );
1226     }
1227 
1228     crt->version++;
1229 
1230     if( ( ret = mbedtls_x509_get_sig_alg( &crt->sig_oid, &sig_params1,
1231                                   &crt->sig_md, &crt->sig_pk,
1232                                   &crt->sig_opts ) ) != 0 )
1233     {
1234         mbedtls_x509_crt_free( crt );
1235         return( ret );
1236     }
1237 
1238     /*
1239      * issuer               Name
1240      */
1241     crt->issuer_raw.p = p;
1242 
1243     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
1244             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
1245     {
1246         mbedtls_x509_crt_free( crt );
1247         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_FORMAT, ret ) );
1248     }
1249 
1250     if( ( ret = mbedtls_x509_get_name( &p, p + len, &crt->issuer ) ) != 0 )
1251     {
1252         mbedtls_x509_crt_free( crt );
1253         return( ret );
1254     }
1255 
1256     crt->issuer_raw.len = p - crt->issuer_raw.p;
1257 
1258     /*
1259      * Validity ::= SEQUENCE {
1260      *      notBefore      Time,
1261      *      notAfter       Time }
1262      *
1263      */
1264     if( ( ret = x509_get_dates( &p, end, &crt->valid_from,
1265                                          &crt->valid_to ) ) != 0 )
1266     {
1267         mbedtls_x509_crt_free( crt );
1268         return( ret );
1269     }
1270 
1271     /*
1272      * subject              Name
1273      */
1274     crt->subject_raw.p = p;
1275 
1276     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
1277             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
1278     {
1279         mbedtls_x509_crt_free( crt );
1280         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_FORMAT, ret ) );
1281     }
1282 
1283     if( len && ( ret = mbedtls_x509_get_name( &p, p + len, &crt->subject ) ) != 0 )
1284     {
1285         mbedtls_x509_crt_free( crt );
1286         return( ret );
1287     }
1288 
1289     crt->subject_raw.len = p - crt->subject_raw.p;
1290 
1291     /*
1292      * SubjectPublicKeyInfo
1293      */
1294     crt->pk_raw.p = p;
1295     if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &crt->pk ) ) != 0 )
1296     {
1297         mbedtls_x509_crt_free( crt );
1298         return( ret );
1299     }
1300     crt->pk_raw.len = p - crt->pk_raw.p;
1301 
1302     /*
1303      *  issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
1304      *                       -- If present, version shall be v2 or v3
1305      *  subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,
1306      *                       -- If present, version shall be v2 or v3
1307      *  extensions      [3]  EXPLICIT Extensions OPTIONAL
1308      *                       -- If present, version shall be v3
1309      */
1310     if( crt->version == 2 || crt->version == 3 )
1311     {
1312         ret = x509_get_uid( &p, end, &crt->issuer_id,  1 );
1313         if( ret != 0 )
1314         {
1315             mbedtls_x509_crt_free( crt );
1316             return( ret );
1317         }
1318     }
1319 
1320     if( crt->version == 2 || crt->version == 3 )
1321     {
1322         ret = x509_get_uid( &p, end, &crt->subject_id,  2 );
1323         if( ret != 0 )
1324         {
1325             mbedtls_x509_crt_free( crt );
1326             return( ret );
1327         }
1328     }
1329 
1330     if( crt->version == 3 )
1331     {
1332         ret = x509_get_crt_ext( &p, end, crt, cb, p_ctx );
1333         if( ret != 0 )
1334         {
1335             mbedtls_x509_crt_free( crt );
1336             return( ret );
1337         }
1338     }
1339 
1340     if( p != end )
1341     {
1342         mbedtls_x509_crt_free( crt );
1343         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_FORMAT,
1344                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
1345     }
1346 
1347     end = crt_end;
1348 
1349     /*
1350      *  }
1351      *  -- end of TBSCertificate
1352      *
1353      *  signatureAlgorithm   AlgorithmIdentifier,
1354      *  signatureValue       BIT STRING
1355      */
1356     if( ( ret = mbedtls_x509_get_alg( &p, end, &sig_oid2, &sig_params2 ) ) != 0 )
1357     {
1358         mbedtls_x509_crt_free( crt );
1359         return( ret );
1360     }
1361 
1362     if( crt->sig_oid.len != sig_oid2.len ||
1363         memcmp( crt->sig_oid.p, sig_oid2.p, crt->sig_oid.len ) != 0 ||
1364         sig_params1.tag != sig_params2.tag ||
1365         sig_params1.len != sig_params2.len ||
1366         ( sig_params1.len != 0 &&
1367           memcmp( sig_params1.p, sig_params2.p, sig_params1.len ) != 0 ) )
1368     {
1369         mbedtls_x509_crt_free( crt );
1370         return( MBEDTLS_ERR_X509_SIG_MISMATCH );
1371     }
1372 
1373     if( ( ret = mbedtls_x509_get_sig( &p, end, &crt->sig ) ) != 0 )
1374     {
1375         mbedtls_x509_crt_free( crt );
1376         return( ret );
1377     }
1378 
1379     if( p != end )
1380     {
1381         mbedtls_x509_crt_free( crt );
1382         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_FORMAT,
1383                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
1384     }
1385 
1386     return( 0 );
1387 }
1388 
1389 /*
1390  * Parse one X.509 certificate in DER format from a buffer and add them to a
1391  * chained list
1392  */
mbedtls_x509_crt_parse_der_internal(mbedtls_x509_crt * chain,const unsigned char * buf,size_t buflen,int make_copy,mbedtls_x509_crt_ext_cb_t cb,void * p_ctx)1393 static int mbedtls_x509_crt_parse_der_internal( mbedtls_x509_crt *chain,
1394                                                 const unsigned char *buf,
1395                                                 size_t buflen,
1396                                                 int make_copy,
1397                                                 mbedtls_x509_crt_ext_cb_t cb,
1398                                                 void *p_ctx )
1399 {
1400     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1401     mbedtls_x509_crt *crt = chain, *prev = NULL;
1402 
1403     /*
1404      * Check for valid input
1405      */
1406     if( crt == NULL || buf == NULL )
1407         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
1408 
1409     while( crt->version != 0 && crt->next != NULL )
1410     {
1411         prev = crt;
1412         crt = crt->next;
1413     }
1414 
1415     /*
1416      * Add new certificate on the end of the chain if needed.
1417      */
1418     if( crt->version != 0 && crt->next == NULL )
1419     {
1420         crt->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
1421 
1422         if( crt->next == NULL )
1423             return( MBEDTLS_ERR_X509_ALLOC_FAILED );
1424 
1425         prev = crt;
1426         mbedtls_x509_crt_init( crt->next );
1427         crt = crt->next;
1428     }
1429 
1430     ret = x509_crt_parse_der_core( crt, buf, buflen, make_copy, cb, p_ctx );
1431     if( ret != 0 )
1432     {
1433         if( prev )
1434             prev->next = NULL;
1435 
1436         if( crt != chain )
1437             mbedtls_free( crt );
1438 
1439         return( ret );
1440     }
1441 
1442     return( 0 );
1443 }
1444 
mbedtls_x509_crt_parse_der_nocopy(mbedtls_x509_crt * chain,const unsigned char * buf,size_t buflen)1445 int mbedtls_x509_crt_parse_der_nocopy( mbedtls_x509_crt *chain,
1446                                        const unsigned char *buf,
1447                                        size_t buflen )
1448 {
1449     return( mbedtls_x509_crt_parse_der_internal( chain, buf, buflen, 0, NULL, NULL ) );
1450 }
1451 
mbedtls_x509_crt_parse_der_with_ext_cb(mbedtls_x509_crt * chain,const unsigned char * buf,size_t buflen,int make_copy,mbedtls_x509_crt_ext_cb_t cb,void * p_ctx)1452 int mbedtls_x509_crt_parse_der_with_ext_cb( mbedtls_x509_crt *chain,
1453                                             const unsigned char *buf,
1454                                             size_t buflen,
1455                                             int make_copy,
1456                                             mbedtls_x509_crt_ext_cb_t cb,
1457                                             void *p_ctx )
1458 {
1459     return( mbedtls_x509_crt_parse_der_internal( chain, buf, buflen, make_copy, cb, p_ctx ) );
1460 }
1461 
mbedtls_x509_crt_parse_der(mbedtls_x509_crt * chain,const unsigned char * buf,size_t buflen)1462 int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain,
1463                                 const unsigned char *buf,
1464                                 size_t buflen )
1465 {
1466     return( mbedtls_x509_crt_parse_der_internal( chain, buf, buflen, 1, NULL, NULL ) );
1467 }
1468 
1469 /*
1470  * Parse one or more PEM certificates from a buffer and add them to the chained
1471  * list
1472  */
mbedtls_x509_crt_parse(mbedtls_x509_crt * chain,const unsigned char * buf,size_t buflen)1473 int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain,
1474                             const unsigned char *buf,
1475                             size_t buflen )
1476 {
1477 #if defined(MBEDTLS_PEM_PARSE_C)
1478     int success = 0, first_error = 0, total_failed = 0;
1479     int buf_format = MBEDTLS_X509_FORMAT_DER;
1480 #endif
1481 
1482     /*
1483      * Check for valid input
1484      */
1485     if( chain == NULL || buf == NULL )
1486         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
1487 
1488     /*
1489      * Determine buffer content. Buffer contains either one DER certificate or
1490      * one or more PEM certificates.
1491      */
1492 #if defined(MBEDTLS_PEM_PARSE_C)
1493     if( buflen != 0 && buf[buflen - 1] == '\0' &&
1494         strstr( (const char *) buf, "-----BEGIN CERTIFICATE-----" ) != NULL )
1495     {
1496         buf_format = MBEDTLS_X509_FORMAT_PEM;
1497     }
1498 
1499     if( buf_format == MBEDTLS_X509_FORMAT_DER )
1500         return mbedtls_x509_crt_parse_der( chain, buf, buflen );
1501 #else
1502     return mbedtls_x509_crt_parse_der( chain, buf, buflen );
1503 #endif
1504 
1505 #if defined(MBEDTLS_PEM_PARSE_C)
1506     if( buf_format == MBEDTLS_X509_FORMAT_PEM )
1507     {
1508         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1509         mbedtls_pem_context pem;
1510 
1511         /* 1 rather than 0 since the terminating NULL byte is counted in */
1512         while( buflen > 1 )
1513         {
1514             size_t use_len;
1515             mbedtls_pem_init( &pem );
1516 
1517             /* If we get there, we know the string is null-terminated */
1518             ret = mbedtls_pem_read_buffer( &pem,
1519                            "-----BEGIN CERTIFICATE-----",
1520                            "-----END CERTIFICATE-----",
1521                            buf, NULL, 0, &use_len );
1522 
1523             if( ret == 0 )
1524             {
1525                 /*
1526                  * Was PEM encoded
1527                  */
1528                 buflen -= use_len;
1529                 buf += use_len;
1530             }
1531             else if( ret == MBEDTLS_ERR_PEM_BAD_INPUT_DATA )
1532             {
1533                 return( ret );
1534             }
1535             else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
1536             {
1537                 mbedtls_pem_free( &pem );
1538 
1539                 /*
1540                  * PEM header and footer were found
1541                  */
1542                 buflen -= use_len;
1543                 buf += use_len;
1544 
1545                 if( first_error == 0 )
1546                     first_error = ret;
1547 
1548                 total_failed++;
1549                 continue;
1550             }
1551             else
1552                 break;
1553 
1554             ret = mbedtls_x509_crt_parse_der( chain, pem.buf, pem.buflen );
1555 
1556             mbedtls_pem_free( &pem );
1557 
1558             if( ret != 0 )
1559             {
1560                 /*
1561                  * Quit parsing on a memory error
1562                  */
1563                 if( ret == MBEDTLS_ERR_X509_ALLOC_FAILED )
1564                     return( ret );
1565 
1566                 if( first_error == 0 )
1567                     first_error = ret;
1568 
1569                 total_failed++;
1570                 continue;
1571             }
1572 
1573             success = 1;
1574         }
1575     }
1576 
1577     if( success )
1578         return( total_failed );
1579     else if( first_error )
1580         return( first_error );
1581     else
1582         return( MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT );
1583 #endif /* MBEDTLS_PEM_PARSE_C */
1584 }
1585 
1586 #if defined(MBEDTLS_FS_IO)
1587 /*
1588  * Load one or more certificates and add them to the chained list
1589  */
mbedtls_x509_crt_parse_file(mbedtls_x509_crt * chain,const char * path)1590 int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path )
1591 {
1592     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1593     size_t n;
1594     unsigned char *buf;
1595 
1596     if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )
1597         return( ret );
1598 
1599     ret = mbedtls_x509_crt_parse( chain, buf, n );
1600 
1601     mbedtls_platform_zeroize( buf, n );
1602     mbedtls_free( buf );
1603 
1604     return( ret );
1605 }
1606 
1607 #ifndef ESCP_MBDTLS_CUSTOMIZATION
mbedtls_x509_crt_parse_path(mbedtls_x509_crt * chain,const char * path)1608 int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )
1609 {
1610     int ret = 0;
1611 #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
1612     int w_ret;
1613     WCHAR szDir[MAX_PATH];
1614     char filename[MAX_PATH];
1615     char *p;
1616     size_t len = strlen( path );
1617 
1618     WIN32_FIND_DATAW file_data;
1619     HANDLE hFind;
1620 
1621     if( len > MAX_PATH - 3 )
1622         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
1623 
1624     memset( szDir, 0, sizeof(szDir) );
1625     memset( filename, 0, MAX_PATH );
1626     memcpy( filename, path, len );
1627     filename[len++] = '\\';
1628     p = filename + len;
1629     filename[len++] = '*';
1630 
1631     w_ret = MultiByteToWideChar( CP_ACP, 0, filename, (int)len, szDir,
1632                                  MAX_PATH - 3 );
1633     if( w_ret == 0 )
1634         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
1635 
1636     hFind = FindFirstFileW( szDir, &file_data );
1637     if( hFind == INVALID_HANDLE_VALUE )
1638         return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
1639 
1640     len = MAX_PATH - len;
1641     do
1642     {
1643         memset( p, 0, len );
1644 
1645         if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
1646             continue;
1647 
1648         w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName,
1649                                      lstrlenW( file_data.cFileName ),
1650                                      p, (int) len - 1,
1651                                      NULL, NULL );
1652         if( w_ret == 0 )
1653         {
1654             ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
1655             goto cleanup;
1656         }
1657 
1658         w_ret = mbedtls_x509_crt_parse_file( chain, filename );
1659         if( w_ret < 0 )
1660             ret++;
1661         else
1662             ret += w_ret;
1663     }
1664     while( FindNextFileW( hFind, &file_data ) != 0 );
1665 
1666     if( GetLastError() != ERROR_NO_MORE_FILES )
1667         ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
1668 
1669 cleanup:
1670     FindClose( hFind );
1671 #else /* _WIN32 */
1672     int t_ret;
1673     int snp_ret;
1674     struct stat sb;
1675     struct dirent *entry;
1676     char entry_name[MBEDTLS_X509_MAX_FILE_PATH_LEN];
1677     DIR *dir = opendir( path );
1678 
1679     if( dir == NULL )
1680         return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
1681 
1682 #if defined(MBEDTLS_THREADING_C)
1683     if( ( ret = mbedtls_mutex_lock( &mbedtls_threading_readdir_mutex ) ) != 0 )
1684     {
1685         closedir( dir );
1686         return( ret );
1687     }
1688 #endif /* MBEDTLS_THREADING_C */
1689 
1690     memset( &sb, 0, sizeof( sb ) );
1691 
1692     while( ( entry = readdir( dir ) ) != NULL )
1693     {
1694         snp_ret = mbedtls_snprintf( entry_name, sizeof entry_name,
1695                                     "%s/%s", path, entry->d_name );
1696 
1697         if( snp_ret < 0 || (size_t)snp_ret >= sizeof entry_name )
1698         {
1699             ret = MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
1700             goto cleanup;
1701         }
1702         else if( stat( entry_name, &sb ) == -1 )
1703         {
1704             ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
1705             goto cleanup;
1706         }
1707 
1708         if( !S_ISREG( sb.st_mode ) )
1709             continue;
1710 
1711         // Ignore parse errors
1712         //
1713         t_ret = mbedtls_x509_crt_parse_file( chain, entry_name );
1714         if( t_ret < 0 )
1715             ret++;
1716         else
1717             ret += t_ret;
1718     }
1719 
1720 cleanup:
1721     closedir( dir );
1722 
1723 #if defined(MBEDTLS_THREADING_C)
1724     if( mbedtls_mutex_unlock( &mbedtls_threading_readdir_mutex ) != 0 )
1725         ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR;
1726 #endif /* MBEDTLS_THREADING_C */
1727 
1728 #endif /* _WIN32 */
1729 
1730     return( ret );
1731 }
1732 #endif
1733 #endif /* MBEDTLS_FS_IO */
1734 
1735 /*
1736  * OtherName ::= SEQUENCE {
1737  *      type-id    OBJECT IDENTIFIER,
1738  *      value      [0] EXPLICIT ANY DEFINED BY type-id }
1739  *
1740  * HardwareModuleName ::= SEQUENCE {
1741  *                           hwType OBJECT IDENTIFIER,
1742  *                           hwSerialNum OCTET STRING }
1743  *
1744  * NOTE: we currently only parse and use otherName of type HwModuleName,
1745  * as defined in RFC 4108.
1746  */
x509_get_other_name(const mbedtls_x509_buf * subject_alt_name,mbedtls_x509_san_other_name * other_name)1747 static int x509_get_other_name( const mbedtls_x509_buf *subject_alt_name,
1748                                 mbedtls_x509_san_other_name *other_name )
1749 {
1750     int ret = 0;
1751     size_t len;
1752     unsigned char *p = subject_alt_name->p;
1753     const unsigned char *end = p + subject_alt_name->len;
1754     mbedtls_x509_buf cur_oid;
1755 
1756     if( ( subject_alt_name->tag &
1757         ( MBEDTLS_ASN1_TAG_CLASS_MASK | MBEDTLS_ASN1_TAG_VALUE_MASK ) ) !=
1758         ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_OTHER_NAME ) )
1759     {
1760         /*
1761          * The given subject alternative name is not of type "othername".
1762          */
1763         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
1764     }
1765 
1766     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
1767                                       MBEDTLS_ASN1_OID ) ) != 0 )
1768         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
1769 
1770     cur_oid.tag = MBEDTLS_ASN1_OID;
1771     cur_oid.p = p;
1772     cur_oid.len = len;
1773 
1774     /*
1775      * Only HwModuleName is currently supported.
1776      */
1777     if( MBEDTLS_OID_CMP( MBEDTLS_OID_ON_HW_MODULE_NAME, &cur_oid ) != 0 )
1778     {
1779         return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );
1780     }
1781 
1782     if( p + len >= end )
1783     {
1784         mbedtls_platform_zeroize( other_name, sizeof( *other_name ) );
1785         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1786                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
1787     }
1788     p += len;
1789     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
1790             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC ) ) != 0 )
1791         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
1792 
1793     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
1794                      MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
1795        return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
1796 
1797     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OID ) ) != 0 )
1798         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
1799 
1800     other_name->value.hardware_module_name.oid.tag = MBEDTLS_ASN1_OID;
1801     other_name->value.hardware_module_name.oid.p = p;
1802     other_name->value.hardware_module_name.oid.len = len;
1803 
1804     if( p + len >= end )
1805     {
1806         mbedtls_platform_zeroize( other_name, sizeof( *other_name ) );
1807         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1808                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
1809     }
1810     p += len;
1811     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
1812                                       MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
1813         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
1814 
1815     other_name->value.hardware_module_name.val.tag = MBEDTLS_ASN1_OCTET_STRING;
1816     other_name->value.hardware_module_name.val.p = p;
1817     other_name->value.hardware_module_name.val.len = len;
1818     p += len;
1819     if( p != end )
1820     {
1821         mbedtls_platform_zeroize( other_name,
1822                                   sizeof( *other_name ) );
1823         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1824                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
1825     }
1826     return( 0 );
1827 }
1828 
mbedtls_x509_parse_subject_alt_name(const mbedtls_x509_buf * san_buf,mbedtls_x509_subject_alternative_name * san)1829 int mbedtls_x509_parse_subject_alt_name( const mbedtls_x509_buf *san_buf,
1830                                          mbedtls_x509_subject_alternative_name *san )
1831 {
1832     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1833     switch( san_buf->tag &
1834             ( MBEDTLS_ASN1_TAG_CLASS_MASK |
1835               MBEDTLS_ASN1_TAG_VALUE_MASK ) )
1836     {
1837         /*
1838          * otherName
1839          */
1840         case( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_OTHER_NAME ):
1841         {
1842             mbedtls_x509_san_other_name other_name;
1843 
1844             ret = x509_get_other_name( san_buf, &other_name );
1845             if( ret != 0 )
1846                 return( ret );
1847 
1848             memset( san, 0, sizeof( mbedtls_x509_subject_alternative_name ) );
1849             san->type = MBEDTLS_X509_SAN_OTHER_NAME;
1850             memcpy( &san->san.other_name,
1851                     &other_name, sizeof( other_name ) );
1852 
1853         }
1854         break;
1855 
1856         /*
1857          * dNSName
1858          */
1859         case( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_DNS_NAME ):
1860         {
1861             memset( san, 0, sizeof( mbedtls_x509_subject_alternative_name ) );
1862             san->type = MBEDTLS_X509_SAN_DNS_NAME;
1863 
1864             memcpy( &san->san.unstructured_name,
1865                     san_buf, sizeof( *san_buf ) );
1866 
1867         }
1868         break;
1869 
1870         /*
1871          * Type not supported
1872          */
1873         default:
1874             return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );
1875     }
1876     return( 0 );
1877 }
1878 
1879 #if !defined(MBEDTLS_X509_REMOVE_INFO)
x509_info_subject_alt_name(char ** buf,size_t * size,const mbedtls_x509_sequence * subject_alt_name,const char * prefix)1880 static int x509_info_subject_alt_name( char **buf, size_t *size,
1881                                        const mbedtls_x509_sequence
1882                                                     *subject_alt_name,
1883                                        const char *prefix )
1884 {
1885     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1886     size_t n = *size;
1887     char *p = *buf;
1888     const mbedtls_x509_sequence *cur = subject_alt_name;
1889     mbedtls_x509_subject_alternative_name san;
1890     int parse_ret;
1891 
1892     while( cur != NULL )
1893     {
1894         memset( &san, 0, sizeof( san ) );
1895         parse_ret = mbedtls_x509_parse_subject_alt_name( &cur->buf, &san );
1896         if( parse_ret != 0 )
1897         {
1898             if( parse_ret == MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE )
1899             {
1900                 ret = mbedtls_snprintf( p, n, "\n%s    <unsupported>", prefix );
1901                 MBEDTLS_X509_SAFE_SNPRINTF;
1902             }
1903             else
1904             {
1905                 ret = mbedtls_snprintf( p, n, "\n%s    <malformed>", prefix );
1906                 MBEDTLS_X509_SAFE_SNPRINTF;
1907             }
1908             cur = cur->next;
1909             continue;
1910         }
1911 
1912         switch( san.type )
1913         {
1914             /*
1915              * otherName
1916              */
1917             case MBEDTLS_X509_SAN_OTHER_NAME:
1918             {
1919                 mbedtls_x509_san_other_name *other_name = &san.san.other_name;
1920 
1921                 ret = mbedtls_snprintf( p, n, "\n%s    otherName :", prefix );
1922                 MBEDTLS_X509_SAFE_SNPRINTF;
1923 
1924                 if( MBEDTLS_OID_CMP( MBEDTLS_OID_ON_HW_MODULE_NAME,
1925                                      &other_name->value.hardware_module_name.oid ) != 0 )
1926                 {
1927                     ret = mbedtls_snprintf( p, n, "\n%s        hardware module name :", prefix );
1928                     MBEDTLS_X509_SAFE_SNPRINTF;
1929                     ret = mbedtls_snprintf( p, n, "\n%s            hardware type          : ", prefix );
1930                     MBEDTLS_X509_SAFE_SNPRINTF;
1931 
1932                     ret = mbedtls_oid_get_numeric_string( p, n, &other_name->value.hardware_module_name.oid );
1933                     MBEDTLS_X509_SAFE_SNPRINTF;
1934 
1935                     ret = mbedtls_snprintf( p, n, "\n%s            hardware serial number : ", prefix );
1936                     MBEDTLS_X509_SAFE_SNPRINTF;
1937 
1938                     if( other_name->value.hardware_module_name.val.len >= n )
1939                     {
1940                         *p = '\0';
1941                         return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
1942                     }
1943 
1944                     memcpy( p, other_name->value.hardware_module_name.val.p,
1945                             other_name->value.hardware_module_name.val.len );
1946                     p += other_name->value.hardware_module_name.val.len;
1947 
1948                     n -= other_name->value.hardware_module_name.val.len;
1949 
1950                 }/* MBEDTLS_OID_ON_HW_MODULE_NAME */
1951             }
1952             break;
1953 
1954             /*
1955              * dNSName
1956              */
1957             case MBEDTLS_X509_SAN_DNS_NAME:
1958             {
1959                 ret = mbedtls_snprintf( p, n, "\n%s    dNSName : ", prefix );
1960                 MBEDTLS_X509_SAFE_SNPRINTF;
1961                 if( san.san.unstructured_name.len >= n )
1962                 {
1963                     *p = '\0';
1964                     return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
1965                 }
1966 
1967                 memcpy( p, san.san.unstructured_name.p, san.san.unstructured_name.len );
1968                 p += san.san.unstructured_name.len;
1969                 n -= san.san.unstructured_name.len;
1970             }
1971             break;
1972 
1973             /*
1974              * Type not supported, skip item.
1975              */
1976             default:
1977                 ret = mbedtls_snprintf( p, n, "\n%s    <unsupported>", prefix );
1978                 MBEDTLS_X509_SAFE_SNPRINTF;
1979                 break;
1980         }
1981 
1982         cur = cur->next;
1983     }
1984 
1985     *p = '\0';
1986 
1987     *size = n;
1988     *buf = p;
1989 
1990     return( 0 );
1991 }
1992 
1993 #define PRINT_ITEM(i)                           \
1994     {                                           \
1995         ret = mbedtls_snprintf( p, n, "%s" i, sep );    \
1996         MBEDTLS_X509_SAFE_SNPRINTF;                        \
1997         sep = ", ";                             \
1998     }
1999 
2000 #define CERT_TYPE(type,name)                    \
2001     if( ns_cert_type & (type) )                 \
2002         PRINT_ITEM( name );
2003 
x509_info_cert_type(char ** buf,size_t * size,unsigned char ns_cert_type)2004 static int x509_info_cert_type( char **buf, size_t *size,
2005                                 unsigned char ns_cert_type )
2006 {
2007     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2008     size_t n = *size;
2009     char *p = *buf;
2010     const char *sep = "";
2011 
2012     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT,         "SSL Client" );
2013     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER,         "SSL Server" );
2014     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL,              "Email" );
2015     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING,     "Object Signing" );
2016     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_RESERVED,           "Reserved" );
2017     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CA,             "SSL CA" );
2018     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA,           "Email CA" );
2019     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA,  "Object Signing CA" );
2020 
2021     *size = n;
2022     *buf = p;
2023 
2024     return( 0 );
2025 }
2026 
2027 #define KEY_USAGE(code,name)    \
2028     if( key_usage & (code) )    \
2029         PRINT_ITEM( name );
2030 
x509_info_key_usage(char ** buf,size_t * size,unsigned int key_usage)2031 static int x509_info_key_usage( char **buf, size_t *size,
2032                                 unsigned int key_usage )
2033 {
2034     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2035     size_t n = *size;
2036     char *p = *buf;
2037     const char *sep = "";
2038 
2039     KEY_USAGE( MBEDTLS_X509_KU_DIGITAL_SIGNATURE,    "Digital Signature" );
2040     KEY_USAGE( MBEDTLS_X509_KU_NON_REPUDIATION,      "Non Repudiation" );
2041     KEY_USAGE( MBEDTLS_X509_KU_KEY_ENCIPHERMENT,     "Key Encipherment" );
2042     KEY_USAGE( MBEDTLS_X509_KU_DATA_ENCIPHERMENT,    "Data Encipherment" );
2043     KEY_USAGE( MBEDTLS_X509_KU_KEY_AGREEMENT,        "Key Agreement" );
2044     KEY_USAGE( MBEDTLS_X509_KU_KEY_CERT_SIGN,        "Key Cert Sign" );
2045     KEY_USAGE( MBEDTLS_X509_KU_CRL_SIGN,             "CRL Sign" );
2046     KEY_USAGE( MBEDTLS_X509_KU_ENCIPHER_ONLY,        "Encipher Only" );
2047     KEY_USAGE( MBEDTLS_X509_KU_DECIPHER_ONLY,        "Decipher Only" );
2048 
2049     *size = n;
2050     *buf = p;
2051 
2052     return( 0 );
2053 }
2054 
x509_info_ext_key_usage(char ** buf,size_t * size,const mbedtls_x509_sequence * extended_key_usage)2055 static int x509_info_ext_key_usage( char **buf, size_t *size,
2056                                     const mbedtls_x509_sequence *extended_key_usage )
2057 {
2058     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2059     const char *desc;
2060     size_t n = *size;
2061     char *p = *buf;
2062     const mbedtls_x509_sequence *cur = extended_key_usage;
2063     const char *sep = "";
2064 
2065     while( cur != NULL )
2066     {
2067         if( mbedtls_oid_get_extended_key_usage( &cur->buf, &desc ) != 0 )
2068             desc = "???";
2069 
2070         ret = mbedtls_snprintf( p, n, "%s%s", sep, desc );
2071         MBEDTLS_X509_SAFE_SNPRINTF;
2072 
2073         sep = ", ";
2074 
2075         cur = cur->next;
2076     }
2077 
2078     *size = n;
2079     *buf = p;
2080 
2081     return( 0 );
2082 }
2083 
x509_info_cert_policies(char ** buf,size_t * size,const mbedtls_x509_sequence * certificate_policies)2084 static int x509_info_cert_policies( char **buf, size_t *size,
2085                                     const mbedtls_x509_sequence *certificate_policies )
2086 {
2087     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2088     const char *desc;
2089     size_t n = *size;
2090     char *p = *buf;
2091     const mbedtls_x509_sequence *cur = certificate_policies;
2092     const char *sep = "";
2093 
2094     while( cur != NULL )
2095     {
2096         if( mbedtls_oid_get_certificate_policies( &cur->buf, &desc ) != 0 )
2097             desc = "???";
2098 
2099         ret = mbedtls_snprintf( p, n, "%s%s", sep, desc );
2100         MBEDTLS_X509_SAFE_SNPRINTF;
2101 
2102         sep = ", ";
2103 
2104         cur = cur->next;
2105     }
2106 
2107     *size = n;
2108     *buf = p;
2109 
2110     return( 0 );
2111 }
2112 
2113 /*
2114  * Return an informational string about the certificate.
2115  */
2116 #define BEFORE_COLON    18
2117 #define BC              "18"
mbedtls_x509_crt_info(char * buf,size_t size,const char * prefix,const mbedtls_x509_crt * crt)2118 int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,
2119                    const mbedtls_x509_crt *crt )
2120 {
2121     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2122     size_t n;
2123     char *p;
2124     char key_size_str[BEFORE_COLON];
2125 
2126     p = buf;
2127     n = size;
2128 
2129     if( NULL == crt )
2130     {
2131         ret = mbedtls_snprintf( p, n, "\nCertificate is uninitialised!\n" );
2132         MBEDTLS_X509_SAFE_SNPRINTF;
2133 
2134         return( (int) ( size - n ) );
2135     }
2136 
2137     ret = mbedtls_snprintf( p, n, "%scert. version     : %d\n",
2138                                prefix, crt->version );
2139     MBEDTLS_X509_SAFE_SNPRINTF;
2140     ret = mbedtls_snprintf( p, n, "%sserial number     : ",
2141                                prefix );
2142     MBEDTLS_X509_SAFE_SNPRINTF;
2143 
2144     ret = mbedtls_x509_serial_gets( p, n, &crt->serial );
2145     MBEDTLS_X509_SAFE_SNPRINTF;
2146 
2147     ret = mbedtls_snprintf( p, n, "\n%sissuer name       : ", prefix );
2148     MBEDTLS_X509_SAFE_SNPRINTF;
2149     ret = mbedtls_x509_dn_gets( p, n, &crt->issuer  );
2150     MBEDTLS_X509_SAFE_SNPRINTF;
2151 
2152     ret = mbedtls_snprintf( p, n, "\n%ssubject name      : ", prefix );
2153     MBEDTLS_X509_SAFE_SNPRINTF;
2154     ret = mbedtls_x509_dn_gets( p, n, &crt->subject );
2155     MBEDTLS_X509_SAFE_SNPRINTF;
2156 
2157     ret = mbedtls_snprintf( p, n, "\n%sissued  on        : " \
2158                    "%04d-%02d-%02d %02d:%02d:%02d", prefix,
2159                    crt->valid_from.year, crt->valid_from.mon,
2160                    crt->valid_from.day,  crt->valid_from.hour,
2161                    crt->valid_from.min,  crt->valid_from.sec );
2162     MBEDTLS_X509_SAFE_SNPRINTF;
2163 
2164     ret = mbedtls_snprintf( p, n, "\n%sexpires on        : " \
2165                    "%04d-%02d-%02d %02d:%02d:%02d", prefix,
2166                    crt->valid_to.year, crt->valid_to.mon,
2167                    crt->valid_to.day,  crt->valid_to.hour,
2168                    crt->valid_to.min,  crt->valid_to.sec );
2169     MBEDTLS_X509_SAFE_SNPRINTF;
2170 
2171     ret = mbedtls_snprintf( p, n, "\n%ssigned using      : ", prefix );
2172     MBEDTLS_X509_SAFE_SNPRINTF;
2173 
2174     ret = mbedtls_x509_sig_alg_gets( p, n, &crt->sig_oid, crt->sig_pk,
2175                              crt->sig_md, crt->sig_opts );
2176     MBEDTLS_X509_SAFE_SNPRINTF;
2177 
2178     /* Key size */
2179     if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON,
2180                                       mbedtls_pk_get_name( &crt->pk ) ) ) != 0 )
2181     {
2182         return( ret );
2183     }
2184 
2185     ret = mbedtls_snprintf( p, n, "\n%s%-" BC "s: %d bits", prefix, key_size_str,
2186                           (int) mbedtls_pk_get_bitlen( &crt->pk ) );
2187     MBEDTLS_X509_SAFE_SNPRINTF;
2188 
2189     /*
2190      * Optional extensions
2191      */
2192 
2193     if( crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS )
2194     {
2195         ret = mbedtls_snprintf( p, n, "\n%sbasic constraints : CA=%s", prefix,
2196                         crt->ca_istrue ? "true" : "false" );
2197         MBEDTLS_X509_SAFE_SNPRINTF;
2198 
2199         if( crt->max_pathlen > 0 )
2200         {
2201             ret = mbedtls_snprintf( p, n, ", max_pathlen=%d", crt->max_pathlen - 1 );
2202             MBEDTLS_X509_SAFE_SNPRINTF;
2203         }
2204     }
2205 
2206     if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
2207     {
2208         ret = mbedtls_snprintf( p, n, "\n%ssubject alt name  :", prefix );
2209         MBEDTLS_X509_SAFE_SNPRINTF;
2210 
2211         if( ( ret = x509_info_subject_alt_name( &p, &n,
2212                                                 &crt->subject_alt_names,
2213                                                 prefix ) ) != 0 )
2214             return( ret );
2215     }
2216 
2217     if( crt->ext_types & MBEDTLS_X509_EXT_NS_CERT_TYPE )
2218     {
2219         ret = mbedtls_snprintf( p, n, "\n%scert. type        : ", prefix );
2220         MBEDTLS_X509_SAFE_SNPRINTF;
2221 
2222         if( ( ret = x509_info_cert_type( &p, &n, crt->ns_cert_type ) ) != 0 )
2223             return( ret );
2224     }
2225 
2226     if( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE )
2227     {
2228         ret = mbedtls_snprintf( p, n, "\n%skey usage         : ", prefix );
2229         MBEDTLS_X509_SAFE_SNPRINTF;
2230 
2231         if( ( ret = x509_info_key_usage( &p, &n, crt->key_usage ) ) != 0 )
2232             return( ret );
2233     }
2234 
2235     if( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE )
2236     {
2237         ret = mbedtls_snprintf( p, n, "\n%sext key usage     : ", prefix );
2238         MBEDTLS_X509_SAFE_SNPRINTF;
2239 
2240         if( ( ret = x509_info_ext_key_usage( &p, &n,
2241                                              &crt->ext_key_usage ) ) != 0 )
2242             return( ret );
2243     }
2244 
2245     if( crt->ext_types & MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES )
2246     {
2247         ret = mbedtls_snprintf( p, n, "\n%scertificate policies : ", prefix );
2248         MBEDTLS_X509_SAFE_SNPRINTF;
2249 
2250         if( ( ret = x509_info_cert_policies( &p, &n,
2251                                              &crt->certificate_policies ) ) != 0 )
2252             return( ret );
2253     }
2254 
2255     ret = mbedtls_snprintf( p, n, "\n" );
2256     MBEDTLS_X509_SAFE_SNPRINTF;
2257 
2258     return( (int) ( size - n ) );
2259 }
2260 
2261 struct x509_crt_verify_string {
2262     int code;
2263     const char *string;
2264 };
2265 
2266 #define X509_CRT_ERROR_INFO( err, err_str, info ) { err, info },
2267 static const struct x509_crt_verify_string x509_crt_verify_strings[] = {
2268     MBEDTLS_X509_CRT_ERROR_INFO_LIST
2269     { 0, NULL }
2270 };
2271 #undef X509_CRT_ERROR_INFO
2272 
mbedtls_x509_crt_verify_info(char * buf,size_t size,const char * prefix,uint32_t flags)2273 int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
2274                           uint32_t flags )
2275 {
2276     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2277     const struct x509_crt_verify_string *cur;
2278     char *p = buf;
2279     size_t n = size;
2280 
2281     for( cur = x509_crt_verify_strings; cur->string != NULL ; cur++ )
2282     {
2283         if( ( flags & cur->code ) == 0 )
2284             continue;
2285 
2286         ret = mbedtls_snprintf( p, n, "%s%s\n", prefix, cur->string );
2287         MBEDTLS_X509_SAFE_SNPRINTF;
2288         flags ^= cur->code;
2289     }
2290 
2291     if( flags != 0 )
2292     {
2293         ret = mbedtls_snprintf( p, n, "%sUnknown reason "
2294                                        "(this should not happen)\n", prefix );
2295         MBEDTLS_X509_SAFE_SNPRINTF;
2296     }
2297 
2298     return( (int) ( size - n ) );
2299 }
2300 #endif /* MBEDTLS_X509_REMOVE_INFO */
2301 
mbedtls_x509_crt_check_key_usage(const mbedtls_x509_crt * crt,unsigned int usage)2302 int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
2303                                       unsigned int usage )
2304 {
2305     unsigned int usage_must, usage_may;
2306     unsigned int may_mask = MBEDTLS_X509_KU_ENCIPHER_ONLY
2307                           | MBEDTLS_X509_KU_DECIPHER_ONLY;
2308 
2309     if( ( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) == 0 )
2310         return( 0 );
2311 
2312     usage_must = usage & ~may_mask;
2313 
2314     if( ( ( crt->key_usage & ~may_mask ) & usage_must ) != usage_must )
2315         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
2316 
2317     usage_may = usage & may_mask;
2318 
2319     if( ( ( crt->key_usage & may_mask ) | usage_may ) != usage_may )
2320         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
2321 
2322     return( 0 );
2323 }
2324 
mbedtls_x509_crt_check_extended_key_usage(const mbedtls_x509_crt * crt,const char * usage_oid,size_t usage_len)2325 int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
2326                                        const char *usage_oid,
2327                                        size_t usage_len )
2328 {
2329     const mbedtls_x509_sequence *cur;
2330 
2331     /* Extension is not mandatory, absent means no restriction */
2332     if( ( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE ) == 0 )
2333         return( 0 );
2334 
2335     /*
2336      * Look for the requested usage (or wildcard ANY) in our list
2337      */
2338     for( cur = &crt->ext_key_usage; cur != NULL; cur = cur->next )
2339     {
2340         const mbedtls_x509_buf *cur_oid = &cur->buf;
2341 
2342         if( cur_oid->len == usage_len &&
2343             memcmp( cur_oid->p, usage_oid, usage_len ) == 0 )
2344         {
2345             return( 0 );
2346         }
2347 
2348         if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE, cur_oid ) == 0 )
2349             return( 0 );
2350     }
2351 
2352     return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
2353 }
2354 
2355 #if defined(MBEDTLS_X509_CRL_PARSE_C)
2356 /*
2357  * Return 1 if the certificate is revoked, or 0 otherwise.
2358  */
mbedtls_x509_crt_is_revoked(const mbedtls_x509_crt * crt,const mbedtls_x509_crl * crl)2359 int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl )
2360 {
2361     const mbedtls_x509_crl_entry *cur = &crl->entry;
2362 
2363     while( cur != NULL && cur->serial.len != 0 )
2364     {
2365         if( crt->serial.len == cur->serial.len &&
2366             memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 )
2367         {
2368             return( 1 );
2369         }
2370 
2371         cur = cur->next;
2372     }
2373 
2374     return( 0 );
2375 }
2376 
2377 /*
2378  * Check that the given certificate is not revoked according to the CRL.
2379  * Skip validation if no CRL for the given CA is present.
2380  */
x509_crt_verifycrl(mbedtls_x509_crt * crt,mbedtls_x509_crt * ca,mbedtls_x509_crl * crl_list,const mbedtls_x509_crt_profile * profile)2381 static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
2382                                mbedtls_x509_crl *crl_list,
2383                                const mbedtls_x509_crt_profile *profile )
2384 {
2385     int flags = 0;
2386     unsigned char hash[MBEDTLS_MD_MAX_SIZE];
2387     const mbedtls_md_info_t *md_info;
2388 
2389     if( ca == NULL )
2390         return( flags );
2391 
2392     while( crl_list != NULL )
2393     {
2394         if( crl_list->version == 0 ||
2395             x509_name_cmp( &crl_list->issuer, &ca->subject ) != 0 )
2396         {
2397             crl_list = crl_list->next;
2398             continue;
2399         }
2400 
2401         /*
2402          * Check if the CA is configured to sign CRLs
2403          */
2404         if( mbedtls_x509_crt_check_key_usage( ca,
2405                                               MBEDTLS_X509_KU_CRL_SIGN ) != 0 )
2406         {
2407             flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
2408             break;
2409         }
2410 
2411         /*
2412          * Check if CRL is correctly signed by the trusted CA
2413          */
2414         if( x509_profile_check_md_alg( profile, crl_list->sig_md ) != 0 )
2415             flags |= MBEDTLS_X509_BADCRL_BAD_MD;
2416 
2417         if( x509_profile_check_pk_alg( profile, crl_list->sig_pk ) != 0 )
2418             flags |= MBEDTLS_X509_BADCRL_BAD_PK;
2419 
2420         md_info = mbedtls_md_info_from_type( crl_list->sig_md );
2421         if( mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash ) != 0 )
2422         {
2423             /* Note: this can't happen except after an internal error */
2424             flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
2425             break;
2426         }
2427 
2428         if( x509_profile_check_key( profile, &ca->pk ) != 0 )
2429             flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
2430 
2431         if( mbedtls_pk_verify_ext( crl_list->sig_pk, crl_list->sig_opts, &ca->pk,
2432                            crl_list->sig_md, hash, mbedtls_md_get_size( md_info ),
2433                            crl_list->sig.p, crl_list->sig.len ) != 0 )
2434         {
2435             flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
2436             break;
2437         }
2438 
2439 #if defined(VENDOR_CUSTOMISE_CHECK_CERT_DATE_C)
2440         /* 定制处理,是否定制校验证书有效期,回调业务函数自己处理 */
2441         if (g_mbedtls_customize_crl_date_checker != NULL)
2442         {
2443             flags |= g_mbedtls_customize_crl_date_checker(crl_list);
2444         }
2445         else    // 没有注册处理函数,按默认规则处理
2446         {
2447             if( mbedtls_x509_time_is_past( &crl_list->next_update ) )
2448                 flags |= MBEDTLS_X509_BADCRL_EXPIRED;
2449 
2450             if( mbedtls_x509_time_is_future( &crl_list->this_update ) )
2451                 flags |= MBEDTLS_X509_BADCRL_FUTURE;
2452         }
2453 #else
2454         /*
2455          * Check for validity of CRL (Do not drop out)
2456          */
2457         if( mbedtls_x509_time_is_past( &crl_list->next_update ) )
2458             flags |= MBEDTLS_X509_BADCRL_EXPIRED;
2459 
2460         if( mbedtls_x509_time_is_future( &crl_list->this_update ) )
2461             flags |= MBEDTLS_X509_BADCRL_FUTURE;
2462 #endif
2463         /*
2464          * Check if certificate is revoked
2465          */
2466         if( mbedtls_x509_crt_is_revoked( crt, crl_list ) )
2467         {
2468             flags |= MBEDTLS_X509_BADCERT_REVOKED;
2469             break;
2470         }
2471 
2472         crl_list = crl_list->next;
2473     }
2474 
2475     return( flags );
2476 }
2477 #endif /* MBEDTLS_X509_CRL_PARSE_C */
2478 
2479 /*
2480  * Check the signature of a certificate by its parent
2481  */
x509_crt_check_signature(const mbedtls_x509_crt * child,mbedtls_x509_crt * parent,mbedtls_x509_crt_restart_ctx * rs_ctx)2482 static int x509_crt_check_signature( const mbedtls_x509_crt *child,
2483                                      mbedtls_x509_crt *parent,
2484                                      mbedtls_x509_crt_restart_ctx *rs_ctx )
2485 {
2486     unsigned char hash[MBEDTLS_MD_MAX_SIZE];
2487     size_t hash_len;
2488 #if !defined(MBEDTLS_USE_PSA_CRYPTO)
2489     const mbedtls_md_info_t *md_info;
2490     md_info = mbedtls_md_info_from_type( child->sig_md );
2491     hash_len = mbedtls_md_get_size( md_info );
2492 
2493     /* Note: hash errors can happen only after an internal error */
2494     if( mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ) != 0 )
2495         return( -1 );
2496 #else
2497     psa_hash_operation_t hash_operation = PSA_HASH_OPERATION_INIT;
2498     psa_algorithm_t hash_alg = mbedtls_psa_translate_md( child->sig_md );
2499 
2500     if( psa_hash_setup( &hash_operation, hash_alg ) != PSA_SUCCESS )
2501         return( -1 );
2502 
2503     if( psa_hash_update( &hash_operation, child->tbs.p, child->tbs.len )
2504         != PSA_SUCCESS )
2505     {
2506         return( -1 );
2507     }
2508 
2509     if( psa_hash_finish( &hash_operation, hash, sizeof( hash ), &hash_len )
2510         != PSA_SUCCESS )
2511     {
2512         return( -1 );
2513     }
2514 #endif /* MBEDTLS_USE_PSA_CRYPTO */
2515     /* Skip expensive computation on obvious mismatch */
2516     if( ! mbedtls_pk_can_do( &parent->pk, child->sig_pk ) )
2517         return( -1 );
2518 
2519 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2520     if( rs_ctx != NULL && child->sig_pk == MBEDTLS_PK_ECDSA )
2521     {
2522         return( mbedtls_pk_verify_restartable( &parent->pk,
2523                     child->sig_md, hash, hash_len,
2524                     child->sig.p, child->sig.len, &rs_ctx->pk ) );
2525     }
2526 #else
2527     (void) rs_ctx;
2528 #endif
2529 
2530     return( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk,
2531                 child->sig_md, hash, hash_len,
2532                 child->sig.p, child->sig.len ) );
2533 }
2534 
2535 /*
2536  * Check if 'parent' is a suitable parent (signing CA) for 'child'.
2537  * Return 0 if yes, -1 if not.
2538  *
2539  * top means parent is a locally-trusted certificate
2540  */
x509_crt_check_parent(const mbedtls_x509_crt * child,const mbedtls_x509_crt * parent,int top)2541 static int x509_crt_check_parent( const mbedtls_x509_crt *child,
2542                                   const mbedtls_x509_crt *parent,
2543                                   int top )
2544 {
2545     int need_ca_bit;
2546 
2547     /* Parent must be the issuer */
2548     if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 )
2549         return( -1 );
2550 
2551     /* Parent must have the basicConstraints CA bit set as a general rule */
2552     need_ca_bit = 1;
2553 
2554     /* Exception: v1/v2 certificates that are locally trusted. */
2555     if( top && parent->version < 3 )
2556         need_ca_bit = 0;
2557 
2558     if( need_ca_bit && ! parent->ca_istrue )
2559         return( -1 );
2560 
2561     if( need_ca_bit &&
2562         mbedtls_x509_crt_check_key_usage( parent, MBEDTLS_X509_KU_KEY_CERT_SIGN ) != 0 )
2563     {
2564         return( -1 );
2565     }
2566 
2567     return( 0 );
2568 }
2569 
2570 /*
2571  * Find a suitable parent for child in candidates, or return NULL.
2572  *
2573  * Here suitable is defined as:
2574  *  1. subject name matches child's issuer
2575  *  2. if necessary, the CA bit is set and key usage allows signing certs
2576  *  3. for trusted roots, the signature is correct
2577  *     (for intermediates, the signature is checked and the result reported)
2578  *  4. pathlen constraints are satisfied
2579  *
2580  * If there's a suitable candidate which is also time-valid, return the first
2581  * such. Otherwise, return the first suitable candidate (or NULL if there is
2582  * none).
2583  *
2584  * The rationale for this rule is that someone could have a list of trusted
2585  * roots with two versions on the same root with different validity periods.
2586  * (At least one user reported having such a list and wanted it to just work.)
2587  * The reason we don't just require time-validity is that generally there is
2588  * only one version, and if it's expired we want the flags to state that
2589  * rather than NOT_TRUSTED, as would be the case if we required it here.
2590  *
2591  * The rationale for rule 3 (signature for trusted roots) is that users might
2592  * have two versions of the same CA with different keys in their list, and the
2593  * way we select the correct one is by checking the signature (as we don't
2594  * rely on key identifier extensions). (This is one way users might choose to
2595  * handle key rollover, another relies on self-issued certs, see [SIRO].)
2596  *
2597  * Arguments:
2598  *  - [in] child: certificate for which we're looking for a parent
2599  *  - [in] candidates: chained list of potential parents
2600  *  - [out] r_parent: parent found (or NULL)
2601  *  - [out] r_signature_is_good: 1 if child signature by parent is valid, or 0
2602  *  - [in] top: 1 if candidates consists of trusted roots, ie we're at the top
2603  *         of the chain, 0 otherwise
2604  *  - [in] path_cnt: number of intermediates seen so far
2605  *  - [in] self_cnt: number of self-signed intermediates seen so far
2606  *         (will never be greater than path_cnt)
2607  *  - [in-out] rs_ctx: context for restarting operations
2608  *
2609  * Return value:
2610  *  - 0 on success
2611  *  - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise
2612  */
x509_crt_find_parent_in(mbedtls_x509_crt * child,mbedtls_x509_crt * candidates,mbedtls_x509_crt ** r_parent,int * r_signature_is_good,int top,unsigned path_cnt,unsigned self_cnt,mbedtls_x509_crt_restart_ctx * rs_ctx)2613 static int x509_crt_find_parent_in(
2614                         mbedtls_x509_crt *child,
2615                         mbedtls_x509_crt *candidates,
2616                         mbedtls_x509_crt **r_parent,
2617                         int *r_signature_is_good,
2618                         int top,
2619                         unsigned path_cnt,
2620                         unsigned self_cnt,
2621                         mbedtls_x509_crt_restart_ctx *rs_ctx )
2622 {
2623     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2624     mbedtls_x509_crt *parent, *fallback_parent;
2625     int signature_is_good = 0, fallback_signature_is_good;
2626 
2627 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2628     /* did we have something in progress? */
2629     if( rs_ctx != NULL && rs_ctx->parent != NULL )
2630     {
2631         /* restore saved state */
2632         parent = rs_ctx->parent;
2633         fallback_parent = rs_ctx->fallback_parent;
2634         fallback_signature_is_good = rs_ctx->fallback_signature_is_good;
2635 
2636         /* clear saved state */
2637         rs_ctx->parent = NULL;
2638         rs_ctx->fallback_parent = NULL;
2639         rs_ctx->fallback_signature_is_good = 0;
2640 
2641         /* resume where we left */
2642         goto check_signature;
2643     }
2644 #endif
2645 
2646     fallback_parent = NULL;
2647     fallback_signature_is_good = 0;
2648 
2649     for( parent = candidates; parent != NULL; parent = parent->next )
2650     {
2651         /* basic parenting skills (name, CA bit, key usage) */
2652         if( x509_crt_check_parent( child, parent, top ) != 0 )
2653             continue;
2654 
2655         /* +1 because stored max_pathlen is 1 higher that the actual value */
2656         if( parent->max_pathlen > 0 &&
2657             (size_t) parent->max_pathlen < 1 + path_cnt - self_cnt )
2658         {
2659             continue;
2660         }
2661 
2662         /* Signature */
2663 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2664 check_signature:
2665 #endif
2666         ret = x509_crt_check_signature( child, parent, rs_ctx );
2667 
2668 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2669         if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
2670         {
2671             /* save state */
2672             rs_ctx->parent = parent;
2673             rs_ctx->fallback_parent = fallback_parent;
2674             rs_ctx->fallback_signature_is_good = fallback_signature_is_good;
2675 
2676             return( ret );
2677         }
2678 #else
2679         (void) ret;
2680 #endif
2681 
2682         signature_is_good = ret == 0;
2683         if( top && ! signature_is_good )
2684             continue;
2685 
2686 #if defined(VENDOR_CUSTOMISE_CHECK_CERT_DATE_C)
2687         /* 定制处理,是否定制校验证书有效期,回调业务函数自己处理 */
2688         if (g_mbedtls_customize_cert_date_checker != NULL)
2689         {
2690             if (g_mbedtls_customize_cert_date_checker(parent) != 0)
2691             {
2692                 if( fallback_parent == NULL )
2693                 {
2694                     fallback_parent = parent;
2695                     fallback_signature_is_good = signature_is_good;
2696                 }
2697                 continue;
2698             }
2699         }
2700         else /* 如果没有挂回调函数,则按官方默认方式处理 */
2701         {
2702             /* optional time check */
2703             if( mbedtls_x509_time_is_past( &parent->valid_to ) ||
2704                 mbedtls_x509_time_is_future( &parent->valid_from ) )
2705             {
2706                 if( fallback_parent == NULL )
2707                 {
2708                     fallback_parent = parent;
2709                     fallback_signature_is_good = signature_is_good;
2710                 }
2711 
2712                 continue;
2713             }
2714         }
2715 #else
2716         /* optional time check */
2717         if( mbedtls_x509_time_is_past( &parent->valid_to ) ||
2718             mbedtls_x509_time_is_future( &parent->valid_from ) )
2719         {
2720             if( fallback_parent == NULL )
2721             {
2722                 fallback_parent = parent;
2723                 fallback_signature_is_good = signature_is_good;
2724             }
2725 
2726             continue;
2727         }
2728 #endif
2729 
2730         *r_parent = parent;
2731         *r_signature_is_good = signature_is_good;
2732 
2733         break;
2734     }
2735 
2736     if( parent == NULL )
2737     {
2738         *r_parent = fallback_parent;
2739         *r_signature_is_good = fallback_signature_is_good;
2740     }
2741 
2742     return( 0 );
2743 }
2744 
2745 /*
2746  * Find a parent in trusted CAs or the provided chain, or return NULL.
2747  *
2748  * Searches in trusted CAs first, and return the first suitable parent found
2749  * (see find_parent_in() for definition of suitable).
2750  *
2751  * Arguments:
2752  *  - [in] child: certificate for which we're looking for a parent, followed
2753  *         by a chain of possible intermediates
2754  *  - [in] trust_ca: list of locally trusted certificates
2755  *  - [out] parent: parent found (or NULL)
2756  *  - [out] parent_is_trusted: 1 if returned `parent` is trusted, or 0
2757  *  - [out] signature_is_good: 1 if child signature by parent is valid, or 0
2758  *  - [in] path_cnt: number of links in the chain so far (EE -> ... -> child)
2759  *  - [in] self_cnt: number of self-signed certs in the chain so far
2760  *         (will always be no greater than path_cnt)
2761  *  - [in-out] rs_ctx: context for restarting operations
2762  *
2763  * Return value:
2764  *  - 0 on success
2765  *  - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise
2766  */
x509_crt_find_parent(mbedtls_x509_crt * child,mbedtls_x509_crt * trust_ca,mbedtls_x509_crt ** parent,int * parent_is_trusted,int * signature_is_good,unsigned path_cnt,unsigned self_cnt,mbedtls_x509_crt_restart_ctx * rs_ctx)2767 static int x509_crt_find_parent(
2768                         mbedtls_x509_crt *child,
2769                         mbedtls_x509_crt *trust_ca,
2770                         mbedtls_x509_crt **parent,
2771                         int *parent_is_trusted,
2772                         int *signature_is_good,
2773                         unsigned path_cnt,
2774                         unsigned self_cnt,
2775                         mbedtls_x509_crt_restart_ctx *rs_ctx )
2776 {
2777     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2778     mbedtls_x509_crt *search_list;
2779 
2780     *parent_is_trusted = 1;
2781 
2782 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2783     /* restore then clear saved state if we have some stored */
2784     if( rs_ctx != NULL && rs_ctx->parent_is_trusted != -1 )
2785     {
2786         *parent_is_trusted = rs_ctx->parent_is_trusted;
2787         rs_ctx->parent_is_trusted = -1;
2788     }
2789 #endif
2790 
2791     while( 1 ) {
2792         search_list = *parent_is_trusted ? trust_ca : child->next;
2793 
2794         ret = x509_crt_find_parent_in( child, search_list,
2795                                        parent, signature_is_good,
2796                                        *parent_is_trusted,
2797                                        path_cnt, self_cnt, rs_ctx );
2798 
2799 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2800         if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
2801         {
2802             /* save state */
2803             rs_ctx->parent_is_trusted = *parent_is_trusted;
2804             return( ret );
2805         }
2806 #else
2807         (void) ret;
2808 #endif
2809 
2810         /* stop here if found or already in second iteration */
2811         if( *parent != NULL || *parent_is_trusted == 0 )
2812             break;
2813 
2814         /* prepare second iteration */
2815         *parent_is_trusted = 0;
2816     }
2817 
2818     /* extra precaution against mistakes in the caller */
2819     if( *parent == NULL )
2820     {
2821         *parent_is_trusted = 0;
2822         *signature_is_good = 0;
2823     }
2824 
2825     return( 0 );
2826 }
2827 
2828 /*
2829  * Check if an end-entity certificate is locally trusted
2830  *
2831  * Currently we require such certificates to be self-signed (actually only
2832  * check for self-issued as self-signatures are not checked)
2833  */
x509_crt_check_ee_locally_trusted(mbedtls_x509_crt * crt,mbedtls_x509_crt * trust_ca)2834 static int x509_crt_check_ee_locally_trusted(
2835                     mbedtls_x509_crt *crt,
2836                     mbedtls_x509_crt *trust_ca )
2837 {
2838     mbedtls_x509_crt *cur;
2839 
2840     /* must be self-issued */
2841     if( x509_name_cmp( &crt->issuer, &crt->subject ) != 0 )
2842         return( -1 );
2843 
2844     /* look for an exact match with trusted cert */
2845     for( cur = trust_ca; cur != NULL; cur = cur->next )
2846     {
2847         if( crt->raw.len == cur->raw.len &&
2848             memcmp( crt->raw.p, cur->raw.p, crt->raw.len ) == 0 )
2849         {
2850             return( 0 );
2851         }
2852     }
2853 
2854     /* too bad */
2855     return( -1 );
2856 }
2857 
2858 /*
2859  * Build and verify a certificate chain
2860  *
2861  * Given a peer-provided list of certificates EE, C1, ..., Cn and
2862  * a list of trusted certs R1, ... Rp, try to build and verify a chain
2863  *      EE, Ci1, ... Ciq [, Rj]
2864  * such that every cert in the chain is a child of the next one,
2865  * jumping to a trusted root as early as possible.
2866  *
2867  * Verify that chain and return it with flags for all issues found.
2868  *
2869  * Special cases:
2870  * - EE == Rj -> return a one-element list containing it
2871  * - EE, Ci1, ..., Ciq cannot be continued with a trusted root
2872  *   -> return that chain with NOT_TRUSTED set on Ciq
2873  *
2874  * Tests for (aspects of) this function should include at least:
2875  * - trusted EE
2876  * - EE -> trusted root
2877  * - EE -> intermediate CA -> trusted root
2878  * - if relevant: EE untrusted
2879  * - if relevant: EE -> intermediate, untrusted
2880  * with the aspect under test checked at each relevant level (EE, int, root).
2881  * For some aspects longer chains are required, but usually length 2 is
2882  * enough (but length 1 is not in general).
2883  *
2884  * Arguments:
2885  *  - [in] crt: the cert list EE, C1, ..., Cn
2886  *  - [in] trust_ca: the trusted list R1, ..., Rp
2887  *  - [in] ca_crl, profile: as in verify_with_profile()
2888  *  - [out] ver_chain: the built and verified chain
2889  *      Only valid when return value is 0, may contain garbage otherwise!
2890  *      Restart note: need not be the same when calling again to resume.
2891  *  - [in-out] rs_ctx: context for restarting operations
2892  *
2893  * Return value:
2894  *  - non-zero if the chain could not be fully built and examined
2895  *  - 0 is the chain was successfully built and examined,
2896  *      even if it was found to be invalid
2897  */
x509_crt_verify_chain(mbedtls_x509_crt * crt,mbedtls_x509_crt * trust_ca,mbedtls_x509_crl * ca_crl,mbedtls_x509_crt_ca_cb_t f_ca_cb,void * p_ca_cb,const mbedtls_x509_crt_profile * profile,mbedtls_x509_crt_verify_chain * ver_chain,mbedtls_x509_crt_restart_ctx * rs_ctx)2898 static int x509_crt_verify_chain(
2899                 mbedtls_x509_crt *crt,
2900                 mbedtls_x509_crt *trust_ca,
2901                 mbedtls_x509_crl *ca_crl,
2902                 mbedtls_x509_crt_ca_cb_t f_ca_cb,
2903                 void *p_ca_cb,
2904                 const mbedtls_x509_crt_profile *profile,
2905                 mbedtls_x509_crt_verify_chain *ver_chain,
2906                 mbedtls_x509_crt_restart_ctx *rs_ctx )
2907 {
2908     /* Don't initialize any of those variables here, so that the compiler can
2909      * catch potential issues with jumping ahead when restarting */
2910     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2911     uint32_t *flags;
2912     mbedtls_x509_crt_verify_chain_item *cur;
2913     mbedtls_x509_crt *child;
2914     mbedtls_x509_crt *parent;
2915     int parent_is_trusted;
2916     int child_is_trusted;
2917     int signature_is_good;
2918     unsigned self_cnt;
2919     mbedtls_x509_crt *cur_trust_ca = NULL;
2920 
2921 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2922     /* resume if we had an operation in progress */
2923     if( rs_ctx != NULL && rs_ctx->in_progress == x509_crt_rs_find_parent )
2924     {
2925         /* restore saved state */
2926         *ver_chain = rs_ctx->ver_chain; /* struct copy */
2927         self_cnt = rs_ctx->self_cnt;
2928 
2929         /* restore derived state */
2930         cur = &ver_chain->items[ver_chain->len - 1];
2931         child = cur->crt;
2932         flags = &cur->flags;
2933 
2934         goto find_parent;
2935     }
2936 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
2937 
2938     child = crt;
2939     self_cnt = 0;
2940     parent_is_trusted = 0;
2941     child_is_trusted = 0;
2942 
2943     while( 1 ) {
2944         /* Add certificate to the verification chain */
2945         cur = &ver_chain->items[ver_chain->len];
2946         cur->crt = child;
2947         cur->flags = 0;
2948         ver_chain->len++;
2949         flags = &cur->flags;
2950 
2951 #if defined(VENDOR_CUSTOMISE_CHECK_CERT_DATE_C)
2952         /* 定制处理,是否定制校验证书有效期,回调业务函数自己处理 */
2953         if (g_mbedtls_customize_cert_date_checker != NULL)
2954         {
2955             *flags |= g_mbedtls_customize_cert_date_checker( child );
2956         }
2957         else    // 没有注册处理函数,按默认规则处理
2958         {
2959             /* Check time-validity (all certificates) */
2960             if( mbedtls_x509_time_is_past( &child->valid_to ) )
2961                 *flags |= MBEDTLS_X509_BADCERT_EXPIRED;
2962 
2963             if( mbedtls_x509_time_is_future( &child->valid_from ) )
2964                 *flags |= MBEDTLS_X509_BADCERT_FUTURE;
2965         }
2966 #else
2967         /* Check time-validity (all certificates) */
2968         if( mbedtls_x509_time_is_past( &child->valid_to ) )
2969             *flags |= MBEDTLS_X509_BADCERT_EXPIRED;
2970 
2971         if( mbedtls_x509_time_is_future( &child->valid_from ) )
2972             *flags |= MBEDTLS_X509_BADCERT_FUTURE;
2973 #endif
2974 
2975         /* Stop here for trusted roots (but not for trusted EE certs) */
2976         if( child_is_trusted )
2977             return( 0 );
2978 
2979         /* Check signature algorithm: MD & PK algs */
2980         if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
2981             *flags |= MBEDTLS_X509_BADCERT_BAD_MD;
2982 
2983         if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
2984             *flags |= MBEDTLS_X509_BADCERT_BAD_PK;
2985 
2986         /* Special case: EE certs that are locally trusted */
2987         if( ver_chain->len == 1 &&
2988             x509_crt_check_ee_locally_trusted( child, trust_ca ) == 0 )
2989         {
2990             return( 0 );
2991         }
2992 
2993 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2994 find_parent:
2995 #endif
2996 
2997         /* Obtain list of potential trusted signers from CA callback,
2998          * or use statically provided list. */
2999 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
3000         if( f_ca_cb != NULL )
3001         {
3002             mbedtls_x509_crt_free( ver_chain->trust_ca_cb_result );
3003             mbedtls_free( ver_chain->trust_ca_cb_result );
3004             ver_chain->trust_ca_cb_result = NULL;
3005 
3006             ret = f_ca_cb( p_ca_cb, child, &ver_chain->trust_ca_cb_result );
3007             if( ret != 0 )
3008                 return( MBEDTLS_ERR_X509_FATAL_ERROR );
3009 
3010             cur_trust_ca = ver_chain->trust_ca_cb_result;
3011         }
3012         else
3013 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
3014         {
3015             ((void) f_ca_cb);
3016             ((void) p_ca_cb);
3017             cur_trust_ca = trust_ca;
3018         }
3019 
3020         /* Look for a parent in trusted CAs or up the chain */
3021         ret = x509_crt_find_parent( child, cur_trust_ca, &parent,
3022                                        &parent_is_trusted, &signature_is_good,
3023                                        ver_chain->len - 1, self_cnt, rs_ctx );
3024 
3025 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
3026         if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
3027         {
3028             /* save state */
3029             rs_ctx->in_progress = x509_crt_rs_find_parent;
3030             rs_ctx->self_cnt = self_cnt;
3031             rs_ctx->ver_chain = *ver_chain; /* struct copy */
3032 
3033             return( ret );
3034         }
3035 #else
3036         (void) ret;
3037 #endif
3038 
3039         /* No parent? We're done here */
3040         if( parent == NULL )
3041         {
3042             *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
3043             return( 0 );
3044         }
3045 
3046         /* Count intermediate self-issued (not necessarily self-signed) certs.
3047          * These can occur with some strategies for key rollover, see [SIRO],
3048          * and should be excluded from max_pathlen checks. */
3049         if( ver_chain->len != 1 &&
3050             x509_name_cmp( &child->issuer, &child->subject ) == 0 )
3051         {
3052             self_cnt++;
3053         }
3054 
3055         /* path_cnt is 0 for the first intermediate CA,
3056          * and if parent is trusted it's not an intermediate CA */
3057         if( ! parent_is_trusted &&
3058             ver_chain->len > MBEDTLS_X509_MAX_INTERMEDIATE_CA )
3059         {
3060             /* return immediately to avoid overflow the chain array */
3061             return( MBEDTLS_ERR_X509_FATAL_ERROR );
3062         }
3063 
3064         /* signature was checked while searching parent */
3065         if( ! signature_is_good )
3066             *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
3067 
3068         /* check size of signing key */
3069         if( x509_profile_check_key( profile, &parent->pk ) != 0 )
3070             *flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
3071 
3072 #if defined(MBEDTLS_X509_CRL_PARSE_C)
3073         /* Check trusted CA's CRL for the given crt */
3074         *flags |= x509_crt_verifycrl( child, parent, ca_crl, profile );
3075 #else
3076         (void) ca_crl;
3077 #endif
3078 
3079         /* prepare for next iteration */
3080         child = parent;
3081         parent = NULL;
3082         child_is_trusted = parent_is_trusted;
3083         signature_is_good = 0;
3084     }
3085 }
3086 
3087 /*
3088  * Check for CN match
3089  */
x509_crt_check_cn(const mbedtls_x509_buf * name,const char * cn,size_t cn_len)3090 static int x509_crt_check_cn( const mbedtls_x509_buf *name,
3091                               const char *cn, size_t cn_len )
3092 {
3093     /* try exact match */
3094     if( name->len == cn_len &&
3095         x509_memcasecmp( cn, name->p, cn_len ) == 0 )
3096     {
3097         return( 0 );
3098     }
3099 
3100     /* try wildcard match */
3101     if( x509_check_wildcard( cn, name ) == 0 )
3102     {
3103         return( 0 );
3104     }
3105 
3106     return( -1 );
3107 }
3108 
3109 /*
3110  * Check for SAN match, see RFC 5280 Section 4.2.1.6
3111  */
x509_crt_check_san(const mbedtls_x509_buf * name,const char * cn,size_t cn_len)3112 static int x509_crt_check_san( const mbedtls_x509_buf *name,
3113                                const char *cn, size_t cn_len )
3114 {
3115     const unsigned char san_type = (unsigned char) name->tag &
3116                                    MBEDTLS_ASN1_TAG_VALUE_MASK;
3117 
3118     /* dNSName */
3119     if( san_type == MBEDTLS_X509_SAN_DNS_NAME )
3120         return( x509_crt_check_cn( name, cn, cn_len ) );
3121 
3122     /* (We may handle other types here later.) */
3123 
3124     /* Unrecognized type */
3125     return( -1 );
3126 }
3127 
3128 #if defined(VENDOR_ONT_CHECK_CERT_CN_NAME_C)
3129 /*****************************************************************************
3130  * @brief 定制,ONT产品特殊处理,用于校验证书的CN名
3131  *        mbedtls默认只校验证书CN,如果不对,则返回错误。
3132  *        ONT定制情况下,另外再校验name
3133  * @param crt 证书
3134  * @param cn CN名
3135  * @param flags 输出校验标志
3136 ******************************************************************************/
x509_crt_verify_name(const mbedtls_x509_crt * crt,const char * cn,uint32_t * flags)3137 static void x509_crt_verify_name( const mbedtls_x509_crt *crt,
3138                                   const char *cn,
3139                                   uint32_t *flags )
3140 {
3141     const mbedtls_x509_name *name;
3142     const mbedtls_x509_sequence *cur = NULL;
3143     size_t cn_len = strlen( cn );
3144 
3145     if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
3146     {
3147         for( cur = &crt->subject_alt_names; cur != NULL; cur = cur->next )
3148         {
3149             if( x509_crt_check_san( &cur->buf, cn, cn_len ) == 0 )
3150                 break;
3151         }
3152     }
3153 
3154     for( name = &crt->subject; name != NULL; name = name->next )
3155     {
3156         if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 &&
3157             x509_crt_check_cn( &name->val, cn, cn_len ) == 0 )
3158         {
3159             break;
3160         }
3161     }
3162 
3163     if( name == NULL && cur == NULL )
3164         *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
3165 }
3166 #else
3167 /*
3168  * Verify the requested CN - only call this if cn is not NULL!
3169  */
x509_crt_verify_name(const mbedtls_x509_crt * crt,const char * cn,uint32_t * flags)3170 static void x509_crt_verify_name( const mbedtls_x509_crt *crt,
3171                                   const char *cn,
3172                                   uint32_t *flags )
3173 {
3174     const mbedtls_x509_name *name;
3175     const mbedtls_x509_sequence *cur;
3176     size_t cn_len = strlen( cn );
3177 
3178     if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
3179     {
3180         for( cur = &crt->subject_alt_names; cur != NULL; cur = cur->next )
3181         {
3182             if( x509_crt_check_san( &cur->buf, cn, cn_len ) == 0 )
3183                 break;
3184         }
3185 
3186         if( cur == NULL )
3187             *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
3188     }
3189     else
3190     {
3191         for( name = &crt->subject; name != NULL; name = name->next )
3192         {
3193             if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 &&
3194                 x509_crt_check_cn( &name->val, cn, cn_len ) == 0 )
3195             {
3196                 break;
3197             }
3198         }
3199 
3200         if( name == NULL )
3201             *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
3202     }
3203 }
3204 #endif
3205 
3206 /*
3207  * Merge the flags for all certs in the chain, after calling callback
3208  */
x509_crt_merge_flags_with_cb(uint32_t * flags,const mbedtls_x509_crt_verify_chain * ver_chain,int (* f_vrfy)(void *,mbedtls_x509_crt *,int,uint32_t *),void * p_vrfy)3209 static int x509_crt_merge_flags_with_cb(
3210            uint32_t *flags,
3211            const mbedtls_x509_crt_verify_chain *ver_chain,
3212            int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
3213            void *p_vrfy )
3214 {
3215     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3216     unsigned i;
3217     uint32_t cur_flags;
3218     const mbedtls_x509_crt_verify_chain_item *cur;
3219 
3220     for( i = ver_chain->len; i != 0; --i )
3221     {
3222         cur = &ver_chain->items[i-1];
3223         cur_flags = cur->flags;
3224 
3225         if( NULL != f_vrfy )
3226             if( ( ret = f_vrfy( p_vrfy, cur->crt, (int) i-1, &cur_flags ) ) != 0 )
3227                 return( ret );
3228 
3229         *flags |= cur_flags;
3230     }
3231 
3232     return( 0 );
3233 }
3234 
3235 /*
3236  * Verify the certificate validity, with profile, restartable version
3237  *
3238  * This function:
3239  *  - checks the requested CN (if any)
3240  *  - checks the type and size of the EE cert's key,
3241  *    as that isn't done as part of chain building/verification currently
3242  *  - builds and verifies the chain
3243  *  - then calls the callback and merges the flags
3244  *
3245  * The parameters pairs `trust_ca`, `ca_crl` and `f_ca_cb`, `p_ca_cb`
3246  * are mutually exclusive: If `f_ca_cb != NULL`, it will be used by the
3247  * verification routine to search for trusted signers, and CRLs will
3248  * be disabled. Otherwise, `trust_ca` will be used as the static list
3249  * of trusted signers, and `ca_crl` will be use as the static list
3250  * of CRLs.
3251  */
x509_crt_verify_restartable_ca_cb(mbedtls_x509_crt * crt,mbedtls_x509_crt * trust_ca,mbedtls_x509_crl * ca_crl,mbedtls_x509_crt_ca_cb_t f_ca_cb,void * p_ca_cb,const mbedtls_x509_crt_profile * profile,const char * cn,uint32_t * flags,int (* f_vrfy)(void *,mbedtls_x509_crt *,int,uint32_t *),void * p_vrfy,mbedtls_x509_crt_restart_ctx * rs_ctx)3252 static int x509_crt_verify_restartable_ca_cb( mbedtls_x509_crt *crt,
3253                      mbedtls_x509_crt *trust_ca,
3254                      mbedtls_x509_crl *ca_crl,
3255                      mbedtls_x509_crt_ca_cb_t f_ca_cb,
3256                      void *p_ca_cb,
3257                      const mbedtls_x509_crt_profile *profile,
3258                      const char *cn, uint32_t *flags,
3259                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
3260                      void *p_vrfy,
3261                      mbedtls_x509_crt_restart_ctx *rs_ctx )
3262 {
3263     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3264     mbedtls_pk_type_t pk_type;
3265     mbedtls_x509_crt_verify_chain ver_chain;
3266     uint32_t ee_flags;
3267 
3268     *flags = 0;
3269     ee_flags = 0;
3270     x509_crt_verify_chain_reset( &ver_chain );
3271 
3272     if( profile == NULL )
3273     {
3274         ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;
3275         goto exit;
3276     }
3277 
3278     /* check name if requested */
3279     if( cn != NULL )
3280         x509_crt_verify_name( crt, cn, &ee_flags );
3281 
3282     /* Check the type and size of the key */
3283     pk_type = mbedtls_pk_get_type( &crt->pk );
3284 
3285     if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
3286         ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK;
3287 
3288     if( x509_profile_check_key( profile, &crt->pk ) != 0 )
3289         ee_flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
3290 
3291     /* Check the chain */
3292     ret = x509_crt_verify_chain( crt, trust_ca, ca_crl,
3293                                  f_ca_cb, p_ca_cb, profile,
3294                                  &ver_chain, rs_ctx );
3295 
3296     if( ret != 0 )
3297         goto exit;
3298 
3299     /* Merge end-entity flags */
3300     ver_chain.items[0].flags |= ee_flags;
3301 
3302     /* Build final flags, calling callback on the way if any */
3303     ret = x509_crt_merge_flags_with_cb( flags, &ver_chain, f_vrfy, p_vrfy );
3304 
3305 exit:
3306 
3307 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
3308     mbedtls_x509_crt_free( ver_chain.trust_ca_cb_result );
3309     mbedtls_free( ver_chain.trust_ca_cb_result );
3310     ver_chain.trust_ca_cb_result = NULL;
3311 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
3312 
3313 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
3314     if( rs_ctx != NULL && ret != MBEDTLS_ERR_ECP_IN_PROGRESS )
3315         mbedtls_x509_crt_restart_free( rs_ctx );
3316 #endif
3317 
3318     /* prevent misuse of the vrfy callback - VERIFY_FAILED would be ignored by
3319      * the SSL module for authmode optional, but non-zero return from the
3320      * callback means a fatal error so it shouldn't be ignored */
3321     if( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED )
3322         ret = MBEDTLS_ERR_X509_FATAL_ERROR;
3323 
3324     if( ret != 0 )
3325     {
3326         *flags = (uint32_t) -1;
3327         return( ret );
3328     }
3329 
3330     if( *flags != 0 )
3331         return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
3332 
3333     return( 0 );
3334 }
3335 
3336 
3337 /*
3338  * Verify the certificate validity (default profile, not restartable)
3339  */
mbedtls_x509_crt_verify(mbedtls_x509_crt * crt,mbedtls_x509_crt * trust_ca,mbedtls_x509_crl * ca_crl,const char * cn,uint32_t * flags,int (* f_vrfy)(void *,mbedtls_x509_crt *,int,uint32_t *),void * p_vrfy)3340 int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
3341                      mbedtls_x509_crt *trust_ca,
3342                      mbedtls_x509_crl *ca_crl,
3343                      const char *cn, uint32_t *flags,
3344                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
3345                      void *p_vrfy )
3346 {
3347     return( x509_crt_verify_restartable_ca_cb( crt, trust_ca, ca_crl,
3348                                          NULL, NULL,
3349                                          &mbedtls_x509_crt_profile_default,
3350                                          cn, flags,
3351                                          f_vrfy, p_vrfy, NULL ) );
3352 }
3353 
3354 /*
3355  * Verify the certificate validity (user-chosen profile, not restartable)
3356  */
mbedtls_x509_crt_verify_with_profile(mbedtls_x509_crt * crt,mbedtls_x509_crt * trust_ca,mbedtls_x509_crl * ca_crl,const mbedtls_x509_crt_profile * profile,const char * cn,uint32_t * flags,int (* f_vrfy)(void *,mbedtls_x509_crt *,int,uint32_t *),void * p_vrfy)3357 int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
3358                      mbedtls_x509_crt *trust_ca,
3359                      mbedtls_x509_crl *ca_crl,
3360                      const mbedtls_x509_crt_profile *profile,
3361                      const char *cn, uint32_t *flags,
3362                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
3363                      void *p_vrfy )
3364 {
3365     return( x509_crt_verify_restartable_ca_cb( crt, trust_ca, ca_crl,
3366                                                  NULL, NULL,
3367                                                  profile, cn, flags,
3368                                                  f_vrfy, p_vrfy, NULL ) );
3369 }
3370 
3371 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
3372 /*
3373  * Verify the certificate validity (user-chosen profile, CA callback,
3374  *                                  not restartable).
3375  */
mbedtls_x509_crt_verify_with_ca_cb(mbedtls_x509_crt * crt,mbedtls_x509_crt_ca_cb_t f_ca_cb,void * p_ca_cb,const mbedtls_x509_crt_profile * profile,const char * cn,uint32_t * flags,int (* f_vrfy)(void *,mbedtls_x509_crt *,int,uint32_t *),void * p_vrfy)3376 int mbedtls_x509_crt_verify_with_ca_cb( mbedtls_x509_crt *crt,
3377                      mbedtls_x509_crt_ca_cb_t f_ca_cb,
3378                      void *p_ca_cb,
3379                      const mbedtls_x509_crt_profile *profile,
3380                      const char *cn, uint32_t *flags,
3381                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
3382                      void *p_vrfy )
3383 {
3384     return( x509_crt_verify_restartable_ca_cb( crt, NULL, NULL,
3385                                                  f_ca_cb, p_ca_cb,
3386                                                  profile, cn, flags,
3387                                                  f_vrfy, p_vrfy, NULL ) );
3388 }
3389 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
3390 
mbedtls_x509_crt_verify_restartable(mbedtls_x509_crt * crt,mbedtls_x509_crt * trust_ca,mbedtls_x509_crl * ca_crl,const mbedtls_x509_crt_profile * profile,const char * cn,uint32_t * flags,int (* f_vrfy)(void *,mbedtls_x509_crt *,int,uint32_t *),void * p_vrfy,mbedtls_x509_crt_restart_ctx * rs_ctx)3391 int mbedtls_x509_crt_verify_restartable( mbedtls_x509_crt *crt,
3392                      mbedtls_x509_crt *trust_ca,
3393                      mbedtls_x509_crl *ca_crl,
3394                      const mbedtls_x509_crt_profile *profile,
3395                      const char *cn, uint32_t *flags,
3396                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
3397                      void *p_vrfy,
3398                      mbedtls_x509_crt_restart_ctx *rs_ctx )
3399 {
3400     return( x509_crt_verify_restartable_ca_cb( crt, trust_ca, ca_crl,
3401                                                  NULL, NULL,
3402                                                  profile, cn, flags,
3403                                                  f_vrfy, p_vrfy, rs_ctx ) );
3404 }
3405 
3406 
3407 /*
3408  * Initialize a certificate chain
3409  */
mbedtls_x509_crt_init(mbedtls_x509_crt * crt)3410 void mbedtls_x509_crt_init( mbedtls_x509_crt *crt )
3411 {
3412     memset( crt, 0, sizeof(mbedtls_x509_crt) );
3413 }
3414 
3415 /*
3416  * Unallocate all certificate data
3417  */
mbedtls_x509_crt_free(mbedtls_x509_crt * crt)3418 void mbedtls_x509_crt_free( mbedtls_x509_crt *crt )
3419 {
3420     mbedtls_x509_crt *cert_cur = crt;
3421     mbedtls_x509_crt *cert_prv;
3422     mbedtls_x509_name *name_cur;
3423     mbedtls_x509_name *name_prv;
3424     mbedtls_x509_sequence *seq_cur;
3425     mbedtls_x509_sequence *seq_prv;
3426 
3427     if( crt == NULL )
3428         return;
3429 
3430     do
3431     {
3432         mbedtls_pk_free( &cert_cur->pk );
3433 
3434 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
3435         mbedtls_free( cert_cur->sig_opts );
3436 #endif
3437 
3438         name_cur = cert_cur->issuer.next;
3439         while( name_cur != NULL )
3440         {
3441             name_prv = name_cur;
3442             name_cur = name_cur->next;
3443             mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
3444             mbedtls_free( name_prv );
3445         }
3446 
3447         name_cur = cert_cur->subject.next;
3448         while( name_cur != NULL )
3449         {
3450             name_prv = name_cur;
3451             name_cur = name_cur->next;
3452             mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
3453             mbedtls_free( name_prv );
3454         }
3455 
3456         seq_cur = cert_cur->ext_key_usage.next;
3457         while( seq_cur != NULL )
3458         {
3459             seq_prv = seq_cur;
3460             seq_cur = seq_cur->next;
3461             mbedtls_platform_zeroize( seq_prv,
3462                                       sizeof( mbedtls_x509_sequence ) );
3463             mbedtls_free( seq_prv );
3464         }
3465 
3466         seq_cur = cert_cur->subject_alt_names.next;
3467         while( seq_cur != NULL )
3468         {
3469             seq_prv = seq_cur;
3470             seq_cur = seq_cur->next;
3471             mbedtls_platform_zeroize( seq_prv,
3472                                       sizeof( mbedtls_x509_sequence ) );
3473             mbedtls_free( seq_prv );
3474         }
3475 
3476         seq_cur = cert_cur->certificate_policies.next;
3477         while( seq_cur != NULL )
3478         {
3479             seq_prv = seq_cur;
3480             seq_cur = seq_cur->next;
3481             mbedtls_platform_zeroize( seq_prv,
3482                                       sizeof( mbedtls_x509_sequence ) );
3483             mbedtls_free( seq_prv );
3484         }
3485 
3486         if( cert_cur->raw.p != NULL && cert_cur->own_buffer )
3487         {
3488             mbedtls_platform_zeroize( cert_cur->raw.p, cert_cur->raw.len );
3489             mbedtls_free( cert_cur->raw.p );
3490         }
3491 
3492         cert_cur = cert_cur->next;
3493     }
3494     while( cert_cur != NULL );
3495 
3496     cert_cur = crt;
3497     do
3498     {
3499         cert_prv = cert_cur;
3500         cert_cur = cert_cur->next;
3501 
3502         mbedtls_platform_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) );
3503         if( cert_prv != crt )
3504             mbedtls_free( cert_prv );
3505     }
3506     while( cert_cur != NULL );
3507 }
3508 
3509 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
3510 /*
3511  * Initialize a restart context
3512  */
mbedtls_x509_crt_restart_init(mbedtls_x509_crt_restart_ctx * ctx)3513 void mbedtls_x509_crt_restart_init( mbedtls_x509_crt_restart_ctx *ctx )
3514 {
3515     mbedtls_pk_restart_init( &ctx->pk );
3516 
3517     ctx->parent = NULL;
3518     ctx->fallback_parent = NULL;
3519     ctx->fallback_signature_is_good = 0;
3520 
3521     ctx->parent_is_trusted = -1;
3522 
3523     ctx->in_progress = x509_crt_rs_none;
3524     ctx->self_cnt = 0;
3525     x509_crt_verify_chain_reset( &ctx->ver_chain );
3526 }
3527 
3528 /*
3529  * Free the components of a restart context
3530  */
mbedtls_x509_crt_restart_free(mbedtls_x509_crt_restart_ctx * ctx)3531 void mbedtls_x509_crt_restart_free( mbedtls_x509_crt_restart_ctx *ctx )
3532 {
3533     if( ctx == NULL )
3534         return;
3535 
3536     mbedtls_pk_restart_free( &ctx->pk );
3537     mbedtls_x509_crt_restart_init( ctx );
3538 }
3539 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
3540 
3541 #endif /* MBEDTLS_X509_CRT_PARSE_C */
3542