Coverage Report

Created: 2026-11-16 07:12

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 "crypto/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 only has to be unpredictable, not secret, so it is
508
             * drawn with ossl_rand_hash_salt(), which still succeeds in a
509
             * library context without a usable RAND (e.g. only the null
510
             * provider loaded) instead of making every such certificate
511
             * with an unknown extension invalid.
512
             *
513
             * The key and the entry wrappers remain valid for the duration of
514
             * the scan; the table never outlives this function. Only this
515
             * and the later extensions can be inserted, so the wrappers are
516
             * sized for count - i entries.
517
             *
518
             * If the table cannot be set up or an insert fails, fail closed
519
             * with EXFLAG_INVALID, as ossl_x509v3_cache_extensions() does for
520
             * any other extension it cannot process. Leaving the loop
521
             * silently would skip not only the duplicate check but also the
522
             * unsupported-critical check for this and every later extension.
523
             */
524
0
            if (h == NULL) {
525
0
                OSSL_LIB_CTX *libctx = NULL;
526
527
0
                ossl_x509_get0_libctx(x509, &libctx, NULL);
528
0
                if (!ossl_rand_hash_salt(libctx, (unsigned char *)k, sizeof(k))
529
0
                    || (arr = OPENSSL_malloc_array(count - i, sizeof(*arr))) == NULL
530
0
                    || (h = OPENSSL_LH_new(oid_hash, oid_cmp)) == NULL) {
531
0
                    *flags |= EXFLAG_INVALID;
532
0
                    break;
533
0
                }
534
0
            }
535
0
            arr[num_entries].obj = a;
536
0
            arr[num_entries].key = k;
537
0
            if (OPENSSL_LH_insert(h, &arr[num_entries]) != NULL) {
538
0
                *flags |= EXFLAG_DUPLICATE;
539
0
                break;
540
0
            }
541
0
            if (OPENSSL_LH_error(h) != 0) {
542
0
                *flags |= EXFLAG_INVALID;
543
0
                break;
544
0
            }
545
0
            num_entries++;
546
0
        }
547
0
        if (nid == NID_freshest_crl)
548
0
            *flags |= EXFLAG_FRESHEST;
549
0
        if (!X509_EXTENSION_get_critical(ex))
550
0
            continue;
551
0
        if (!X509_supported_extension(ex)) {
552
0
            *flags |= EXFLAG_CRITICAL;
553
0
            break;
554
0
        }
555
0
    }
556
0
    OPENSSL_LH_free(h);
557
0
    OPENSSL_free(arr);
558
0
}
559
560
0
#define V1_ROOT (EXFLAG_V1 | EXFLAG_SS)
561
#define ku_reject(x, usage) \
562
0
    (((x)->ex_flags & EXFLAG_KUSAGE) != 0 && ((x)->ex_kusage & (usage)) == 0)
563
#define xku_reject(x, usage) \
564
0
    (((x)->ex_flags & EXFLAG_XKUSAGE) != 0 && ((x)->ex_xkusage & (usage)) == 0)
565
#define ns_reject(x, usage) \
566
0
    (((x)->ex_flags & EXFLAG_NSCERT) != 0 && ((x)->ex_nscert & (usage)) == 0)
567
568
/*
569
 * Cache info on various X.509v3 extensions and further derived information,
570
 * e.g., if cert 'x' is self-issued, in x->ex_flags and other internal fields.
571
 * x->fingerprint is filled in, or else EXFLAG_NO_FINGERPRINT is set in
572
 * x->ex_flags.
573
 * Set EXFLAG_INVALID and return 0 in case the certificate is invalid.
574
 *
575
 * This is usually called by side-effect on objects, and forces us to keep
576
 * mutable X509 objects around. We should really make this go away.
577
 * In the interest of being able to do so, this function explicitly takes
578
 * a const argument and casts away const.
579
 */
