Coverage Report

Created: 2026-10-28 07:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/crypto/x509/v3_purp.c
Line
Count
Source
1
/*
2
 * Copyright 1999-2026 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
#include <stdio.h>
11
#include "internal/cryptlib.h"
12
#include "internal/numbers.h"
13
#include <openssl/x509v3.h>
14
#include <openssl/x509_vfy.h>
15
#include "crypto/x509.h"
16
#include "internal/tsan_assist.h"
17
#include "x509_local.h"
18
#include "crypto/objects/obj_dat.h"
19
#include "crypto/siphash.h"
20
#include <openssl/rand.h>
21
22
static int check_ssl_ca(const X509 *x);
23
static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
24
    int non_leaf);
25
static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
26
    int non_leaf);
27
static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x,
28
    int non_leaf);
29
static int purpose_smime(const X509 *x, int non_leaf);
30
static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x,
31
    int non_leaf);
32
static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x,
33
    int non_leaf);
34
static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x,
35
    int non_leaf);
36
static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x,
37
    int non_leaf);
38
static int check_purpose_code_sign(const X509_PURPOSE *xp, const X509 *x,
39
    int non_leaf);
40
static int no_check_purpose(const X509_PURPOSE *xp, const X509 *x,
41
    int non_leaf);
42
static int check_purpose_ocsp_helper(const X509_PURPOSE *xp, const X509 *x,
43
    int non_leaf);
44
static int check_name_constraints(const NAME_CONSTRAINTS *nc);
45
46
static int xp_cmp(const X509_PURPOSE *const *a, const X509_PURPOSE *const *b);
47
static void xptable_free(X509_PURPOSE *p);
48
49
/* note that the id must be unique and for the standard entries == idx + 1 */
50
static X509_PURPOSE xstandard[] = {
51
    { X509_PURPOSE_SSL_CLIENT, X509_TRUST_SSL_CLIENT, 0,
52
        check_purpose_ssl_client, "SSL client", "sslclient", NULL },
53
    { X509_PURPOSE_SSL_SERVER, X509_TRUST_SSL_SERVER, 0,
54
        check_purpose_ssl_server, "SSL server", "sslserver", NULL },
55
    { X509_PURPOSE_NS_SSL_SERVER, X509_TRUST_SSL_SERVER, 0,
56
        check_purpose_ns_ssl_server, "Netscape SSL server", "nssslserver", NULL },
57
    { X509_PURPOSE_SMIME_SIGN, X509_TRUST_EMAIL, 0, check_purpose_smime_sign,
58
        "S/MIME signing", "smimesign", NULL },
59
    { X509_PURPOSE_SMIME_ENCRYPT, X509_TRUST_EMAIL, 0,
60
        check_purpose_smime_encrypt, "S/MIME encryption", "smimeencrypt", NULL },
61
    { X509_PURPOSE_CRL_SIGN, X509_TRUST_COMPAT, 0, check_purpose_crl_sign,
62
        "CRL signing", "crlsign", NULL },
63
    { X509_PURPOSE_ANY, X509_TRUST_DEFAULT, 0, no_check_purpose,
64
        "Any Purpose", "any",
65
        NULL },
66
    { X509_PURPOSE_OCSP_HELPER, X509_TRUST_COMPAT, 0, check_purpose_ocsp_helper,
67
        "OCSP helper", "ocsphelper", NULL },
68
    { X509_PURPOSE_TIMESTAMP_SIGN, X509_TRUST_TSA, 0,
69
        check_purpose_timestamp_sign, "Time Stamp signing", "timestampsign",
70
        NULL },
71
    { X509_PURPOSE_CODE_SIGN, X509_TRUST_OBJECT_SIGN, 0,
72
        check_purpose_code_sign, "Code signing", "codesign",
73
        NULL },
74
};
75
76
0
#define X509_PURPOSE_COUNT OSSL_NELEM(xstandard)
77
78
/* the id must be unique, but there may be gaps and maybe table is not sorted */
79
static STACK_OF(X509_PURPOSE) *xptable = NULL;
80
81
static int xp_cmp(const X509_PURPOSE *const *a, const X509_PURPOSE *const *b)
82
0
{
83
0
    return (*a)->purpose - (*b)->purpose;
84
0
}
85
86
int X509_check_purpose(const X509 *x, int id, int non_leaf)
87
0
{
88
0
    int idx;
89
0
    const X509_PURPOSE *pt;
90
91
    /*
92
     * TODO: This cast can be dropped when https://github.com/openssl/openssl/pull/30067
93
     * gets merged
94
     */
95
0
    if (!ossl_x509v3_cache_extensions((X509 *)x))
96
0
        return -1;
97
0
    if (id == -1)
98
0
        return 1;
99
100
0
    idx = X509_PURPOSE_get_by_id(id);
101
0
    if (idx == -1)
102
0
        return -1;
103
0
    pt = X509_PURPOSE_get0(idx);
104
0
    return pt->check_purpose(pt, x, non_leaf);
105
0
}
106
107
/* resets to default (any) purpose if purpose == X509_PURPOSE_DEFAULT_ANY (0) */
108
int X509_PURPOSE_set(int *p, int purpose)
109
0
{
110
0
    if (purpose != X509_PURPOSE_DEFAULT_ANY && X509_PURPOSE_get_by_id(purpose) == -1) {
111
0
        ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_PURPOSE);
112
0
        return 0;
113
0
    }
114
0
    *p = purpose;
115
0
    return 1;
116
0
}
117
118
int X509_PURPOSE_get_count(void)
119
0
{
120
0
    if (!xptable)
121
0
        return X509_PURPOSE_COUNT;
122
0
    return sk_X509_PURPOSE_num(xptable) + X509_PURPOSE_COUNT;
123
0
}
124
125
/* find smallest identifier not yet taken - note there might be gaps */
126
int X509_PURPOSE_get_unused_id(ossl_unused OSSL_LIB_CTX *libctx)
127
0
{
128
0
    int id = X509_PURPOSE_MAX + 1;
129
130
0
    while (X509_PURPOSE_get_by_id(id) != -1)
131
0
        id++;
132
0
    return id; /* is guaranteed to be unique and > X509_PURPOSE_MAX and != 0 */
133
0
}
134
135
X509_PURPOSE *X509_PURPOSE_get0(int idx)
136
0
{
137
0
    if (idx < 0)
138
0
        return NULL;
139
0
    if (idx < (int)X509_PURPOSE_COUNT)
140
0
        return xstandard + idx;
141
0
    return sk_X509_PURPOSE_value(xptable, idx - X509_PURPOSE_COUNT);
142
0
}
143
144
int X509_PURPOSE_get_by_sname(const char *sname)
145
0
{
146
0
    int i;
147
0
    X509_PURPOSE *xptmp;
148
149
0
    for (i = 0; i < X509_PURPOSE_get_count(); i++) {
150
0
        xptmp = X509_PURPOSE_get0(i);
151
0
        if (strcmp(xptmp->sname, sname) == 0)
152
0
            return i;
153
0
    }
154
0
    return -1;
155
0
}
156
157
/* Returns -1 on error, else an index => 0 in standard/extended purpose table */
158
int X509_PURPOSE_get_by_id(int purpose)
159
0
{
160
0
    X509_PURPOSE tmp;
161
0
    int idx;
162
163
0
    if (purpose >= X509_PURPOSE_MIN && purpose <= X509_PURPOSE_MAX)
164
0
        return purpose - X509_PURPOSE_MIN;
165
0
    if (xptable == NULL)
166
0
        return -1;
167
0
    tmp.purpose = purpose;
168
0
    idx = sk_X509_PURPOSE_find(xptable, &tmp);
169
0
    if (idx < 0)
170
0
        return -1;
171
0
    return idx + X509_PURPOSE_COUNT;
172
0
}
173
174
/*
175
 * Add purpose entry identified by |sname|. |id| must be >= X509_PURPOSE_MIN.
176
 * May also be used to modify existing entry, including changing its id.
177
 */
178
int X509_PURPOSE_add(int id, int trust, int flags,
179
    int (*ck)(const X509_PURPOSE *, const X509 *, int),
180
    const char *name, const char *sname, void *arg)
181
0
{
182
0
    int old_id = 0;
183
0
    int idx;
184
0
    X509_PURPOSE *ptmp;
185
186
0
    if (id < X509_PURPOSE_MIN) {
187
0
        ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_PURPOSE);
188
0
        return 0;
189
0
    }
190
0
    if (trust < X509_TRUST_DEFAULT || name == NULL || sname == NULL || ck == NULL) {
191
0
        ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_INVALID_ARGUMENT);
192
0
        return 0;
193
0
    }
194
195
    /* This is set according to what we change: application can't set it */
