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