580
int ossl_x509v3_cache_extensions(const X509 *const_x)
581
0
{
582
0
    BASIC_CONSTRAINTS *bs;
583
0
    PROXY_CERT_INFO_EXTENSION *pci;
584
0
    ASN1_BIT_STRING *usage;
585
0
    ASN1_BIT_STRING *ns;
586
0
    EXTENDED_KEY_USAGE *extusage;
587
0
    int i;
588
0
    int res;
589
0
    uint32_t tmp_ex_flags;
590
0
    unsigned char tmp_fingerprint[OSSL_X509_FINGERPRINT_SIZE];
591
0
    long tmp_ex_pathlen;
592
0
    long tmp_ex_pcpathlen;
593
0
    uint32_t tmp_ex_kusage;
594
0
    uint32_t tmp_ex_xkusage;
595
0
    uint32_t tmp_ex_nscert;
596
0
    ASN1_OCTET_STRING *tmp_skid = NULL;
597
0
    AUTHORITY_KEYID *tmp_akid = NULL;
598
0
    STACK_OF(GENERAL_NAME) *tmp_altname = NULL;
599
0
    NAME_CONSTRAINTS *tmp_nc = NULL;
600
0
    STACK_OF(DIST_POINT) *tmp_crldp = NULL;
601
0
#ifndef OPENSSL_NO_RFC3779
602
0
    STACK_OF(IPAddressFamily) *tmp_rfc3779_addr = NULL;
603
0
    struct ASIdentifiers_st *tmp_rfc3779_asid = NULL;
604
0
#endif
605
0
    int ret = 0;
606
607
0
#ifdef tsan_ld_acq
608
    /* Fast lock-free check, see end of the function for details. */
609
0
    if (tsan_ld_acq((TSAN_QUALIFIER int *)&const_x->ex_cached)) {
610
0
        ret = (const_x->ex_flags & EXFLAG_INVALID) == 0;
611
0
        goto done;
612
0
    }
613
0
#endif
614
615
0
    if (!CRYPTO_THREAD_read_lock(const_x->lock))
616
0
        goto done;
617
0
    tmp_ex_flags = const_x->ex_flags;
618
0
    tmp_ex_pcpathlen = const_x->ex_pcpathlen;
619
0
    tmp_ex_kusage = const_x->ex_kusage;
620
0
    tmp_ex_nscert = const_x->ex_nscert;
621
622
0
    if ((tmp_ex_flags & EXFLAG_SET) != 0) { /* Cert has already been processed */
623
0
        CRYPTO_THREAD_unlock(const_x->lock);
624
0
        ret = (tmp_ex_flags & EXFLAG_INVALID) == 0;
625
0
        goto done;
626
0
    }
627
628
0
    ERR_set_mark();
629
630
0
    if (!ossl_x509_internal_fingerprint(ASN1_ITEM_rptr(X509), const_x,
631
0
            tmp_fingerprint))
632
0
        tmp_ex_flags |= EXFLAG_NO_FINGERPRINT;
633
634
    /* V1 should mean no extensions ... */
635
0
    if (X509_get_version(const_x) == X509_VERSION_1)
636
0
        tmp_ex_flags |= EXFLAG_V1;
637
638
    /* Handle basic constraints */
639
0
    tmp_ex_pathlen = -1;
640
0
    if ((bs = X509_get_ext_d2i(const_x, NID_basic_constraints, &i, NULL)) != NULL) {
641
0
        if (bs->ca)
642
0
            tmp_ex_flags |= EXFLAG_CA;
643
0
        if (bs->pathlen != NULL) {
644
            /*
645
             * The error case !bs->ca is checked by check_chain()
646
             * in case ctx->param->flags & X509_V_FLAG_X509_STRICT
647
             */
648
0
            if (bs->pathlen->type == V_ASN1_NEG_INTEGER) {
649
0
                ERR_raise(ERR_LIB_X509V3, X509V3_R_NEGATIVE_PATHLEN);
650
0
                tmp_ex_flags |= EXFLAG_INVALID;
651
0
            } else {
652
0
                tmp_ex_pathlen = ASN1_INTEGER_get(bs->pathlen);
653
0
                if (tmp_ex_pathlen < 0 || tmp_ex_pathlen > 255) {
654
0
                    ERR_raise(ERR_LIB_X509V3, X509V3_R_PATHLEN_TOO_LARGE);
655
0
                    tmp_ex_flags |= EXFLAG_INVALID;
656
0
                    tmp_ex_pathlen = -1;
657
0
                }
658
0
            }
659
0
        }
660
0
        BASIC_CONSTRAINTS_free(bs);
661
0
        tmp_ex_flags |= EXFLAG_BCONS;
662
0
    } else if (i != -1) {
663
0
        tmp_ex_flags |= EXFLAG_INVALID;
664
0
    }
665
666
    /* Handle proxy certificates */
667
0
    if ((pci = X509_get_ext_d2i(const_x, NID_proxyCertInfo, &i, NULL)) != NULL) {
668
0
        if ((tmp_ex_flags & EXFLAG_CA) != 0
669
0
            || X509_get_ext_by_NID(const_x, NID_subject_alt_name, -1) >= 0
670
0
            || X509_get_ext_by_NID(const_x, NID_issuer_alt_name, -1) >= 0) {
671
0
            tmp_ex_flags |= EXFLAG_INVALID;
672
0
        }
673
0
        if (pci->pcPathLengthConstraint != NULL) {
674
0
            if (pci->pcPathLengthConstraint->type == V_ASN1_NEG_INTEGER) {
675
0
                ERR_raise(ERR_LIB_X509V3, X509V3_R_NEGATIVE_PATHLEN);
676
0
                tmp_ex_flags |= EXFLAG_INVALID;
677
0
                tmp_ex_pcpathlen = -1;
678
0
            } else {
679
0
                tmp_ex_pcpathlen = ASN1_INTEGER_get(pci->pcPathLengthConstraint);
680
0
                if (tmp_ex_pcpathlen < 0 || tmp_ex_pcpathlen > 255) {
681
0
                    ERR_raise(ERR_LIB_X509V3, X509V3_R_PATHLEN_TOO_LARGE);
682
0
                    tmp_ex_flags |= EXFLAG_INVALID;
683
0
                    tmp_ex_pcpathlen = -1;
684
0
                }
685
0
            }
686
0
        } else {
687
0
            tmp_ex_pcpathlen = -1;
688
0
        }
689
0
        PROXY_CERT_INFO_EXTENSION_free(pci);
690
0
        tmp_ex_flags |= EXFLAG_PROXY;
691
0
    } else if (i != -1) {
692
0
        tmp_ex_flags |= EXFLAG_INVALID;
693
0
    }
694
695
    /* Handle (basic) key usage */
696
0
    if ((usage = X509_get_ext_d2i(const_x, NID_key_usage, &i, NULL)) != NULL) {
697
0
        tmp_ex_kusage = 0;
698
0
        if (usage->length > 0) {
699
0
            tmp_ex_kusage = usage->data[0];
700
0
            if (usage->length > 1)
701
0
                tmp_ex_kusage |= usage->data[1] << 8;
702
0
        }
703
0
        tmp_ex_flags |= EXFLAG_KUSAGE;
704
0
        ASN1_BIT_STRING_free(usage);
705
        /* Check for empty key usage according to RFC 5280 section 4.2.1.3 */
706
0
        if (tmp_ex_kusage == 0) {
707
0
            ERR_raise(ERR_LIB_X509V3, X509V3_R_EMPTY_KEY_USAGE);
708
0
            tmp_ex_flags |= EXFLAG_INVALID;
709
0
        }
710
0
    } else if (i != -1) {
711
0
        tmp_ex_flags |= EXFLAG_INVALID;
712
0
    }
713
714
    /* Handle extended key usage */
715
0
    tmp_ex_xkusage = 0;
716
0
    if ((extusage = X509_get_ext_d2i(const_x, NID_ext_key_usage, &i, NULL)) != NULL) {
717
0
        tmp_ex_flags |= EXFLAG_XKUSAGE;
718
0
        for (i = 0; i < sk_ASN1_OBJECT_num(extusage); i++) {
719
0
            switch (OBJ_obj2nid(sk_ASN1_OBJECT_value(extusage, i))) {
720
0
            case NID_server_auth:
721
0
                tmp_ex_xkusage |= XKU_SSL_SERVER;
722
0
                break;
723
0
            case NID_client_auth:
724
0
                tmp_ex_xkusage |= XKU_SSL_CLIENT;
725
0
                break;
726
0
            case NID_email_protect:
727
0
                tmp_ex_xkusage |= XKU_SMIME;
728
0
                break;
729
0
            case NID_code_sign:
730
0
                tmp_ex_xkusage |= XKU_CODE_SIGN;
731
0
                break;
732
0
            case NID_ms_sgc:
733
0
            case NID_ns_sgc:
734
0
                tmp_ex_xkusage |= XKU_SGC;
735
0
                break;
736
0
            case NID_OCSP_sign:
737
0
                tmp_ex_xkusage |= XKU_OCSP_SIGN;
738
0
                break;
739
0
            case NID_time_stamp:
740
0
                tmp_ex_xkusage |= XKU_TIMESTAMP;
741
0
                break;
742
0
            case NID_dvcs:
743
0
                tmp_ex_xkusage |= XKU_DVCS;
744
0
                break;
745
0
            case NID_anyExtendedKeyUsage:
746
0
                tmp_ex_xkusage |= XKU_ANYEKU;
747
0
                break;
748
0
            default:
749
                /* Ignore unknown extended key usage */
750
0
                break;
751
0
            }
752
0
        }
753
0
        sk_ASN1_OBJECT_pop_free(extusage, ASN1_OBJECT_free);
754
0
    } else if (i != -1) {
755
0
        tmp_ex_flags |= EXFLAG_INVALID;
756
0
    }
757
758
    /* Handle legacy Netscape extension */
759
0
    if ((ns = X509_get_ext_d2i(const_x, NID_netscape_cert_type, &i, NULL)) != NULL) {
760
0
        if (ns->length > 0)
761
0
            tmp_ex_nscert = ns->data[0];
762
0
        else
763
0
            tmp_ex_nscert = 0;
764
0
        tmp_ex_flags |= EXFLAG_NSCERT;
765
0
        ASN1_BIT_STRING_free(ns);
766
0
    } else if (i != -1) {
767
0
        tmp_ex_flags |= EXFLAG_INVALID;
768
0
    }
769
770
    /* Handle subject key identifier and issuer/authority key identifier */
771
0
    tmp_skid = X509_get_ext_d2i(const_x, NID_subject_key_identifier, &i, NULL);
772
0
    if (tmp_skid == NULL && i != -1)
773
0
        tmp_ex_flags |= EXFLAG_INVALID;
774
775
0
    tmp_akid = X509_get_ext_d2i(const_x, NID_authority_key_identifier, &i, NULL);
776
0
    if (tmp_akid == NULL && i != -1)
777
0
        tmp_ex_flags |= EXFLAG_INVALID;
778
779
    /* Setting EXFLAG_SS is equivalent to ossl_x509_likely_issued(const_x, const_x) == X509_V_OK */
780
0
    if (X509_NAME_cmp(X509_get_subject_name(const_x), X509_get_issuer_name(const_x)) == 0) {
781
0
        tmp_ex_flags |= EXFLAG_SI; /* Certificate is self-issued: subject == issuer */
782
        /*
783
         * When the SKID is missing, which is rare for self-issued certs,
784
         * we could afford doing the (accurate) actual self-signature check, but
785
         * decided against it for efficiency reasons and according to RFC 5280,
786
         * CA certs MUST have an SKID and non-root certs MUST have an AKID.
787
         *
788
         * The cached const_x->skid is not populated until the write-lock
789
         * publication below, so the keyid comparison is done directly
790
         * against tmp_skid.  X509_check_akid() is retained for its serial
791
         * number and issuer name checks.
792
         */
793
0
        if ((tmp_akid == NULL || tmp_akid->keyid == NULL || tmp_skid == NULL
794
0
                || ASN1_OCTET_STRING_cmp(tmp_akid->keyid, tmp_skid) == 0)
795
0
            && X509_check_akid(const_x, tmp_akid) == X509_V_OK
796
0
            && check_sig_alg_match(X509_get0_pubkey(const_x), const_x) == X509_V_OK) {
797
            /*
798
             * Assume self-signed if the signature alg matches the pkey alg and
799
             * AKID is missing or matches respective fields in the same cert
800
             * Not checking if any given key usage extension allows signing.
801
             */
802
0
            tmp_ex_flags |= EXFLAG_SS;
803
0
        }
804
0
    }
805
806
    /* Handle subject alternative names and various other extensions */
807
0
    tmp_altname = X509_get_ext_d2i(const_x, NID_subject_alt_name, &i, NULL);
808
0
    if (tmp_altname == NULL && i != -1)
809
0
        tmp_ex_flags |= EXFLAG_INVALID;
810
0
    tmp_nc = X509_get_ext_d2i(const_x, NID_name_constraints, &i, NULL);
811
0
    if (tmp_nc == NULL && i != -1)
812
0
        tmp_ex_flags |= EXFLAG_INVALID;
813
0
    if (!check_name_constraints(tmp_nc))
814
0
        tmp_ex_flags |= EXFLAG_INVALID;
815
816
    /* Handle CRL distribution point entries */
817
0
    res = setup_crldp(const_x, &tmp_crldp);
818
0
    if (res == 0)
819
0
        tmp_ex_flags |= EXFLAG_INVALID;
820
821
0
#ifndef OPENSSL_NO_RFC3779
822
0
    tmp_rfc3779_addr = X509_get_ext_d2i(const_x, NID_sbgp_ipAddrBlock, &i, NULL);
823
0
    if (tmp_rfc3779_addr == NULL && i != -1)
824
0
        tmp_ex_flags |= EXFLAG_INVALID;
825
826
0
    tmp_rfc3779_asid = X509_get_ext_d2i(const_x, NID_sbgp_autonomousSysNum, &i, NULL);
827
0
    if (tmp_rfc3779_asid == NULL && i != -1)
828
0
        tmp_ex_flags |= EXFLAG_INVALID;
829
0
#endif
830
831
0
    scan_ext_flags(const_x, &tmp_ex_flags);
832
833
0
    tmp_ex_flags |= EXFLAG_SET; /* Indicate that cert has been processed */
834
0
    ERR_pop_to_mark();
835
836
0
    CRYPTO_THREAD_unlock(const_x->lock);
837
    /*
838
     * Now that we've done all the compute intensive work under read lock
839
     * do all the updating under a write lock
840
     */
841
0
    if (!CRYPTO_THREAD_write_lock(const_x->lock))
842
0
        goto done;
843
844
    /* See if another thread updated this certificate before we got the write lock. */
845
0
    if ((const_x->ex_flags & EXFLAG_SET) != 0) { /* Cert has already been processed */
846
0
        CRYPTO_THREAD_unlock(const_x->lock);
847
0
        ret = (const_x->ex_flags & EXFLAG_INVALID) == 0;
848
0
        goto done;
849
0
    }
850
851
    /* Otherwise, we have the lock, set the cached fields in the cert. */
852
0
    ((X509 *)const_x)->ex_flags = tmp_ex_flags;
853
0
    ((X509 *)const_x)->ex_pathlen = tmp_ex_pathlen;
854
0
    ((X509 *)const_x)->ex_pcpathlen = tmp_ex_pcpathlen;
855
0
    if (!(tmp_ex_flags & EXFLAG_NO_FINGERPRINT))
856
0
        memcpy(((X509 *)const_x)->fingerprint, tmp_fingerprint,
857
0
            sizeof(tmp_fingerprint));
858
0
    if (tmp_ex_flags & EXFLAG_KUSAGE)
859
0
        ((X509 *)const_x)->ex_kusage = tmp_ex_kusage;
860
0
    ((X509 *)const_x)->ex_xkusage = tmp_ex_xkusage;
861
0
    if (tmp_ex_flags & EXFLAG_NSCERT)
862
0
        ((X509 *)const_x)->ex_nscert = tmp_ex_nscert;
863
0
    ASN1_OCTET_STRING_free(((X509 *)const_x)->skid);
864
0
    ((X509 *)const_x)->skid = tmp_skid;
865
0
    tmp_skid = NULL;
866
0
    AUTHORITY_KEYID_free(((X509 *)const_x)->akid);
867
0
    ((X509 *)const_x)->akid = tmp_akid;
868
0
    tmp_akid = NULL;
869
0
    sk_GENERAL_NAME_pop_free(((X509 *)const_x)->altname, GENERAL_NAME_free);
870
0
    ((X509 *)const_x)->altname = tmp_altname;
871
0
    tmp_altname = NULL;
872
0
    NAME_CONSTRAINTS_free(((X509 *)const_x)->nc);
873
0
    ((X509 *)const_x)->nc = tmp_nc;
874
0
    tmp_nc = NULL;
875
0
    sk_DIST_POINT_pop_free(((X509 *)const_x)->crldp, DIST_POINT_free);
876
0
    ((X509 *)const_x)->crldp = tmp_crldp;
877
0
    tmp_crldp = NULL;
878
0
#ifndef OPENSSL_NO_RFC3779
879
0
    sk_IPAddressFamily_pop_free(((X509 *)const_x)->rfc3779_addr, IPAddressFamily_free);
880
0
    ((X509 *)const_x)->rfc3779_addr = tmp_rfc3779_addr;
881
0
    tmp_rfc3779_addr = NULL;
882
0
    ASIdentifiers_free(((X509 *)const_x)->rfc3779_asid);
883
0
    ((X509 *)const_x)->rfc3779_asid = tmp_rfc3779_asid;
884
0
    tmp_rfc3779_asid = NULL;
885
0
#endif
886
887
0
#ifdef tsan_st_rel
888
0
    tsan_st_rel((TSAN_QUALIFIER int *)&const_x->ex_cached, 1);
889
    /*
890
     * Above store triggers fast lock-free check in the beginning of the
891
     * function. But one has to ensure that the structure is "stable", i.e.
892
     * all stores are visible on all processors. Hence the release fence.
893
     */
894
0
#endif
895
0
    CRYPTO_THREAD_unlock(const_x->lock);
896
0
    if (tmp_ex_flags & EXFLAG_INVALID) {
897
0
        ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_CERTIFICATE);
898
0
        goto done;
899
0
    }