196
0
    flags &= ~X509_PURPOSE_DYNAMIC;
197
    /* This will always be set for application modified trust entries */
198
0
    flags |= X509_PURPOSE_DYNAMIC_NAME;
199
200
    /* Get existing entry if any */
201
0
    idx = X509_PURPOSE_get_by_sname(sname);
202
0
    if (idx == -1) { /* Need a new entry */
203
0
        if (X509_PURPOSE_get_by_id(id) != -1) {
204
0
            ERR_raise(ERR_LIB_X509V3, X509V3_R_PURPOSE_NOT_UNIQUE);
205
0
            return 0;
206
0
        }
207
0
        if ((ptmp = OPENSSL_malloc(sizeof(*ptmp))) == NULL)
208
0
            return 0;
209
0
        ptmp->flags = X509_PURPOSE_DYNAMIC;
210
0
    } else {
211
0
        ptmp = X509_PURPOSE_get0(idx);
212
0
        old_id = ptmp->purpose;
213
0
        if (id != old_id && X509_PURPOSE_get_by_id(id) != -1) {
214
0
            ERR_raise(ERR_LIB_X509V3, X509V3_R_PURPOSE_NOT_UNIQUE);
215
0
            return 0;
216
0
        }
217
0
    }
218
219
    /* OPENSSL_free existing name if dynamic */
220
0
    if ((ptmp->flags & X509_PURPOSE_DYNAMIC_NAME) != 0) {
221
0
        OPENSSL_free(ptmp->name);
222
0
        OPENSSL_free(ptmp->sname);
223
0
    }
224
    /* Dup supplied name */
225
0
    ptmp->name = OPENSSL_strdup(name);
226
0
    ptmp->sname = OPENSSL_strdup(sname);
227
0
    if (ptmp->name == NULL || ptmp->sname == NULL)
228
0
        goto err;
229
    /* Keep the dynamic flag of existing entry */
230
0
    ptmp->flags &= X509_PURPOSE_DYNAMIC;
231
    /* Set all other flags */
232
0
    ptmp->flags |= flags;
233
234
0
    ptmp->purpose = id;
235
0
    ptmp->trust = trust;
236
0
    ptmp->check_purpose = ck;
237
0
    ptmp->usr_data = arg;
238
239
    /* If its a new entry manage the dynamic table */
240
0
    if (idx == -1) {
241
0
        if (xptable == NULL
242
0
            && (xptable = sk_X509_PURPOSE_new(xp_cmp)) == NULL) {
243
0
            ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
244
0
            goto err;
245
0
        }
246
0
        if (!sk_X509_PURPOSE_push(xptable, ptmp)) {
247
0
            ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
248
0
            goto err;
249
0
        }
250
0
    } else if (id != old_id) {
251
        /* on changing existing entry id, make sure to reset 'sorted' */
252
0
        (void)sk_X509_PURPOSE_set(xptable, idx, ptmp);
253
0
    }
254
0
    return 1;
255
0
err:
256
0
    if (idx == -1) {
257
0
        OPENSSL_free(ptmp->name);
258
0
        OPENSSL_free(ptmp->sname);
259
0
        OPENSSL_free(ptmp);
260
0
    }
261
0
    return 0;
262
0
}
263
264
static void xptable_free(X509_PURPOSE *p)
265
0
{
266
0
    if (p == NULL)
267
0
        return;
268
0
    if ((p->flags & X509_PURPOSE_DYNAMIC) != 0) {
269
0
        if ((p->flags & X509_PURPOSE_DYNAMIC_NAME) != 0) {
270
0
            OPENSSL_free(p->name);
271
0
            OPENSSL_free(p->sname);
272
0
        }
273
0
        OPENSSL_free(p);
274
0
    }
275
0
}
276
277
void X509_PURPOSE_cleanup(void)
278
0
{
279
0
    sk_X509_PURPOSE_pop_free(xptable, xptable_free);
280
0
    xptable = NULL;
281
0
}
282
283
int X509_PURPOSE_get_id(const X509_PURPOSE *xp)
284
0
{
285
0
    return xp->purpose;
286
0
}
287
288
char *X509_PURPOSE_get0_name(const X509_PURPOSE *xp)
289
0
{
290
0
    return xp->name;
291
0
}
292
293
char *X509_PURPOSE_get0_sname(const X509_PURPOSE *xp)
294
0
{
295
0
    return xp->sname;
296
0
}
297
298
int X509_PURPOSE_get_trust(const X509_PURPOSE *xp)
299
0
{
300
0
    return xp->trust;
301
0
}
302
303
static int nid_cmp(const int *a, const int *b)
304
0
{
305
0
    return *a - *b;
306
0
}
307
308
DECLARE_OBJ_BSEARCH_CMP_FN(int, int, nid);
309
IMPLEMENT_OBJ_BSEARCH_CMP_FN(int, int, nid);
310
311
int X509_supported_extension(const X509_EXTENSION *ex)
312
0
{
313
    /*
314
     * This table is a list of the NIDs of supported extensions: that is
315
     * those which are used by the verify process. If an extension is
316
     * critical and doesn't appear in this list then the verify process will
317
     * normally reject the certificate. The list must be kept in numerical
318
     * order because it will be searched using bsearch.
319
     */
320
0
    static const int supported_nids[] = {
321
0
        NID_netscape_cert_type, /* 71 */
322
0
        NID_key_usage, /* 83 */
323
0
        NID_subject_alt_name, /* 85 */
324
0
        NID_basic_constraints, /* 87 */
325
0
        NID_certificate_policies, /* 89 */
326
0
        NID_crl_distribution_points, /* 103 */
327
0
        NID_ext_key_usage, /* 126 */
328
0
#ifndef OPENSSL_NO_RFC3779
329
0
        NID_sbgp_ipAddrBlock, /* 290 */
330
0
        NID_sbgp_autonomousSysNum, /* 291 */
331
0
#endif
332
0
        NID_id_pkix_OCSP_noCheck, /* 369 */
333
0
        NID_policy_constraints, /* 401 */
334
0
        NID_proxyCertInfo, /* 663 */
335
0
        NID_name_constraints, /* 666 */
336
0
        NID_policy_mappings, /* 747 */
337
0
        NID_inhibit_any_policy /* 748 */
338
0
    };
339
340
0
    int ex_nid = OBJ_obj2nid(X509_EXTENSION_get_object(ex));
341
342
0
    if (ex_nid == NID_undef)
343
0
        return 0;
344
345
0
    if (OBJ_bsearch_nid(&ex_nid, supported_nids, OSSL_NELEM(supported_nids)))
346
0
        return 1;
347
0
    return 0;
348
0
}
349
350
/*
351
 * Returns 1 on success, 0 if x is invalid.
352
 *
353
 * The full name of a nameRelativeToCRLIssuer distribution point is not
354
 * computed here.  Doing so for every parsed certificate cost an
355
 * X509_NAME_dup() of the issuer name per relative distribution point,
356
 * which a certificate with many such entries could turn into hundreds of
357
 * megabytes of heap on a plain TLS handshake, while the result is only
358
 * needed when a CRL is actually being matched against the certificate.
359
 * That name is now built on demand in the CRL checking code instead.
360
 */
361
static int setup_dp(DIST_POINT *dp)
362
0
{
363
0
    if (dp->distpoint == NULL && sk_GENERAL_NAME_num(dp->CRLissuer) <= 0) {
364
0
        ERR_raise(ERR_LIB_X509, X509_R_INVALID_DISTPOINT);
365
0
        return 0;
366
0
    }
367
0
    if (dp->reasons != NULL) {
368
0
        if (dp->reasons->length > 0)
369
0
            dp->dp_reasons = dp->reasons->data[0];
370
0
        if (dp->reasons->length > 1)
371
0
            dp->dp_reasons |= (dp->reasons->data[1] << 8);
372
0
        dp->dp_reasons &= CRLDP_ALL_REASONS;
373
0
    } else {
374
0
        dp->dp_reasons = CRLDP_ALL_REASONS;
375
0
    }
376
0
    return 1;
377
0
}
378
379
/* Return 1 on success, 0 if x is invalid. */
380
static int setup_crldp(const X509 *x, STACK_OF(DIST_POINT) **tmp_crldp)
381
0
{
382
0
    int i;
383
384
0
    *tmp_crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, &i, NULL);
385
0
    if (*tmp_crldp == NULL && i != -1)
386
0
        return 0;
387
388
0
    for (i = 0; i < sk_DIST_POINT_num(*tmp_crldp); i++) {
389
0
        if (!setup_dp(sk_DIST_POINT_value(*tmp_crldp, i)))
390
0
            return 0;
391
0
    }
392
0
    return 1;
