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