900
901
0
    ret = 1;
902
903
0
done:
904
0
    ASN1_OCTET_STRING_free(tmp_skid);
905
0
    AUTHORITY_KEYID_free(tmp_akid);
906
0
    sk_GENERAL_NAME_pop_free(tmp_altname, GENERAL_NAME_free);
907
0
    NAME_CONSTRAINTS_free(tmp_nc);
908
0
    sk_DIST_POINT_pop_free(tmp_crldp, DIST_POINT_free);
909
0
#ifndef OPENSSL_NO_RFC3779
910
0
    sk_IPAddressFamily_pop_free(tmp_rfc3779_addr, IPAddressFamily_free);
911
0
    ASIdentifiers_free(tmp_rfc3779_asid);
912
0
#endif
913
0
    return ret;
914
0
}
915
916
/*-
917
 * CA checks common to all purposes
918
 * return codes:
919
 * 0 not a CA
920
 * 1 is a CA
921
 * 2 Only possible in older versions of openSSL when basicConstraints are absent
922
 *   new versions will not return this value. May be a CA
923
 * 3 basicConstraints absent but self-signed V1.
924
 * 4 basicConstraints absent but keyUsage present and keyCertSign asserted.
925
 * 5 Netscape specific CA Flags present
926
 */
927
928
static int check_ca(const X509 *x)
929
0
{
930
    /* keyUsage if present should allow cert signing */
931
0
    if (ku_reject(x, KU_KEY_CERT_SIGN))
932
0
        return 0;
933
0
    if ((x->ex_flags & EXFLAG_BCONS) != 0) {
934
        /* If basicConstraints says not a CA then say so */
935
0
        return (x->ex_flags & EXFLAG_CA) != 0;
936
0
    } else {
937
        /* We support V1 roots for...  uh, I don't really know why. */
938
0
        if ((x->ex_flags & V1_ROOT) == V1_ROOT)
939
0
            return 3;
940
        /*
941
         * If key usage present it must have certSign so tolerate it
942
         */
943
0
        else if ((x->ex_flags & EXFLAG_KUSAGE) != 0)
944
0
            return 4;
945
        /* Older certificates could have Netscape-specific CA types */
946
0
        else if ((x->ex_flags & EXFLAG_NSCERT) != 0
947
0
            && (x->ex_nscert & NS_ANY_CA) != 0)
948
0
            return 5;
949
        /* Can this still be regarded a CA certificate?  I doubt it. */
950
0
        return 0;
951
0
    }
952
0
}
953
954
void X509_set_proxy_flag(X509 *x)
955
0
{
956
0
    if (CRYPTO_THREAD_write_lock(x->lock)) {
957
0
        x->ex_flags |= EXFLAG_PROXY;
958
0
        CRYPTO_THREAD_unlock(x->lock);
959
0
    }
960
0
}
961
962
void X509_set_proxy_pathlen(X509 *x, long l)
963
0
{
964
    /*
965
     * Out of range values cannot be reported from a void function, so
966
     * fail closed: the caller asked for a constraint, and 0 permits no
967
     * further delegation and can never be more permissive than the
968
     * requested value.
969
     */
970
0
    if (l < -1 || l > 255)
971
0
        l = 0;
972
0
    x->ex_pcpathlen = l;
973
0
}
974
975
int X509_check_ca(const X509 *x)
976
0
{
977
    /* Note 0 normally means "not a CA" - but in this case means error. */
978
0
    if (!ossl_x509v3_cache_extensions(x))
979
0
        return 0;
980
981
0
    return check_ca(x);
982
0
}
983
984
/* Check SSL CA: common checks for SSL client and server. */
985
static int check_ssl_ca(const X509 *x)
986
0
{
987
0
    int ca_ret = check_ca(x);
988
989
0
    if (ca_ret == 0)
990
0
        return 0;
991
    /* Check nsCertType if present */
992
0
    return ca_ret != 5 || (x->ex_nscert & NS_SSL_CA) != 0;
993
0
}
994
995
static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
996
    int non_leaf)