393
0
}
394
395
/* Check that issuer public key algorithm matches subject signature algorithm */
396
static int check_sig_alg_match(const EVP_PKEY *issuer_key, const X509 *subject)
397
0
{
398
0
    int subj_sig_nid;
399
400
0
    if (issuer_key == NULL)
401
0
        return X509_V_ERR_NO_ISSUER_PUBLIC_KEY;
402
0
    if (OBJ_find_sigid_algs(OBJ_obj2nid(subject->cert_info.signature.algorithm),
403
0
            NULL, &subj_sig_nid)
404
0
        == 0)
405
0
        return X509_V_ERR_UNSUPPORTED_SIGNATURE_ALGORITHM;
406
0
    if (EVP_PKEY_is_a(issuer_key, OBJ_nid2sn(subj_sig_nid))
407
0
        || (EVP_PKEY_is_a(issuer_key, "RSA") && subj_sig_nid == NID_rsassaPss))
408
0
        return X509_V_OK;
409
0
    return X509_V_ERR_SIGNATURE_ALGORITHM_MISMATCH;
410
0
}
411
412
/*
413
 * Per-scan SipHash keying for the duplicate-extension fall-back table.
414
 *
415
 * Standard extensions have an assigned NID and are deduplicated with the O(1)
416
 * bitset in scan_ext_flags(). Only unknown or dynamically registered OIDs,
417
 * whose bytes are fully attacker-controlled on an untrusted certificate, reach
418
 * the hash table. An unkeyed hash would let an attacker precompute colliding
419
 * OIDs and drive the table into O(n^2) chain walks (hash flooding). Hash the
420
 * OID with SipHash under a random key drawn once per scan, mirroring the
421
 * defense in ssl/quic/quic_lcidm.c.
422
 */
423
typedef struct {
424
    const ASN1_OBJECT *obj;
425
    const uint64_t *key; /* 128-bit SipHash key owned by scan_ext_flags */
426
} oid_hte;
427
428
static unsigned long oid_hash(const void *p)
429
0
{
430
0
    const oid_hte *e = (const oid_hte *)p;
431
0
    SIPHASH sip = { 0 };
432
0
    unsigned char digest[SIPHASH_MIN_DIGEST_SIZE];
433
0
    unsigned long v = 0;
434
435
0
    if (!SipHash_set_hash_size(&sip, SIPHASH_MIN_DIGEST_SIZE))
436
0
        return 0;
437
0
    if (!SipHash_Init(&sip, (const unsigned char *)e->key, 0, 0))
438
0
        return 0;
439
0
    SipHash_Update(&sip, (const unsigned char *)e->obj->data, e->obj->length);
440
441
0
    if (!SipHash_Final(&sip, digest, sizeof(digest)))
442
0
        return 0;
443
0
    memcpy(&v, digest, sizeof(v) < sizeof(digest) ? sizeof(v) : sizeof(digest));
444
0
    return v;
445
0
}
446
447
static int oid_cmp(const void *a, const void *b)
448
0
{
449
0
    return OBJ_cmp(((const oid_hte *)a)->obj, ((const oid_hte *)b)->obj);
450
0
}
451
452
/*
453
 * Scan all extensions of a certificate to collect extension-related flags.
454
 * Detects duplicate extensions (RFC 5280 section 4.2), the presence of a
455
 * freshest CRL extension and unsupported critical extensions.
456
 *
457
 * In the future, if needed, this scanning function could return the index
458
 * of the offending extension on error, allowing the caller to identify which
459
 * extension caused the problem and report it via ERR_raise_data().
460
 */
461
static void scan_ext_flags(const X509 *x509, uint32_t *flags)
462
0
{
463
0
    OPENSSL_LHASH *h = NULL;
464
0
    oid_hte *arr = NULL;
465
0
    size_t num_entries = 0;
466
0
    uint64_t k[2]; /* random SipHash key for the fall-back table */
467
0
    uint8_t ex_bitset[(NUM_NID + 7) / 8];
468
0
    int count = X509_get_ext_count(x509);
469
470
0
    memset(ex_bitset, 0, sizeof(ex_bitset));
471
    /* A certificate MUST NOT include more than one instance of an extension. */
472
0
    for (int i = 0; i < count; i++) {
473
0
        const X509_EXTENSION *ex = X509_get_ext(x509, i);
474
0
        const ASN1_OBJECT *a = X509_EXTENSION_get_object(ex);
475
0
        int nid = OBJ_obj2nid(a);
476
477
        /*
478
         * Known NIDs within the build-time bitset limit are checked for
479
         * duplicates in constant time. Unknown OIDs and dynamically registered
480
         * NIDs that exceed the limit fall back to duplicate detection via a
481
         * hash table.
482
         */
483
0
        if (nid > NID_undef && nid < NUM_NID) {
484
0
            unsigned int ex_bit = nid;
485
486
0
            if ((ex_bitset[ex_bit >> 3] & (1u << (ex_bit & 7))) != 0) {
487
0
                *flags |= EXFLAG_DUPLICATE;
488
0
                break;
489
0
            }
490
0
            ex_bitset[ex_bit >> 3] |= (1u << (ex_bit & 7));
491
0
        } else {
492
            /*
493
             * Extensions with unknown NID (NID_undef) and dynamically
494
             * registered NIDs are handled here by hashing the OID (data/length).
495
             * A zero-length OID should not reach this point, but we check for
496
             * it anyway and assign the EXFLAG_INVALID flag if it does.
497
             */
498
0
            if (a->length < 1) {
499
0
                *flags |= EXFLAG_INVALID;
500
0
                break;
501
0
            }
502
            /*
503
             * Create the table and draw a fresh random SipHash key the first
504
             * time an attacker-controlled OID is seen, so unkeyed hashing
505
             * cannot be used to force O(n^2) collisions (hash flooding).
506
             *
507
             * The key and the entry wrappers remain valid for the duration of
508
             * the scan; the table never outlives this function.
509
             *
510
             * If the table cannot be set up or an insert fails, fail closed
511
             * with EXFLAG_INVALID, as ossl_x509v3_cache_extensions() does for
512
             * any other extension it cannot process. Leaving the loop
513
             * silently would skip not only the duplicate check but also the
514
             * unsupported-critical check for this and every later extension.
515
             */
516
0
            if (h == NULL) {
517
0
                OSSL_LIB_CTX *libctx = NULL;
518
519
0
                ossl_x509_get0_libctx(x509, &libctx, NULL);
520
0
                if (RAND_bytes_ex(libctx, (unsigned char *)k, sizeof(k), 0) <= 0
521
0
                    || (arr = OPENSSL_malloc_array(count, sizeof(*arr))) == NULL
522
0
                    || (h = OPENSSL_LH_new(oid_hash, oid_cmp)) == NULL) {
523
0
                    *flags |= EXFLAG_INVALID;
524
0
                    break;
525
0
                }
526
0
            }
527
0
            arr[num_entries].obj = a;
528
0
            arr[num_entries].key = k;
529
0
            if (OPENSSL_LH_insert(h, &arr[num_entries]) != NULL) {
530
0
                *flags |= EXFLAG_DUPLICATE;
531
0
                break;
532
0
            }
533
0
            if (OPENSSL_LH_error(h) != 0) {
534
0
                *flags |= EXFLAG_INVALID;
535
0
                break;
536
0
            }
537
0
            num_entries++;
538
0
        }
539
0
        if (nid == NID_freshest_crl)
540
0
            *flags |= EXFLAG_FRESHEST;
541
0
        if (!X509_EXTENSION_get_critical(ex))
542
0
            continue;
543
0
        if (!X509_supported_extension(ex)) {
544
0
            *flags |= EXFLAG_CRITICAL;
545
0
            break;
546
0
        }
547
0
    }
548
0
    OPENSSL_LH_free(h);
549
0
    OPENSSL_free(arr);
550
0
}
551
552
0
#define V1_ROOT (EXFLAG_V1 | EXFLAG_SS)
553
#define ku_reject(x, usage) \
554
0
    (((x)->ex_flags & EXFLAG_KUSAGE) != 0 && ((x)->ex_kusage & (usage)) == 0)
555
#define xku_reject(x, usage) \
556
0
    (((x)->ex_flags & EXFLAG_XKUSAGE) != 0 && ((x)->ex_xkusage & (usage)) == 0)
557
#define ns_reject(x, usage) \
558
0
    (((x)->ex_flags & EXFLAG_NSCERT) != 0 && ((x)->ex_nscert & (usage)) == 0)
559
560
/*
561
 * Cache info on various X.509v3 extensions and further derived information,
562
 * e.g., if cert 'x' is self-issued, in x->ex_flags and other internal fields.
563
 * x->fingerprint is filled in, or else EXFLAG_NO_FINGERPRINT is set in
564
 * x->ex_flags.
565
 * Set EXFLAG_INVALID and return 0 in case the certificate is invalid.
566
 *
567
 * This is usually called by side-effect on objects, and forces us to keep
568
 * mutable X509 objects around. We should really make this go away.
569
 * In the interest of being able to do so, this function explicitly takes
570
 * a const argument and casts away const.
571
 */
