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