997
0
{
998
0
    if (xku_reject(x, XKU_SSL_CLIENT))
999
0
        return 0;
1000
0
    if (non_leaf)
1001
0
        return check_ssl_ca(x);
1002
    /* We need to do digital signatures or key agreement */
1003
0
    if (ku_reject(x, KU_DIGITAL_SIGNATURE | KU_KEY_AGREEMENT))
1004
0
        return 0;
1005
    /* nsCertType if present should allow SSL client use */
1006
0
    if (ns_reject(x, NS_SSL_CLIENT))
1007
0
        return 0;
1008
0
    return 1;
1009
0
}
1010
1011
/*
1012
 * Key usage needed for TLS/SSL server: digital signature, encipherment or
1013
 * key agreement. The ssl code can check this more thoroughly for individual
1014
 * key types.
1015
 */
1016
#define KU_TLS \
1017
    KU_DIGITAL_SIGNATURE | KU_KEY_ENCIPHERMENT | KU_KEY_AGREEMENT
1018
1019
static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
1020
    int non_leaf)
1021
0
{
1022
0
    if (xku_reject(x, XKU_SSL_SERVER | XKU_SGC))
1023
0
        return 0;
1024
0
    if (non_leaf)
1025
0
        return check_ssl_ca(x);
1026
1027
0
    if (ns_reject(x, NS_SSL_SERVER))
1028
0
        return 0;
1029
0
    if (ku_reject(x, KU_TLS))
1030
0
        return 0;
1031
1032
0
    return 1;
1033
0
}
1034
1035
static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x,
1036
    int non_leaf)