572
int ossl_x509v3_cache_extensions(const X509 *const_x)
573
0
{
574
0
    BASIC_CONSTRAINTS *bs;
575
0
    PROXY_CERT_INFO_EXTENSION *pci;
576
0
    ASN1_BIT_STRING *usage;
577
0
    ASN1_BIT_STRING *ns;
578
0
    EXTENDED_KEY_USAGE *extusage;
579
0
    int i;
580
0
    int res;
581
0
    uint32_t tmp_ex_flags;
582
0
    unsigned char tmp_fingerprint[OSSL_X509_FINGERPRINT_SIZE];
583
0
    long tmp_ex_pathlen;
584
0
    long tmp_ex_pcpathlen;
585
0
    uint32_t tmp_ex_kusage;
586
0
    uint32_t tmp_ex_xkusage;
587
0
    uint32_t tmp_ex_nscert;
588
0
    ASN1_OCTET_STRING *tmp_skid = NULL;
589
0
    AUTHORITY_KEYID *tmp_akid = NULL;
590
0
    STACK_OF(GENERAL_NAME) *tmp_altname = NULL;
591
0
    NAME_CONSTRAINTS *tmp_nc = NULL;
592
0
    STACK_OF(DIST_POINT) *tmp_crldp = NULL;
593
0
#ifndef OPENSSL_NO_RFC3779
594
0
    STACK_OF(IPAddressFamily) *tmp_rfc3779_addr = NULL;
595
0
    struct ASIdentifiers_st *tmp_rfc3779_asid = NULL;
596
0
#endif
597
0
    int ret = 0;
598
599
0
#ifdef tsan_ld_acq
600
    /* Fast lock-free check, see end of the function for details. */
601
0
    if (tsan_ld_acq((TSAN_QUALIFIER int *)&const_x->ex_cached)) {
602
0
        ret = (const_x->ex_flags & EXFLAG_INVALID) == 0;
603
0
        goto done;
604
0
    }
605
0
#endif
606
607
0
    if (!CRYPTO_THREAD_read_lock(const_x->lock))
608
0
        goto done;
609
0
    tmp_ex_flags = const_x->ex_flags;
610
0
    tmp_ex_pcpathlen = const_x->ex_pcpathlen;
611
0
    tmp_ex_kusage = const_x->ex_kusage;
612
0
    tmp_ex_nscert = const_x->ex_nscert;
613
614
0
    if ((tmp_ex_flags & EXFLAG_SET) != 0) { /* Cert has already been processed */
615
0
        CRYPTO_THREAD_unlock(const_x->lock);
616
0
        ret = (tmp_ex_flags & EXFLAG_INVALID) == 0;
617
0
        goto done;
618
0
    }
619
620
0
    ERR_set_mark();
621
622
0
    if (!ossl_x509_internal_fingerprint(ASN1_ITEM_rptr(X509), const_x,
623
0
            tmp_fingerprint))
624
0
        tmp_ex_flags |= EXFLAG_NO_FINGERPRINT;
625
626
    /* V1 should mean no extensions ... */
627
0
    if (X509_get_version(const_x) == X509_VERSION_1)
628
0
        tmp_ex_flags |= EXFLAG_V1;
629
630
    /* Handle basic constraints */
631
0
    tmp_ex_pathlen = -1;
632
0
    if ((bs = X509_get_ext_d2i(const_x, NID_basic_constraints, &i, NULL)) != NULL) {
633
0
        if (bs->ca)
634
0
            tmp_ex_flags |= EXFLAG_CA;
635
0
        if (bs->pathlen != NULL) {
636
            /*
637
             * The error case !bs->ca is checked by check_chain()
638
             * in case ctx->param->flags & X509_V_FLAG_X509_STRICT
639
             */
640
0
            if (bs->pathlen->type == V_ASN1_NEG_INTEGER) {
641
0
                ERR_raise(ERR_LIB_X509V3, X509V3_R_NEGATIVE_PATHLEN);
642
0
                tmp_ex_flags |= EXFLAG_INVALID;
643
0
            } else {
644
0
                tmp_ex_pathlen = ASN1_INTEGER_get(bs->pathlen);
645
0
                if (tmp_ex_pathlen < 0 || tmp_ex_pathlen > 255) {
646
0
                    ERR_raise(ERR_LIB_X509V3, X509V3_R_PATHLEN_TOO_LARGE);
647
0
                    tmp_ex_flags |= EXFLAG_INVALID;
648
0
                    tmp_ex_pathlen = -1;
649
0
                }
650
0
            }
651
0
        }
652
0
        BASIC_CONSTRAINTS_free(bs);
653
0
        tmp_ex_flags |= EXFLAG_BCONS;
654
0
    } else if (i != -1) {
655
0
        tmp_ex_flags |= EXFLAG_INVALID;
656
0
    }
657
658
    /* Handle proxy certificates */
659
0
    if ((pci = X509_get_ext_d2i(const_x, NID_proxyCertInfo, &i, NULL)) != NULL) {
660
0
        if ((tmp_ex_flags & EXFLAG_CA) != 0
661
0
            || X509_get_ext_by_NID(const_x, NID_subject_alt_name, -1) >= 0
662
0
            || X509_get_ext_by_NID(const_x, NID_issuer_alt_name, -1) >= 0) {
663
0
            tmp_ex_flags |= EXFLAG_INVALID;
664
0
        }
665
0
        if (pci->pcPathLengthConstraint != NULL) {
666
0
            if (pci->pcPathLengthConstraint->type == V_ASN1_NEG_INTEGER) {
667
0
                ERR_raise(ERR_LIB_X509V3, X509V3_R_NEGATIVE_PATHLEN);
668
0
                tmp_ex_flags |= EXFLAG_INVALID;
669
0
                tmp_ex_pcpathlen = -1;
670
0
            } else {
671
0
                tmp_ex_pcpathlen = ASN1_INTEGER_get(pci->pcPathLengthConstraint);
672
0
                if (tmp_ex_pcpathlen < 0 || tmp_ex_pcpathlen > 255) {
673
0
                    ERR_raise(ERR_LIB_X509V3, X509V3_R_PATHLEN_TOO_LARGE);
674
0
                    tmp_ex_flags |= EXFLAG_INVALID;
675
0
                    tmp_ex_pcpathlen = -1;
676
0
                }
677
0
            }
678
0
        } else {
679
0
            tmp_ex_pcpathlen = -1;
680
0
        }
681
0
        PROXY_CERT_INFO_EXTENSION_free(pci);
682
0
        tmp_ex_flags |= EXFLAG_PROXY;
683
0
    } else if (i != -1) {
684
0
        tmp_ex_flags |= EXFLAG_INVALID;
685
0
    }
686
687
    /* Handle (basic) key usage */
688
0
    if ((usage = X509_get_ext_d2i(const_x, NID_key_usage, &i, NULL)) != NULL) {
689
0
        tmp_ex_kusage = 0;
690
0
        if (usage->length > 0) {
691
0
            tmp_ex_kusage = usage->data[0];
692
0
            if (usage->length > 1)
693
0
                tmp_ex_kusage |= usage->data[1] << 8;
694
0
        }
695
0
        tmp_ex_flags |= EXFLAG_KUSAGE;
696
0
        ASN1_BIT_STRING_free(usage);
697
        /* Check for empty key usage according to RFC 5280 section 4.2.1.3 */
698
0
        if (tmp_ex_kusage == 0) {
699
0
            ERR_raise(ERR_LIB_X509V3, X509V3_R_EMPTY_KEY_USAGE);
700
0
            tmp_ex_flags |= EXFLAG_INVALID;
701
0
        }
702
0
    } else if (i != -1) {
703
0
        tmp_ex_flags |= EXFLAG_INVALID;
704
0
    }
705
706
    /* Handle extended key usage */
707
0
    tmp_ex_xkusage = 0;
708
0
    if ((extusage = X509_get_ext_d2i(const_x, NID_ext_key_usage, &i, NULL)) != NULL) {
709
0
        tmp_ex_flags |= EXFLAG_XKUSAGE;
710
0
        for (i = 0; i < sk_ASN1_OBJECT_num(extusage); i++) {
711
0
            switch (OBJ_obj2nid(sk_ASN1_OBJECT_value(extusage, i))) {
712
0
            case NID_server_auth:
713
0
                tmp_ex_xkusage |= XKU_SSL_SERVER;
714
0
                break;
715
0
            case NID_client_auth:
716
0
                tmp_ex_xkusage |= XKU_SSL_CLIENT;
717
0
                break;
718
0
            case NID_email_protect:
719
0
                tmp_ex_xkusage |= XKU_SMIME;
720
0
                break;
721
0
            case NID_code_sign:
722
0
                tmp_ex_xkusage |= XKU_CODE_SIGN;
723
0
                break;
724
0
            case NID_ms_sgc:
725
0
            case NID_ns_sgc:
726
0
                tmp_ex_xkusage |= XKU_SGC;
727
0
                break;
728
0
            case NID_OCSP_sign:
729
0
                tmp_ex_xkusage |= XKU_OCSP_SIGN;
730
0
                break;
731
0
            case NID_time_stamp:
732
0
                tmp_ex_xkusage |= XKU_TIMESTAMP;
733
0
                break;
734
0
            case NID_dvcs:
735
0
                tmp_ex_xkusage |= XKU_DVCS;
736
0
                break;
737
0
            case NID_anyExtendedKeyUsage:
738
0
                tmp_ex_xkusage |= XKU_ANYEKU;
739
0
                break;
740
0
            default:
741
                /* Ignore unknown extended key usage */
742
0
                break;
743
0
            }
744
0
        }
745
0
        sk_ASN1_OBJECT_pop_free(extusage, ASN1_OBJECT_free);
746
0
    } else if (i != -1) {
747
0
        tmp_ex_flags |= EXFLAG_INVALID;
748
0
    }
749
750
    /* Handle legacy Netscape extension */
751
0
    if ((ns = X509_get_ext_d2i(const_x, NID_netscape_cert_type, &i, NULL)) != NULL) {
752
0
        if (ns->length > 0)
753
0
            tmp_ex_nscert = ns->data[0];
754
0
        else
755
0
            tmp_ex_nscert = 0;
756
0
        tmp_ex_flags |= EXFLAG_NSCERT;
757
0
        ASN1_BIT_STRING_free(ns);
758
0
    } else if (i != -1) {
759
0
        tmp_ex_flags |= EXFLAG_INVALID;
760
0
    }
761
762
    /* Handle subject key identifier and issuer/authority key identifier */
763
0
    tmp_skid = X509_get_ext_d2i(const_x, NID_subject_key_identifier, &i, NULL);
764
0
    if (tmp_skid == NULL && i != -1)
765
0
        tmp_ex_flags |= EXFLAG_INVALID;
766
767
0
    tmp_akid = X509_get_ext_d2i(const_x, NID_authority_key_identifier, &i, NULL);
768
0
    if (tmp_akid == NULL && i != -1)
769
0
        tmp_ex_flags |= EXFLAG_INVALID;
770
771
    /* Setting EXFLAG_SS is equivalent to ossl_x509_likely_issued(const_x, const_x) == X509_V_OK */
772
0
    if (X509_NAME_cmp(X509_get_subject_name(const_x), X509_get_issuer_name(const_x)) == 0) {
773
0
        tmp_ex_flags |= EXFLAG_SI; /* Certificate is self-issued: subject == issuer */
774
        /*
775
         * When the SKID is missing, which is rare for self-issued certs,
776
         * we could afford doing the (accurate) actual self-signature check, but
777
         * decided against it for efficiency reasons and according to RFC 5280,
778
         * CA certs MUST have an SKID and non-root certs MUST have an AKID.
779
         *
780
         * The cached const_x->skid is not populated until the write-lock
781
         * publication below, so the keyid comparison is done directly
782
         * against tmp_skid.  X509_check_akid() is retained for its serial
783
         * number and issuer name checks.
784
         */
785
0
        if ((tmp_akid == NULL || tmp_akid->keyid == NULL || tmp_skid == NULL
786
0
                || ASN1_OCTET_STRING_cmp(tmp_akid->keyid, tmp_skid) == 0)
787
0
            && X509_check_akid(const_x, tmp_akid) == X509_V_OK
788
0
            && check_sig_alg_match(X509_get0_pubkey(const_x), const_x) == X509_V_OK) {
789
            /*
790
             * Assume self-signed if the signature alg matches the pkey alg and
791
             * AKID is missing or matches respective fields in the same cert
792
             * Not checking if any given key usage extension allows signing.
793
             */
794
0
            tmp_ex_flags |= EXFLAG_SS;
795
0
        }
796
0
    }
797
798
    /* Handle subject alternative names and various other extensions */
799
0
    tmp_altname = X509_get_ext_d2i(const_x, NID_subject_alt_name, &i, NULL);
800
0
    if (tmp_altname == NULL && i != -1)
801
0
        tmp_ex_flags |= EXFLAG_INVALID;
802
0
    tmp_nc = X509_get_ext_d2i(const_x, NID_name_constraints, &i, NULL);
803
0
    if (tmp_nc == NULL && i != -1)
804
0
        tmp_ex_flags |= EXFLAG_INVALID;
805
0
    if (!check_name_constraints(tmp_nc))
806
0
        tmp_ex_flags |= EXFLAG_INVALID;
807
808
    /* Handle CRL distribution point entries */
809
0
    res = setup_crldp(const_x, &tmp_crldp);
810
0
    if (res == 0)
811
0
        tmp_ex_flags |= EXFLAG_INVALID;
812
813
0
#ifndef OPENSSL_NO_RFC3779
814
0
    tmp_rfc3779_addr = X509_get_ext_d2i(const_x, NID_sbgp_ipAddrBlock, &i, NULL);
815
0
    if (tmp_rfc3779_addr == NULL && i != -1)
816
0
        tmp_ex_flags |= EXFLAG_INVALID;
817
818
0
    tmp_rfc3779_asid = X509_get_ext_d2i(const_x, NID_sbgp_autonomousSysNum, &i, NULL);
819
0
    if (tmp_rfc3779_asid == NULL && i != -1)
820
0
        tmp_ex_flags |= EXFLAG_INVALID;
821
0
#endif
822
823
0
    scan_ext_flags(const_x, &tmp_ex_flags);
824
825
0
    tmp_ex_flags |= EXFLAG_SET; /* Indicate that cert has been processed */
826
0
    ERR_pop_to_mark();
827
828
0
    CRYPTO_THREAD_unlock(const_x->lock);
829
    /*
830
     * Now that we've done all the compute intensive work under read lock
831
     * do all the updating under a write lock
832
     */
833
0
    if (!CRYPTO_THREAD_write_lock(const_x->lock))
834
0
        goto done;
835
836
    /* See if another thread updated this certificate before we got the write lock. */
837
0
    if ((const_x->ex_flags & EXFLAG_SET) != 0) { /* Cert has already been processed */
838
0
        CRYPTO_THREAD_unlock(const_x->lock);
839
0
        ret = (const_x->ex_flags & EXFLAG_INVALID) == 0;
840
0
        goto done;
841
0
    }
842
843
    /* Otherwise, we have the lock, set the cached fields in the cert. */
844
0
    ((X509 *)const_x)->ex_flags = tmp_ex_flags;
845
0
    ((X509 *)const_x)->ex_pathlen = tmp_ex_pathlen;
846
0
    ((X509 *)const_x)->ex_pcpathlen = tmp_ex_pcpathlen;
847
0
    if (!(tmp_ex_flags & EXFLAG_NO_FINGERPRINT))
848
0
        memcpy(((X509 *)const_x)->fingerprint, tmp_fingerprint,
849
0
            sizeof(tmp_fingerprint));
850
0
    if (tmp_ex_flags & EXFLAG_KUSAGE)
851
0
        ((X509 *)const_x)->ex_kusage = tmp_ex_kusage;
852
0
    ((X509 *)const_x)->ex_xkusage = tmp_ex_xkusage;
853
0
    if (tmp_ex_flags & EXFLAG_NSCERT)
854
0
        ((X509 *)const_x)->ex_nscert = tmp_ex_nscert;
855
0
    ASN1_OCTET_STRING_free(((X509 *)const_x)->skid);
856
0
    ((X509 *)const_x)->skid = tmp_skid;
857
0
    tmp_skid = NULL;
858
0
    AUTHORITY_KEYID_free(((X509 *)const_x)->akid);
859
0
    ((X509 *)const_x)->akid = tmp_akid;
860
0
    tmp_akid = NULL;
861
0
    sk_GENERAL_NAME_pop_free(((X509 *)const_x)->altname, GENERAL_NAME_free);
862
0
    ((X509 *)const_x)->altname = tmp_altname;
863
0
    tmp_altname = NULL;
864
0
    NAME_CONSTRAINTS_free(((X509 *)const_x)->nc);
865
0
    ((X509 *)const_x)->nc = tmp_nc;
866
0
    tmp_nc = NULL;
867
0
    sk_DIST_POINT_pop_free(((X509 *)const_x)->crldp, DIST_POINT_free);
868
0
    ((X509 *)const_x)->crldp = tmp_crldp;
869
0
    tmp_crldp = NULL;
870
0
#ifndef OPENSSL_NO_RFC3779
871
0
    sk_IPAddressFamily_pop_free(((X509 *)const_x)->rfc3779_addr, IPAddressFamily_free);
872
0
    ((X509 *)const_x)->rfc3779_addr = tmp_rfc3779_addr;
873
0
    tmp_rfc3779_addr = NULL;
874
0
    ASIdentifiers_free(((X509 *)const_x)->rfc3779_asid);
875
0
    ((X509 *)const_x)->rfc3779_asid = tmp_rfc3779_asid;
876
0
    tmp_rfc3779_asid = NULL;
877
0
#endif
878
879
0
#ifdef tsan_st_rel
880
0
    tsan_st_rel((TSAN_QUALIFIER int *)&const_x->ex_cached, 1);
881
    /*
882
     * Above store triggers fast lock-free check in the beginning of the
883
     * function. But one has to ensure that the structure is "stable", i.e.
884
     * all stores are visible on all processors. Hence the release fence.
885
     */
886
0
#endif
887
0
    CRYPTO_THREAD_unlock(const_x->lock);
888
0
    if (tmp_ex_flags & EXFLAG_INVALID) {
889
0
        ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_CERTIFICATE);
890
0
        goto done;
891
0
    }
