Coverage Report

Created: 2025-07-01 06:54

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