1037
0
{
1038
0
    int ret = check_purpose_ssl_server(xp, x, non_leaf);
1039
1040
0
    if (!ret || non_leaf)
1041
0
        return ret;
1042
    /* We need to encipher or Netscape complains */
1043
0
    return ku_reject(x, KU_KEY_ENCIPHERMENT) ? 0 : ret;
1044
0
}
1045
1046
/* common S/MIME client checks */
1047
static int purpose_smime(const X509 *x, int non_leaf)
1048
0
{
1049
0
    if (xku_reject(x, XKU_SMIME))
1050
0
        return 0;
1051
0
    if (non_leaf) {
1052
0
        int ca_ret = check_ca(x);
1053
1054
0
        if (ca_ret == 0)
1055
0
            return 0;
1056
        /* Check nsCertType if present */
1057
0
        if (ca_ret != 5 || (x->ex_nscert & NS_SMIME_CA) != 0)
1058
0
            return ca_ret;
1059
0
        else
1060
0
            return 0;
1061
0
    }
1062
0
    if ((x->ex_flags & EXFLAG_NSCERT) != 0) {
1063
0
        if ((x->ex_nscert & NS_SMIME) != 0)
1064
0
            return 1;
1065
        /* Workaround for some buggy certificates */
1066
0
        return (x->ex_nscert & NS_SSL_CLIENT) != 0 ? 2 : 0;
1067
0
    }
1068
0
    return 1;
1069
0
}
1070
1071
static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x,
1072
    int non_leaf)