892
893
0
    ret = 1;
894
895
0
done:
896
0
    ASN1_OCTET_STRING_free(tmp_skid);
897
0
    AUTHORITY_KEYID_free(tmp_akid);
898
0
    sk_GENERAL_NAME_pop_free(tmp_altname, GENERAL_NAME_free);
899
0
    NAME_CONSTRAINTS_free(tmp_nc);
900
0
    sk_DIST_POINT_pop_free(tmp_crldp, DIST_POINT_free);
901
0
#ifndef OPENSSL_NO_RFC3779
902
0
    sk_IPAddressFamily_pop_free(tmp_rfc3779_addr, IPAddressFamily_free);
903
0
    ASIdentifiers_free(tmp_rfc3779_asid);
904
0
#endif
905
0
    return ret;
906
0
}
907
908
/*-
909
 * CA checks common to all purposes
910
 * return codes:
911
 * 0 not a CA
912
 * 1 is a CA
913
 * 2 Only possible in older versions of openSSL when basicConstraints are absent
914
 *   new versions will not return this value. May be a CA
915
 * 3 basicConstraints absent but self-signed V1.
916
 * 4 basicConstraints absent but keyUsage present and keyCertSign asserted.
917
 * 5 Netscape specific CA Flags present
918
 */
919
920
static int check_ca(const X509 *x)
921
0
{
922
    /* keyUsage if present should allow cert signing */
923
0
    if (ku_reject(x, KU_KEY_CERT_SIGN))
924
0
        return 0;
925
0
    if ((x->ex_flags & EXFLAG_BCONS) != 0) {
926
        /* If basicConstraints says not a CA then say so */
927
0
        return (x->ex_flags & EXFLAG_CA) != 0;
928
0
    } else {
929
        /* We support V1 roots for...  uh, I don't really know why. */
930
0
        if ((x->ex_flags & V1_ROOT) == V1_ROOT)
931
0
            return 3;
932
        /*
933
         * If key usage present it must have certSign so tolerate it
934
         */
935
0
        else if ((x->ex_flags & EXFLAG_KUSAGE) != 0)
936
0
            return 4;
937
        /* Older certificates could have Netscape-specific CA types */
938
0
        else if ((x->ex_flags & EXFLAG_NSCERT) != 0
939
0
            && (x->ex_nscert & NS_ANY_CA) != 0)
940
0
            return 5;
941
        /* Can this still be regarded a CA certificate?  I doubt it. */
942
0
        return 0;
943
0
    }
944
0
}
945
946
void X509_set_proxy_flag(X509 *x)
947
0
{
948
0
    if (CRYPTO_THREAD_write_lock(x->lock)) {
949
0
        x->ex_flags |= EXFLAG_PROXY;
950
0
        CRYPTO_THREAD_unlock(x->lock);
951
0
    }
952
0
}
953
954
void X509_set_proxy_pathlen(X509 *x, long l)
955
0
{
956
    /*
957
     * Out of range values cannot be reported from a void function, so
958
     * fail closed: the caller asked for a constraint, and 0 permits no
959
     * further delegation and can never be more permissive than the
960
     * requested value.
961
     */
962
0
    if (l < -1 || l > 255)
963
0
        l = 0;
964
0
    x->ex_pcpathlen = l;
965
0
}
966
967
int X509_check_ca(const X509 *x)
968
0
{
969
    /* Note 0 normally means "not a CA" - but in this case means error. */
970
0
    if (!ossl_x509v3_cache_extensions(x))
971
0
        return 0;
972
973
0
    return check_ca(x);
974
0
}
975
976
/* Check SSL CA: common checks for SSL client and server. */
977
static int check_ssl_ca(const X509 *x)
978
0
{
979
0
    int ca_ret = check_ca(x);
980
981
0
    if (ca_ret == 0)
982
0
        return 0;
983
    /* Check nsCertType if present */
984
0
    return ca_ret != 5 || (x->ex_nscert & NS_SSL_CA) != 0;
985
0
}
986
987
static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
988
    int non_leaf)
