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