1073
0
{
1074
0
    int ret = purpose_smime(x, non_leaf);
1075
1076
0
    if (!ret || non_leaf)
1077
0
        return ret;
1078
0
    return ku_reject(x, KU_DIGITAL_SIGNATURE | KU_NON_REPUDIATION) ? 0 : ret;
1079
0
}
1080
1081
static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x,
1082
    int non_leaf)
1083
0
{
1084
0
    int ret = purpose_smime(x, non_leaf);
1085
1086
0
    if (!ret || non_leaf)
1087
0
        return ret;
1088
0
    return ku_reject(x, KU_KEY_ENCIPHERMENT) ? 0 : ret;
1089
0
}
1090
1091
static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x,
1092
    int non_leaf)
1093
0
{
1094
0
    if (non_leaf) {
1095
0
        int ca_ret = check_ca(x);
1096
1097
0
        return ca_ret == 2 ? 0 : ca_ret;
1098
0
    }
1099
0
    return !ku_reject(x, KU_CRL_SIGN);
1100
0
}
1101
1102
/*
1103
 * OCSP helper: this is *not* a full OCSP check. It just checks that each CA
1104
 * is valid. Additional checks must be made on the chain.
1105
 */
1106
static int check_purpose_ocsp_helper(const X509_PURPOSE *xp, const X509 *x,
1107
    int non_leaf)
1108
0
{
1109
    /*
1110
     * Must be a valid CA.  Should we really support the "I don't know" value
1111
     * (2)?
1112
     */
1113
0
    if (non_leaf)
1114
0
        return check_ca(x);
1115
    /* Leaf certificate is checked in OCSP_basic_verify() */
1116
0
    return 1;
1117
0
}
1118
1119
static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x,
1120
    int non_leaf)
1121
0
{
1122
0
    int i_ext;
1123
1124
    /*
1125
     * If non_leaf is true we must check if this is a valid CA certificate.
1126
     * The extra requirements by the CA/Browser Forum are not checked.
1127
     */
1128
0
    if (non_leaf)
1129
0
        return check_ca(x);
1130
1131
    /*
1132
     * Key Usage is checked according to RFC 5280 and
1133
     * Extended Key Usage attributes is checked according to RFC 3161.
1134
     * The extra (and somewhat conflicting) CA/Browser Forum
1135
     * Baseline Requirements for the Issuance and Management of
1136
     * Publicly‐Trusted Code Signing Certificates, Version 3.0.0,
1137
     * Section 7.1.2.3: Code signing and Timestamp Certificate are not checked.
1138
     */
1139
    /*
1140
     * Check the optional key usage field:
1141
     * if Key Usage is present, it must be one of digitalSignature
1142
     * and/or nonRepudiation (other values are not consistent and shall
1143
     * be rejected).
1144
     */
1145
0
    if ((x->ex_flags & EXFLAG_KUSAGE) != 0
1146
0
        && ((x->ex_kusage & ~(KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE)) || !(x->ex_kusage & (KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE))))
1147
0
        return 0;
1148
1149
    /* Only timestamp key usage is permitted and it's required. */
1150
0
    if ((x->ex_flags & EXFLAG_XKUSAGE) == 0 || x->ex_xkusage != XKU_TIMESTAMP)
1151
0
        return 0;
1152
1153
    /* Extended Key Usage MUST be critical */
1154
0
    i_ext = X509_get_ext_by_NID(x, NID_ext_key_usage, -1);
1155
0
    if (i_ext >= 0
1156
0
        && !X509_EXTENSION_get_critical(X509_get_ext((X509 *)x, i_ext)))
1157
0
        return 0;
1158
0
    return 1;
1159
0
}
1160
1161
static int check_purpose_code_sign(const X509_PURPOSE *xp, const X509 *x,
1162
    int non_leaf)
1163
0
{
1164
0
    int i_ext;
1165
1166
    /*
1167
     * If non_leaf is true we must check if this is a valid CA certificate.
1168
     * The extra requirements by the CA/Browser Forum are not checked.
1169
     */
1170
0
    if (non_leaf)
1171
0
        return check_ca(x);
1172
1173
    /*
1174
     * Check the key usage and extended key usage fields:
1175
     *
1176
     * Reference: CA/Browser Forum,
1177
     * Baseline Requirements for the Issuance and Management of
1178
     * Publicly‐Trusted Code Signing Certificates, Version 3.0.0,
1179
     * Section 7.1.2.3: Code signing and Timestamp Certificate
1180
     *
1181
     * Checking covers Key Usage and Extended Key Usage attributes.
1182
     * The certificatePolicies, cRLDistributionPoints (CDP), and
1183
     * authorityInformationAccess (AIA) extensions are so far not checked.
1184
     */
1185
    /* Key Usage */
1186
0
    if ((x->ex_flags & EXFLAG_KUSAGE) == 0)
1187
0
        return 0;
1188
0
    if ((x->ex_kusage & KU_DIGITAL_SIGNATURE) == 0)
1189
0
        return 0;
1190
0
    if ((x->ex_kusage & (KU_KEY_CERT_SIGN | KU_CRL_SIGN)) != 0)
1191
0
        return 0;
1192
1193
    /* Key Usage MUST be critical */
1194
0
    i_ext = X509_get_ext_by_NID(x, NID_key_usage, -1);
1195
0
    if (i_ext < 0)
1196
0
        return 0;
1197
0
    if (i_ext >= 0) {
1198
0
        const X509_EXTENSION *ext = X509_get_ext((X509 *)x, i_ext);
1199
0
        if (!X509_EXTENSION_get_critical(ext))
1200
0
            return 0;
1201
0
    }
1202
1203
    /* Extended Key Usage */
1204
0
    if ((x->ex_flags & EXFLAG_XKUSAGE) == 0)
1205
0
        return 0;
1206
0
    if ((x->ex_xkusage & XKU_CODE_SIGN) == 0)
1207
0
        return 0;
1208
0
    if ((x->ex_xkusage & (XKU_ANYEKU | XKU_SSL_SERVER)) != 0)
1209
0
        return 0;
1210
1211
0
    return 1;
1212
0
}
1213
1214
static int no_check_purpose(const X509_PURPOSE *xp, const X509 *x,
1215
    int non_leaf)