989
0
{
990
0
    if (xku_reject(x, XKU_SSL_CLIENT))
991
0
        return 0;
992
0
    if (non_leaf)
993
0
        return check_ssl_ca(x);
994
    /* We need to do digital signatures or key agreement */
995
0
    if (ku_reject(x, KU_DIGITAL_SIGNATURE | KU_KEY_AGREEMENT))
996
0
        return 0;
997
    /* nsCertType if present should allow SSL client use */
998
0
    if (ns_reject(x, NS_SSL_CLIENT))
999
0
        return 0;
1000
0
    return 1;
1001
0
}
1002
1003
/*
1004
 * Key usage needed for TLS/SSL server: digital signature, encipherment or
1005
 * key agreement. The ssl code can check this more thoroughly for individual
1006
 * key types.
1007
 */
1008
#define KU_TLS \
1009
    KU_DIGITAL_SIGNATURE | KU_KEY_ENCIPHERMENT | KU_KEY_AGREEMENT
1010
1011
static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
1012
    int non_leaf)
1013
0
{
1014
0
    if (xku_reject(x, XKU_SSL_SERVER | XKU_SGC))
1015
0
        return 0;
1016
0
    if (non_leaf)
1017
0
        return check_ssl_ca(x);
1018
1019
0
    if (ns_reject(x, NS_SSL_SERVER))
1020
0
        return 0;
1021
0
    if (ku_reject(x, KU_TLS))
1022
0
        return 0;
1023
1024
0
    return 1;
1025
0
}
1026
1027
static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x,
1028
    int non_leaf)
1029
0
{
1030
0
    int ret = check_purpose_ssl_server(xp, x, non_leaf);
1031
1032
0
    if (!ret || non_leaf)
1033
0
        return ret;
1034
    /* We need to encipher or Netscape complains */
1035
0
    return ku_reject(x, KU_KEY_ENCIPHERMENT) ? 0 : ret;
1036
0
}
1037
1038
/* common S/MIME client checks */
1039
static int purpose_smime(const X509 *x, int non_leaf)
1040
0
{
1041
0
    if (xku_reject(x, XKU_SMIME))
1042
0
        return 0;
1043
0
    if (non_leaf) {
1044
0
        int ca_ret = check_ca(x);
1045
1046
0
        if (ca_ret == 0)
1047
0
            return 0;
1048
        /* Check nsCertType if present */
1049
0
        if (ca_ret != 5 || (x->ex_nscert & NS_SMIME_CA) != 0)
1050
0
            return ca_ret;
1051
0
        else
1052
0
            return 0;
1053
0
    }
1054
0
    if ((x->ex_flags & EXFLAG_NSCERT) != 0) {
1055
0
        if ((x->ex_nscert & NS_SMIME) != 0)
1056
0
            return 1;
1057
        /* Workaround for some buggy certificates */
1058
0
        return (x->ex_nscert & NS_SSL_CLIENT) != 0 ? 2 : 0;
1059
0
    }
1060
0
    return 1;
1061
0
}
1062
1063
static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x,
1064
    int non_leaf)
1065
0
{
1066
0
    int ret = purpose_smime(x, non_leaf);
1067
1068
0
    if (!ret || non_leaf)
1069
0
        return ret;
1070
0
    return ku_reject(x, KU_DIGITAL_SIGNATURE | KU_NON_REPUDIATION) ? 0 : ret;
1071
0
}
1072
1073
static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x,
1074
    int non_leaf)
