Coverage Report

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