1216
0
{
1217
0
    return 1;
1218
0
}
1219
1220
static int check_name_constraints(const NAME_CONSTRAINTS *nc)
1221
0
{
1222
0
    GENERAL_SUBTREE *sub;
1223
0
    int ret = 1;
1224
1225
0
    if (nc == NULL)
1226
0
        goto done;
1227
1228
0
    for (int i = 0; nc->permittedSubtrees != NULL
1229
0
        && i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees);
1230
0
        i++) {
1231
0
        sub = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i);
1232
0
        if (sub->base->type == GEN_OTHERNAME
1233
0
            && OBJ_obj2nid(sub->base->d.otherName->type_id)
1234
0
                == NID_id_on_SmtpUTF8Mailbox) {
1235
            /* RFC 9598 prohibits GEN_OTHERNAME email constraints */
1236
0
            ERR_raise(ERR_LIB_X509V3, X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE);
1237
0
            ret = 0;
1238
0
            goto done;
1239
0
        }
1240
0
    }
1241
0
    for (int i = 0; nc->excludedSubtrees != NULL
1242
0
        && i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees);
1243
0
        i++) {
1244
0
        sub = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i);
1245
0
        if (sub->base->type == GEN_OTHERNAME
1246
0
            && OBJ_obj2nid(sub->base->d.otherName->type_id)
1247
0
                == NID_id_on_SmtpUTF8Mailbox) {
1248
            /* RFC 9598 prohibits GEN_OTHERNAME email constraints */
1249
0
            ERR_raise(ERR_LIB_X509V3, X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE);
1250
0
            ret = 0;
1251
0
            goto done;
1252
0
        }
1253
0
    }
1254
1255
0
done:
1256
0
    return ret;
1257
0
}
1258
1259
/*-
1260
 * Various checks to see if one certificate potentially issued the second.
1261
 * This can be used to prune a set of possible issuer certificates which
1262
 * have been looked up using some simple method such as by subject name.
1263
 * These are:
1264
 * 1. issuer_name(subject) == subject_name(issuer)
1265
 * 2. If akid(subject) exists, it matches the respective issuer fields.
1266
 * 3. subject signature algorithm == issuer public key algorithm
1267
 * 4. If key_usage(issuer) exists, it allows for signing subject.
1268
 * Note that this does not include actually checking the signature.
1269
 * Returns 0 for OK, or positive for reason for mismatch
1270
 * where reason codes match those for X509_verify_cert().
1271
 */
1272
int X509_check_issued(const X509 *issuer, const X509 *subject)
1273
0
{
1274
0
    int ret;
1275
1276
0
    if ((ret = ossl_x509_likely_issued(issuer, subject)) != X509_V_OK)
1277
0
        return ret;
1278
0
    return ossl_x509_signing_allowed(issuer, subject);
1279
0
}
1280
1281
/*
1282
 * Do the checks 1., 2., and 3. as described above for X509_check_issued().
1283
 * These are very similar to a section of ossl_x509v3_cache_extensions().
1284
 * If |issuer| equals |subject| (such that self-signature should be checked),
1285
 * use the EXFLAG_SS result of ossl_x509v3_cache_extensions().
1286
 */
1287
int ossl_x509_likely_issued(const X509 *issuer, const X509 *subject)
1288
0
{
1289
0
    int ret;
1290
1291
0
    if (X509_NAME_cmp(X509_get_subject_name(issuer),
1292
0
            X509_get_issuer_name(subject))
1293
0
        != 0)
1294
0
        return X509_V_ERR_SUBJECT_ISSUER_MISMATCH;
1295
1296
    /* set issuer->skid, subject->akid, and subject->ex_flags */
1297
0
    if (!ossl_x509v3_cache_extensions(issuer)
1298
0
        || !ossl_x509v3_cache_extensions(subject))
1299
0
        return X509_V_ERR_UNSPECIFIED;
1300
1301
0
    if (issuer == subject
1302
0
        || (X509_NAME_cmp(X509_get_issuer_name(issuer), X509_get_issuer_name(subject)) == 0
1303
0
            && ASN1_INTEGER_cmp(X509_get0_serialNumber(issuer), X509_get0_serialNumber(subject)) == 0))
1304
        /*
1305
         * At this point, we can assume that issuer and subject
1306
         * are semantically the same cert because they are identical
1307
         * or at least have the same issuer and serial number,
1308
         * which (for any sane cert issuer) implies equality of the two certs.
1309
         * In this case, for consistency with chain building and validation,
1310
         * we make our issuance judgment depend on the presence of EXFLAG_SS.
1311
         * This is used for corrected chain building in the corner case of
1312
         * a self-issued but not actually self-signed trust anchor cert
1313
         * without subject and issuer key identifiers (i.e., no SKID and AKID).
1314
         */
1315
0
        return (issuer->ex_flags & EXFLAG_SS) != 0
1316
0
            ? X509_V_OK
1317
0
            : X509_V_ERR_CERT_SIGNATURE_FAILURE;
1318
1319
0
    ret = X509_check_akid(issuer, subject->akid);
1320
0
    if (ret != X509_V_OK)
1321
0
        return ret;
1322
1323
    /* Check if the subject signature alg matches the issuer's PUBKEY alg */
1324
0
    return check_sig_alg_match(X509_get0_pubkey(issuer), subject);
1325
0
}
1326
1327
/*-
1328
 * Check if certificate I<issuer> is allowed to issue certificate I<subject>
1329
 * according to the B<keyUsage> field of I<issuer> if present
1330
 * depending on any proxyCertInfo extension of I<subject>.
1331
 * Returns 0 for OK, or positive for reason for rejection
1332
 * where reason codes match those for X509_verify_cert().
1333
 */