1075
0
{
1076
0
    int ret = purpose_smime(x, non_leaf);
1077
1078
0
    if (!ret || non_leaf)
1079
0
        return ret;
1080
0
    return ku_reject(x, KU_KEY_ENCIPHERMENT) ? 0 : ret;
1081
0
}
1082
1083
static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x,
1084
    int non_leaf)
1085
0
{
1086
0
    if (non_leaf) {
1087
0
        int ca_ret = check_ca(x);
1088
1089
0
        return ca_ret == 2 ? 0 : ca_ret;
1090
0
    }
1091
0
    return !ku_reject(x, KU_CRL_SIGN);
1092
0
}
1093
1094
/*
1095
 * OCSP helper: this is *not* a full OCSP check. It just checks that each CA
1096
 * is valid. Additional checks must be made on the chain.
1097
 */
1098
static int check_purpose_ocsp_helper(const X509_PURPOSE *xp, const X509 *x,
1099
    int non_leaf)
1100
0
{
1101
    /*
1102
     * Must be a valid CA.  Should we really support the "I don't know" value
1103
     * (2)?
1104
     */
1105
0
    if (non_leaf)
1106
0
        return check_ca(x);
1107
    /* Leaf certificate is checked in OCSP_basic_verify() */
1108
0
    return 1;
1109
0
}
1110
1111
static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x,
1112
    int non_leaf)
1113
0
{
1114
0
    int i_ext;
1115
1116
    /*
1117
     * If non_leaf is true we must check if this is a valid CA certificate.
1118
     * The extra requirements by the CA/Browser Forum are not checked.
1119
     */
1120
0
    if (non_leaf)
1121
0
        return check_ca(x);
1122
1123
    /*
1124
     * Key Usage is checked according to RFC 5280 and
1125
     * Extended Key Usage attributes is checked according to RFC 3161.
1126
     * The extra (and somewhat conflicting) CA/Browser Forum
1127
     * Baseline Requirements for the Issuance and Management of
1128
     * Publicly‐Trusted Code Signing Certificates, Version 3.0.0,
1129
     * Section 7.1.2.3: Code signing and Timestamp Certificate are not checked.
1130
     */
1131
    /*
1132
     * Check the optional key usage field:
1133
     * if Key Usage is present, it must be one of digitalSignature
1134
     * and/or nonRepudiation (other values are not consistent and shall
1135
     * be rejected).
1136
     */
1137
0
    if ((x->ex_flags & EXFLAG_KUSAGE) != 0
1138
0
        && ((x->ex_kusage & ~(KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE)) || !(x->ex_kusage & (KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE))))
1139
0
        return 0;
1140
1141
    /* Only timestamp key usage is permitted and it's required. */
1142
0
    if ((x->ex_flags & EXFLAG_XKUSAGE) == 0 || x->ex_xkusage != XKU_TIMESTAMP)
1143
0
        return 0;
1144
1145
    /* Extended Key Usage MUST be critical */
1146
0
    i_ext = X509_get_ext_by_NID(x, NID_ext_key_usage, -1);
1147
0
    if (i_ext >= 0
1148
0
        && !X509_EXTENSION_get_critical(X509_get_ext((X509 *)x, i_ext)))
1149
0
        return 0;
1150
0
    return 1;
1151
0
}
1152
1153
static int check_purpose_code_sign(const X509_PURPOSE *xp, const X509 *x,
1154
    int non_leaf)
1155
0
{
1156
0
    int i_ext;
1157
1158
    /*
1159
     * If non_leaf is true we must check if this is a valid CA certificate.
1160
     * The extra requirements by the CA/Browser Forum are not checked.
1161
     */
1162
0
    if (non_leaf)
1163
0
        return check_ca(x);
1164
1165
    /*
1166
     * Check the key usage and extended key usage fields:
1167
     *
1168
     * Reference: CA/Browser Forum,
1169
     * Baseline Requirements for the Issuance and Management of
1170
     * Publicly‐Trusted Code Signing Certificates, Version 3.0.0,
1171
     * Section 7.1.2.3: Code signing and Timestamp Certificate
1172
     *
1173
     * Checking covers Key Usage and Extended Key Usage attributes.
1174
     * The certificatePolicies, cRLDistributionPoints (CDP), and
1175
     * authorityInformationAccess (AIA) extensions are so far not checked.
1176
     */
1177
    /* Key Usage */
1178
0
    if ((x->ex_flags & EXFLAG_KUSAGE) == 0)
1179
0
        return 0;
1180
0
    if ((x->ex_kusage & KU_DIGITAL_SIGNATURE) == 0)
1181
0
        return 0;
1182
0
    if ((x->ex_kusage & (KU_KEY_CERT_SIGN | KU_CRL_SIGN)) != 0)
1183
0
        return 0;
1184
1185
    /* Key Usage MUST be critical */
1186
0
    i_ext = X509_get_ext_by_NID(x, NID_key_usage, -1);
1187
0
    if (i_ext < 0)
1188
0
        return 0;
1189
0
    if (i_ext >= 0) {
1190
0
        const X509_EXTENSION *ext = X509_get_ext((X509 *)x, i_ext);
1191
0
        if (!X509_EXTENSION_get_critical(ext))
1192
0
            return 0;
1193
0
    }
1194
1195
    /* Extended Key Usage */
1196
0
    if ((x->ex_flags & EXFLAG_XKUSAGE) == 0)
1197
0
        return 0;
1198
0
    if ((x->ex_xkusage & XKU_CODE_SIGN) == 0)
1199
0
        return 0;
1200
0
    if ((x->ex_xkusage & (XKU_ANYEKU | XKU_SSL_SERVER)) != 0)
1201
0
        return 0;
1202
1203
0
    return 1;
1204
0
}
1205
1206
static int no_check_purpose(const X509_PURPOSE *xp, const X509 *x,
1207
    int non_leaf)
1208
0
{
1209
0
    return 1;
1210
0
}
1211
1212
static int check_name_constraints(const NAME_CONSTRAINTS *nc)
1213
0
{
1214
0
    GENERAL_SUBTREE *sub;
1215
0
    int ret = 1;
1216
1217
0
    if (nc == NULL)
1218
0
        goto done;
1219
1220
0
    for (int i = 0; nc->permittedSubtrees != NULL
1221
0
        && i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees);
1222
0
        i++) {
1223
0
        sub = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i);
1224
0
        if (sub->base->type == GEN_OTHERNAME
1225
0
            && OBJ_obj2nid(sub->base->d.otherName->type_id)
1226
0
                == NID_id_on_SmtpUTF8Mailbox) {
1227
            /* RFC 9598 prohibits GEN_OTHERNAME email constraints */
1228
0
            ERR_raise(ERR_LIB_X509V3, X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE);
1229
0
            ret = 0;
1230
0
            goto done;
1231
0
        }
1232
0
    }
1233
0
    for (int i = 0; nc->excludedSubtrees != NULL
1234
0
        && i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees);
1235
0
        i++) {
1236
0
        sub = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i);
1237
0
        if (sub->base->type == GEN_OTHERNAME
1238
0
            && OBJ_obj2nid(sub->base->d.otherName->type_id)
1239
0
                == NID_id_on_SmtpUTF8Mailbox) {
1240
            /* RFC 9598 prohibits GEN_OTHERNAME email constraints */
1241
0
            ERR_raise(ERR_LIB_X509V3, X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE);
1242
0
            ret = 0;
1243
0
            goto done;
1244
0
        }
1245
0
    }
1246
1247
0
done:
1248
0
    return ret;
1249
0
}
1250
1251
/*-
1252
 * Various checks to see if one certificate potentially issued the second.
1253
 * This can be used to prune a set of possible issuer certificates which
1254
 * have been looked up using some simple method such as by subject name.
1255
 * These are:
1256
 * 1. issuer_name(subject) == subject_name(issuer)
1257
 * 2. If akid(subject) exists, it matches the respective issuer fields.
1258
 * 3. subject signature algorithm == issuer public key algorithm
1259
 * 4. If key_usage(issuer) exists, it allows for signing subject.
1260
 * Note that this does not include actually checking the signature.
1261
 * Returns 0 for OK, or positive for reason for mismatch
1262
 * where reason codes match those for X509_verify_cert().
1263
 */
1264
int X509_check_issued(const X509 *issuer, const X509 *subject)
1265
0
{
1266
0
    int ret;
1267
1268
0
    if ((ret = ossl_x509_likely_issued(issuer, subject)) != X509_V_OK)
1269
0
        return ret;
1270
0
    return ossl_x509_signing_allowed(issuer, subject);
1271
0
}
1272
1273
/*
1274
 * Do the checks 1., 2., and 3. as described above for X509_check_issued().
1275
 * These are very similar to a section of ossl_x509v3_cache_extensions().
1276
 * If |issuer| equals |subject| (such that self-signature should be checked),
1277
 * use the EXFLAG_SS result of ossl_x509v3_cache_extensions().
1278
 */
