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