1334
int ossl_x509_signing_allowed(const X509 *issuer, const X509 *subject)
1335
0
{
1336
0
    if ((subject->ex_flags & EXFLAG_PROXY) != 0) {
1337
0
        if (ku_reject(issuer, KU_DIGITAL_SIGNATURE))
1338
0
            return X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
1339
0
    } else if (ku_reject(issuer, KU_KEY_CERT_SIGN)) {
1340
0
        return X509_V_ERR_KEYUSAGE_NO_CERTSIGN;
1341
0
    }
1342
0
    return X509_V_OK;
1343
0
}
1344
1345
/*
1346
 * check if all sub-fields of the authority key identifier information akid,
1347
 * as far as present, match the respective subjectKeyIdentifier extension (if
1348
 * present in issuer), serialNumber field, and issuer fields of issuer.
1349
 * returns X509_V_OK also if akid is NULL because this means no restriction.
1350
 */
1351
int X509_check_akid(const X509 *issuer, const AUTHORITY_KEYID *akid)
1352
0
{
1353
0
    if (akid == NULL)
1354
0
        return X509_V_OK;
1355
1356
    /* Check key ids (if present) */
1357
0
    if (akid->keyid && issuer->skid && ASN1_OCTET_STRING_cmp(akid->keyid, issuer->skid))
1358
0
        return X509_V_ERR_AKID_SKID_MISMATCH;
1359
    /* Check serial number */
1360
0
    if (akid->serial && ASN1_INTEGER_cmp(X509_get0_serialNumber(issuer), akid->serial))
1361
0
        return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
1362
    /* Check issuer name */
1363
0
    if (akid->issuer) {
1364
        /*
1365
         * Ugh, for some peculiar reason AKID includes SEQUENCE OF
1366
         * GeneralName. So look for a DirName. There may be more than one but
1367
         * we only take any notice of the first.
1368
         */
1369
0
        GENERAL_NAMES *gens = akid->issuer;
1370
0
        GENERAL_NAME *gen;
1371
0
        X509_NAME *nm = NULL;
1372
0
        int i;
1373
1374
0
        for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1375
0
            gen = sk_GENERAL_NAME_value(gens, i);
1376
0
            if (gen->type == GEN_DIRNAME) {
1377
0
                nm = gen->d.dirn;
1378
0
                break;
1379
0
            }
1380
0
        }
1381
0
        if (nm != NULL && X509_NAME_cmp(nm, X509_get_issuer_name(issuer)) != 0)
1382
0
            return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
1383
0
    }
1384
0
    return X509_V_OK;
1385
0
}
1386
1387
uint32_t X509_get_extension_flags(const X509 *x)
1388
0
{
1389
    /* Call for side-effect of computing hash and caching extensions */
1390
0
    X509_check_purpose(x, -1, 0);
1391
0
    return x->ex_flags;
1392
0
}
1393
1394
uint32_t X509_get_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_KUSAGE) != 0 ? x->ex_kusage : UINT32_MAX;
1400
0
}
1401
1402
uint32_t X509_get_extended_key_usage(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 0;
1407
0
    return (x->ex_flags & EXFLAG_XKUSAGE) != 0 ? x->ex_xkusage : UINT32_MAX;
1408
0
}
1409
1410
const ASN1_OCTET_STRING *X509_get0_subject_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->skid;
1416
0
}
1417
1418
const ASN1_OCTET_STRING *X509_get0_authority_key_id(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->keyid : NULL);
1424
0
}
1425
1426
const GENERAL_NAMES *X509_get0_authority_issuer(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->issuer : NULL);
1432
0
}
1433
1434
const ASN1_INTEGER *X509_get0_authority_serial(const X509 *x)
1435
0
{
1436
    /* Call for side-effect of computing hash and caching extensions */
1437
0
    if (X509_check_purpose(x, -1, 0) != 1)
1438
0
        return NULL;
1439
0
    return (x->akid != NULL ? x->akid->serial : NULL);
1440
0
}
1441
1442
long X509_get_pathlen(const X509 *x)
1443
0
{
1444
    /* Called for side effect of caching extensions */
1445
0
    if (X509_check_purpose(x, -1, 0) != 1
1446
0
        || (x->ex_flags & EXFLAG_BCONS) == 0)
1447
0
        return -1;
1448
0
    return x->ex_pathlen;
1449
0
}
1450
1451
long X509_get_proxy_pathlen(const X509 *x)
1452
0
{
1453
    /* Called for side effect of caching extensions */
1454
0
    if (X509_check_purpose(x, -1, 0) != 1
1455
0
        || (x->ex_flags & EXFLAG_PROXY) == 0)
1456
0
        return -1;
1457
0
    return x->ex_pcpathlen;
1458
0
}