1279
int ossl_x509_likely_issued(const X509 *issuer, const X509 *subject)
1280
0
{
1281
0
    int ret;
1282
1283
0
    if (X509_NAME_cmp(X509_get_subject_name(issuer),
1284
0
            X509_get_issuer_name(subject))
1285
0
        != 0)
1286
0
        return X509_V_ERR_SUBJECT_ISSUER_MISMATCH;
1287
1288
    /* set issuer->skid, subject->akid, and subject->ex_flags */
1289
0
    if (!ossl_x509v3_cache_extensions(issuer)
1290
0
        || !ossl_x509v3_cache_extensions(subject))
1291
0
        return X509_V_ERR_UNSPECIFIED;
1292
1293
0
    if (issuer == subject
1294
0
        || (X509_NAME_cmp(X509_get_issuer_name(issuer), X509_get_issuer_name(subject)) == 0
1295
0
            && ASN1_INTEGER_cmp(X509_get0_serialNumber(issuer), X509_get0_serialNumber(subject)) == 0))
1296
        /*
1297
         * At this point, we can assume that issuer and subject
1298
         * are semantically the same cert because they are identical
1299
         * or at least have the same issuer and serial number,
1300
         * which (for any sane cert issuer) implies equality of the two certs.
1301
         * In this case, for consistency with chain building and validation,
1302
         * we make our issuance judgment depend on the presence of EXFLAG_SS.
1303
         * This is used for corrected chain building in the corner case of
1304
         * a self-issued but not actually self-signed trust anchor cert
1305
         * without subject and issuer key identifiers (i.e., no SKID and AKID).
1306
         */
1307
0
        return (issuer->ex_flags & EXFLAG_SS) != 0
1308
0
            ? X509_V_OK
1309
0
            : X509_V_ERR_CERT_SIGNATURE_FAILURE;
1310
1311
0
    ret = X509_check_akid(issuer, subject->akid);
1312
0
    if (ret != X509_V_OK)
1313
0
        return ret;
1314
1315
    /* Check if the subject signature alg matches the issuer's PUBKEY alg */
1316
0
    return check_sig_alg_match(X509_get0_pubkey(issuer), subject);
1317
0
}
1318
1319
/*-
1320
 * Check if certificate I<issuer> is allowed to issue certificate I<subject>
1321
 * according to the B<keyUsage> field of I<issuer> if present
1322
 * depending on any proxyCertInfo extension of I<subject>.
1323
 * Returns 0 for OK, or positive for reason for rejection
1324
 * where reason codes match those for X509_verify_cert().
1325
 */
1326
int ossl_x509_signing_allowed(const X509 *issuer, const X509 *subject)
1327
0
{
1328
0
    if ((subject->ex_flags & EXFLAG_PROXY) != 0) {
1329
0
        if (ku_reject(issuer, KU_DIGITAL_SIGNATURE))
1330
0
            return X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
1331
0
    } else if (ku_reject(issuer, KU_KEY_CERT_SIGN)) {
1332
0
        return X509_V_ERR_KEYUSAGE_NO_CERTSIGN;
1333
0
    }
1334
0
    return X509_V_OK;
1335
0
}
1336
1337
/*
1338
 * check if all sub-fields of the authority key identifier information akid,
1339
 * as far as present, match the respective subjectKeyIdentifier extension (if
1340
 * present in issuer), serialNumber field, and issuer fields of issuer.
1341
 * returns X509_V_OK also if akid is NULL because this means no restriction.
1342
 */
1343
int X509_check_akid(const X509 *issuer, const AUTHORITY_KEYID *akid)
1344
0
{
1345
0
    if (akid == NULL)
1346
0
        return X509_V_OK;
1347
1348
    /* Check key ids (if present) */
1349
0
    if (akid->keyid && issuer->skid && ASN1_OCTET_STRING_cmp(akid->keyid, issuer->skid))
1350
0
        return X509_V_ERR_AKID_SKID_MISMATCH;
1351
    /* Check serial number */
1352
0
    if (akid->serial && ASN1_INTEGER_cmp(X509_get0_serialNumber(issuer), akid->serial))
1353
0
        return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
1354
    /* Check issuer name */
1355
0
    if (akid->issuer) {
1356
        /*
1357
         * Ugh, for some peculiar reason AKID includes SEQUENCE OF
1358
         * GeneralName. So look for a DirName. There may be more than one but
1359
         * we only take any notice of the first.
1360
         */
1361
0
        GENERAL_NAMES *gens = akid->issuer;
1362
0
        GENERAL_NAME *gen;
1363
0
        X509_NAME *nm = NULL;
1364
0
        int i;
1365
1366
0
        for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1367
0
            gen = sk_GENERAL_NAME_value(gens, i);
1368
0
            if (gen->type == GEN_DIRNAME) {
1369
0
                nm = gen->d.dirn;
1370
0
                break;
1371
0
            }
1372
0
        }
1373
0
        if (nm != NULL && X509_NAME_cmp(nm, X509_get_issuer_name(issuer)) != 0)
1374
0
            return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
1375
0
    }
1376
0
    return X509_V_OK;
1377
0
}
1378
1379
uint32_t X509_get_extension_flags(const X509 *x)
1380
0
{
1381
    /* Call for side-effect of computing hash and caching extensions */
1382
0
    X509_check_purpose(x, -1, 0);
1383
0
    return x->ex_flags;
1384
0
}
1385
1386
uint32_t X509_get_key_usage(const X509 *x)
1387
0
{
1388
    /* Call for side-effect of computing hash and caching extensions */
1389
0
    if (X509_check_purpose(x, -1, 0) != 1)
1390
0
        return 0;
1391
0
    return (x->ex_flags & EXFLAG_KUSAGE) != 0 ? x->ex_kusage : UINT32_MAX;
1392
0
}
1393
1394
uint32_t X509_get_extended_key_usage(const X509 *x)
1395
0
{
1396
    /* Call for side-effect of computing hash and caching extensions */
1397
0
    if (X509_check_purpose(x, -1, 0) != 1)
1398
0
        return 0;
1399
0
    return (x->ex_flags & EXFLAG_XKUSAGE) != 0 ? x->ex_xkusage : UINT32_MAX;
1400
0
}
1401
1402
const ASN1_OCTET_STRING *X509_get0_subject_key_id(const X509 *x)
1403
0
{
1404
    /* Call for side-effect of computing hash and caching extensions */
1405
0
    if (X509_check_purpose(x, -1, 0) != 1)
1406
0
        return NULL;
1407
0
    return x->skid;
1408
0
}
1409
1410
const ASN1_OCTET_STRING *X509_get0_authority_key_id(const X509 *x)
1411
0
{
1412
    /* Call for side-effect of computing hash and caching extensions */
1413
0
    if (X509_check_purpose(x, -1, 0) != 1)
1414
0
        return NULL;
1415
0
    return (x->akid != NULL ? x->akid->keyid : NULL);
1416
0
}
1417
1418
const GENERAL_NAMES *X509_get0_authority_issuer(const X509 *x)
1419
0
{
1420
    /* Call for side-effect of computing hash and caching extensions */
1421
0
    if (X509_check_purpose(x, -1, 0) != 1)
1422
0
        return NULL;
1423
0
    return (x->akid != NULL ? x->akid->issuer : NULL);
1424
0
}
1425
1426
const ASN1_INTEGER *X509_get0_authority_serial(const X509 *x)
1427
0
{
1428
    /* Call for side-effect of computing hash and caching extensions */
1429
0
    if (X509_check_purpose(x, -1, 0) != 1)
1430
0
        return NULL;
1431
0
    return (x->akid != NULL ? x->akid->serial : NULL);
1432
0
}
1433
1434
long X509_get_pathlen(const X509 *x)
1435
0
{
1436
    /* Called for side effect of caching extensions */
1437
0
    if (X509_check_purpose(x, -1, 0) != 1
1438
0
        || (x->ex_flags & EXFLAG_BCONS) == 0)
1439
0
        return -1;
1440
0
    return x->ex_pathlen;
1441
0
}
1442
1443
long X509_get_proxy_pathlen(const X509 *x)
1444
0
{
1445
    /* Called for side effect of caching extensions */
1446
0
    if (X509_check_purpose(x, -1, 0) != 1
1447
0
        || (x->ex_flags & EXFLAG_PROXY) == 0)
1448
0
        return -1;
1449
0
    return x->ex_pcpathlen;
1450
0
}