Coverage Report

Created: 2026-05-20 07:05

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
/* Returns 1 on success, 0 if x is invalid, -1 on (internal) error. */
350
static int setup_dp(const X509 *x, DIST_POINT *dp)
351
0
{
352
0
    const X509_NAME *iname = NULL;
353
0
    int i;
354
355
0
    if (dp->distpoint == NULL && sk_GENERAL_NAME_num(dp->CRLissuer) <= 0) {
356
0
        ERR_raise(ERR_LIB_X509, X509_R_INVALID_DISTPOINT);
357
0
        return 0;
358
0
    }
359
0
    if (dp->reasons != NULL) {
360
0
        if (dp->reasons->length > 0)
361
0
            dp->dp_reasons = dp->reasons->data[0];
362
0
        if (dp->reasons->length > 1)
363
0
            dp->dp_reasons |= (dp->reasons->data[1] << 8);
364
0
        dp->dp_reasons &= CRLDP_ALL_REASONS;
365
0
    } else {
366
0
        dp->dp_reasons = CRLDP_ALL_REASONS;
367
0
    }
368
0
    if (dp->distpoint == NULL || dp->distpoint->type != 1)
369
0
        return 1;
370
371
    /* Handle name fragment given by nameRelativeToCRLIssuer */
372
    /*
373
     * Note that the below way of determining iname is not really compliant
374
     * with https://tools.ietf.org/html/rfc5280#section-4.2.1.13
375
     * According to it, sk_GENERAL_NAME_num(dp->CRLissuer) MUST be <= 1
376
     * and any CRLissuer could be of type different to GEN_DIRNAME.
377
     */
378
0
    for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
379
0
        GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
380
381
0
        if (gen->type == GEN_DIRNAME) {
382
0
            iname = gen->d.directoryName;
383
0
            break;
384
0
        }
385
0
    }
386
0
    if (iname == NULL)
387
0
        iname = X509_get_issuer_name(x);
388
0
    return DIST_POINT_set_dpname(dp->distpoint, iname) ? 1 : -1;
389
0
}
390
391
/* Return 1 on success, 0 if x is invalid, -1 on (internal) error. */
392
static int setup_crldp(const X509 *x, STACK_OF(DIST_POINT) **tmp_crldp)
393
0
{
394
0
    int i;
395
396
0
    *tmp_crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, &i, NULL);
397
0
    if (*tmp_crldp == NULL && i != -1)
398
0
        return 0;
399
400
0
    for (i = 0; i < sk_DIST_POINT_num(*tmp_crldp); i++) {
401
0
        int res = setup_dp(x, sk_DIST_POINT_value(*tmp_crldp, i));
402
403
0
        if (res < 1)
404
0
            return res;
405
0
    }
406
0
    return 1;
407
0
}
408
409
/* Check that issuer public key algorithm matches subject signature algorithm */
410
static int check_sig_alg_match(const EVP_PKEY *issuer_key, const X509 *subject)
411
0
{
412
0
    int subj_sig_nid;
413
414
0
    if (issuer_key == NULL)
415
0
        return X509_V_ERR_NO_ISSUER_PUBLIC_KEY;
416
0
    if (OBJ_find_sigid_algs(OBJ_obj2nid(subject->cert_info.signature.algorithm),
417
0
            NULL, &subj_sig_nid)
418
0
        == 0)
419
0
        return X509_V_ERR_UNSUPPORTED_SIGNATURE_ALGORITHM;
420
0
    if (EVP_PKEY_is_a(issuer_key, OBJ_nid2sn(subj_sig_nid))
421
0
        || (EVP_PKEY_is_a(issuer_key, "RSA") && subj_sig_nid == NID_rsassaPss))
422
0
        return X509_V_OK;
423
0
    return X509_V_ERR_SIGNATURE_ALGORITHM_MISMATCH;
424
0
}
425
426
static unsigned long oid_hash(const void *p)
427
0
{
428
0
    const ASN1_OBJECT *a = p;
429
430
0
    return (unsigned long)ossl_fnv1a_hash((uint8_t *)a->data, a->length);
431
0
}
432
433
static int oid_cmp(const void *a, const void *b)
434
0
{
435
0
    return OBJ_cmp((const ASN1_OBJECT *)a, (const ASN1_OBJECT *)b);
436
0
}
437
438
/*
439
 * Scan all extensions of a certificate to collect extension-related flags.
440
 * Detects duplicate extensions (RFC 5280 section 4.2), the presence of a
441
 * freshest CRL extension and unsupported critical extensions.
442
 *
443
 * In the future, if needed, this scanning function could return the index
444
 * of the offending extension on error, allowing the caller to identify which
445
 * extension caused the problem and report it via ERR_raise_data().
446
 */
447
static void scan_ext_flags(const X509 *x509, uint32_t *flags)
448
0
{
449
0
    OPENSSL_LHASH *h = NULL;
450
0
    uint8_t ex_bitset[(NUM_NID + 7) / 8];
451
452
0
    memset(ex_bitset, 0, sizeof(ex_bitset));
453
    /* A certificate MUST NOT include more than one instance of an extension. */
454
0
    for (int i = 0; i < X509_get_ext_count(x509); i++) {
455
0
        const X509_EXTENSION *ex = X509_get_ext(x509, i);
456
0
        const ASN1_OBJECT *a = X509_EXTENSION_get_object(ex);
457
0
        int nid = OBJ_obj2nid(a);
458
459
        /*
460
         * Known NIDs within the build-time bitset limit are checked for
461
         * duplicates in constant time. Unknown OIDs and dynamically registered
462
         * NIDs that exceed the limit fall back to duplicate detection via a
463
         * hash table.
464
         */
465
0
        if (nid > NID_undef && nid < NUM_NID) {
466
0
            unsigned int ex_bit = nid;
467
468
0
            if ((ex_bitset[ex_bit >> 3] & (1u << (ex_bit & 7))) != 0) {
469
0
                *flags |= EXFLAG_DUPLICATE;
470
0
                break;
471
0
            }
472
0
            ex_bitset[ex_bit >> 3] |= (1u << (ex_bit & 7));
473
0
        } else {
474
            /*
475
             * Extensions with unknown NID (NID_undef) and dynamically
476
             * registered NIDs are handled here by hashing the OID (data/length).
477
             * A zero-length OID should not reach this point, but we check for
478
             * it anyway and assign the EXFLAG_INVALID flag if it does.
479
             */
480
0
            if (a->length < 1) {
481
0
                *flags |= EXFLAG_INVALID;
482
0
                break;
483
0
            }
484
            /*
485
             * Hashing the OID should be manageable more cheaply as well, and
486
             * without additional dynamic allocations. In the case of this
487
             * corner case, it’s not a problem at all, but the other duplicate
488
             * detections also require hashing, so for the sake of consistency
489
             * it would make sense to use a cheaper construct here later as well.
490
             */
491
0
            if (h == NULL && (h = OPENSSL_LH_new(oid_hash, oid_cmp)) == NULL)
492
0
                break;
493
0
            if (OPENSSL_LH_insert(h, (void *)a) != NULL) {
494
0
                *flags |= EXFLAG_DUPLICATE;
495
0
                break;
496
0
            }
497
0
        }
498
0
        if (nid == NID_freshest_crl)
499
0
            *flags |= EXFLAG_FRESHEST;
500
0
        if (!X509_EXTENSION_get_critical(ex))
501
0
            continue;
502
0
        if (!X509_supported_extension(ex)) {
503
0
            *flags |= EXFLAG_CRITICAL;
504
0
            break;
505
0
        }
506
0
    }
507
0
    OPENSSL_LH_free(h);
508
0
}
509
510
0
#define V1_ROOT (EXFLAG_V1 | EXFLAG_SS)
511
#define ku_reject(x, usage) \
512
0
    (((x)->ex_flags & EXFLAG_KUSAGE) != 0 && ((x)->ex_kusage & (usage)) == 0)
513
#define xku_reject(x, usage) \
514
0
    (((x)->ex_flags & EXFLAG_XKUSAGE) != 0 && ((x)->ex_xkusage & (usage)) == 0)
515
#define ns_reject(x, usage) \
516
0
    (((x)->ex_flags & EXFLAG_NSCERT) != 0 && ((x)->ex_nscert & (usage)) == 0)
517
518
/*
519
 * Cache info on various X.509v3 extensions and further derived information,
520
 * e.g., if cert 'x' is self-issued, in x->ex_flags and other internal fields.
521
 * x->sha1_hash is filled in, or else EXFLAG_NO_FINGERPRINT is set in x->flags.
522
 * X509_SIG_INFO_VALID is set in x->flags if x->siginf was filled successfully.
523
 * Set EXFLAG_INVALID and return 0 in case the certificate is invalid.
524
 *
525
 * This is usually called by side-effect on objects, and forces us to keep
526
 * mutable X509 objects around. We should really make this go away.
527
 * In the interest of being able to do so, this function explicitly takes
528
 * a const argument and casts away const.
529
 */
530
int ossl_x509v3_cache_extensions(const X509 *const_x)
531
0
{
532
0
    BASIC_CONSTRAINTS *bs;
533
0
    PROXY_CERT_INFO_EXTENSION *pci;
534
0
    ASN1_BIT_STRING *usage;
535
0
    ASN1_BIT_STRING *ns;
536
0
    EXTENDED_KEY_USAGE *extusage;
537
0
    int i;
538
0
    int res;
539
0
    uint32_t tmp_ex_flags;
540
0
    unsigned char tmp_sha1_hash[SHA_DIGEST_LENGTH];
541
0
    long tmp_ex_pathlen;
542
0
    long tmp_ex_pcpathlen;
543
0
    uint32_t tmp_ex_kusage;
544
0
    uint32_t tmp_ex_xkusage;
545
0
    uint32_t tmp_ex_nscert;
546
0
    ASN1_OCTET_STRING *tmp_skid;
547
0
    AUTHORITY_KEYID *tmp_akid;
548
0
    STACK_OF(GENERAL_NAME) *tmp_altname;
549
0
    NAME_CONSTRAINTS *tmp_nc;
550
0
    STACK_OF(DIST_POINT) *tmp_crldp = NULL;
551
0
    X509_SIG_INFO tmp_siginf;
552
553
0
#ifdef tsan_ld_acq
554
    /* Fast lock-free check, see end of the function for details. */
555
0
    if (tsan_ld_acq((TSAN_QUALIFIER int *)&const_x->ex_cached))
556
0
        return (const_x->ex_flags & EXFLAG_INVALID) == 0;
557
0
#endif
558
559
0
    if (!CRYPTO_THREAD_read_lock(const_x->lock))
560
0
        return 0;
561
0
    tmp_ex_flags = const_x->ex_flags;
562
0
    tmp_ex_pcpathlen = const_x->ex_pcpathlen;
563
0
    tmp_ex_kusage = const_x->ex_kusage;
564
0
    tmp_ex_nscert = const_x->ex_nscert;
565
566
0
    if ((tmp_ex_flags & EXFLAG_SET) != 0) { /* Cert has already been processed */
567
0
        CRYPTO_THREAD_unlock(const_x->lock);
568
0
        return (tmp_ex_flags & EXFLAG_INVALID) == 0;
569
0
    }
570
571
0
    ERR_set_mark();
572
573
    /* Cache the SHA1 digest of the cert */
574
0
    if (!X509_digest(const_x, EVP_sha1(), tmp_sha1_hash, NULL))
575
0
        tmp_ex_flags |= EXFLAG_NO_FINGERPRINT;
576
577
    /* V1 should mean no extensions ... */
578
0
    if (X509_get_version(const_x) == X509_VERSION_1)
579
0
        tmp_ex_flags |= EXFLAG_V1;
580
581
    /* Handle basic constraints */
582
0
    tmp_ex_pathlen = -1;
583
0
    if ((bs = X509_get_ext_d2i(const_x, NID_basic_constraints, &i, NULL)) != NULL) {
584
0
        if (bs->ca)
585
0
            tmp_ex_flags |= EXFLAG_CA;
586
0
        if (bs->pathlen != NULL) {
587
            /*
588
             * The error case !bs->ca is checked by check_chain()
589
             * in case ctx->param->flags & X509_V_FLAG_X509_STRICT
590
             */
591
0
            if (bs->pathlen->type == V_ASN1_NEG_INTEGER) {
592
0
                ERR_raise(ERR_LIB_X509V3, X509V3_R_NEGATIVE_PATHLEN);
593
0
                tmp_ex_flags |= EXFLAG_INVALID;
594
0
            } else {
595
0
                tmp_ex_pathlen = ASN1_INTEGER_get(bs->pathlen);
596
0
            }
597
0
        }
598
0
        BASIC_CONSTRAINTS_free(bs);
599
0
        tmp_ex_flags |= EXFLAG_BCONS;
600
0
    } else if (i != -1) {
601
0
        tmp_ex_flags |= EXFLAG_INVALID;
602
0
    }
603
604
    /* Handle proxy certificates */
605
0
    if ((pci = X509_get_ext_d2i(const_x, NID_proxyCertInfo, &i, NULL)) != NULL) {
606
0
        if ((tmp_ex_flags & EXFLAG_CA) != 0
607
0
            || X509_get_ext_by_NID(const_x, NID_subject_alt_name, -1) >= 0
608
0
            || X509_get_ext_by_NID(const_x, NID_issuer_alt_name, -1) >= 0) {
609
0
            tmp_ex_flags |= EXFLAG_INVALID;
610
0
        }
611
0
        if (pci->pcPathLengthConstraint != NULL)
612
0
            tmp_ex_pcpathlen = ASN1_INTEGER_get(pci->pcPathLengthConstraint);
613
0
        else
614
0
            tmp_ex_pcpathlen = -1;
615
0
        PROXY_CERT_INFO_EXTENSION_free(pci);
616
0
        tmp_ex_flags |= EXFLAG_PROXY;
617
0
    } else if (i != -1) {
618
0
        tmp_ex_flags |= EXFLAG_INVALID;
619
0
    }
620
621
    /* Handle (basic) key usage */
622
0
    if ((usage = X509_get_ext_d2i(const_x, NID_key_usage, &i, NULL)) != NULL) {
623
0
        tmp_ex_kusage = 0;
624
0
        if (usage->length > 0) {
625
0
            tmp_ex_kusage = usage->data[0];
626
0
            if (usage->length > 1)
627
0
                tmp_ex_kusage |= usage->data[1] << 8;
628
0
        }
629
0
        tmp_ex_flags |= EXFLAG_KUSAGE;
630
0
        ASN1_BIT_STRING_free(usage);
631
        /* Check for empty key usage according to RFC 5280 section 4.2.1.3 */
632
0
        if (tmp_ex_kusage == 0) {
633
0
            ERR_raise(ERR_LIB_X509V3, X509V3_R_EMPTY_KEY_USAGE);
634
0
            tmp_ex_flags |= EXFLAG_INVALID;
635
0
        }
636
0
    } else if (i != -1) {
637
0
        tmp_ex_flags |= EXFLAG_INVALID;
638
0
    }
639
640
    /* Handle extended key usage */
641
0
    tmp_ex_xkusage = 0;
642
0
    if ((extusage = X509_get_ext_d2i(const_x, NID_ext_key_usage, &i, NULL)) != NULL) {
643
0
        tmp_ex_flags |= EXFLAG_XKUSAGE;
644
0
        for (i = 0; i < sk_ASN1_OBJECT_num(extusage); i++) {
645
0
            switch (OBJ_obj2nid(sk_ASN1_OBJECT_value(extusage, i))) {
646
0
            case NID_server_auth:
647
0
                tmp_ex_xkusage |= XKU_SSL_SERVER;
648
0
                break;
649
0
            case NID_client_auth:
650
0
                tmp_ex_xkusage |= XKU_SSL_CLIENT;
651
0
                break;
652
0
            case NID_email_protect:
653
0
                tmp_ex_xkusage |= XKU_SMIME;
654
0
                break;
655
0
            case NID_code_sign:
656
0
                tmp_ex_xkusage |= XKU_CODE_SIGN;
657
0
                break;
658
0
            case NID_ms_sgc:
659
0
            case NID_ns_sgc:
660
0
                tmp_ex_xkusage |= XKU_SGC;
661
0
                break;
662
0
            case NID_OCSP_sign:
663
0
                tmp_ex_xkusage |= XKU_OCSP_SIGN;
664
0
                break;
665
0
            case NID_time_stamp:
666
0
                tmp_ex_xkusage |= XKU_TIMESTAMP;
667
0
                break;
668
0
            case NID_dvcs:
669
0
                tmp_ex_xkusage |= XKU_DVCS;
670
0
                break;
671
0
            case NID_anyExtendedKeyUsage:
672
0
                tmp_ex_xkusage |= XKU_ANYEKU;
673
0
                break;
674
0
            default:
675
                /* Ignore unknown extended key usage */
676
0
                break;
677
0
            }
678
0
        }
679
0
        sk_ASN1_OBJECT_pop_free(extusage, ASN1_OBJECT_free);
680
0
    } else if (i != -1) {
681
0
        tmp_ex_flags |= EXFLAG_INVALID;
682
0
    }
683
684
    /* Handle legacy Netscape extension */
685
0
    if ((ns = X509_get_ext_d2i(const_x, NID_netscape_cert_type, &i, NULL)) != NULL) {
686
0
        if (ns->length > 0)
687
0
            tmp_ex_nscert = ns->data[0];
688
0
        else
689
0
            tmp_ex_nscert = 0;
690
0
        tmp_ex_flags |= EXFLAG_NSCERT;
691
0
        ASN1_BIT_STRING_free(ns);
692
0
    } else if (i != -1) {
693
0
        tmp_ex_flags |= EXFLAG_INVALID;
694
0
    }
695
696
    /* Handle subject key identifier and issuer/authority key identifier */
697
0
    tmp_skid = X509_get_ext_d2i(const_x, NID_subject_key_identifier, &i, NULL);
698
0
    if (tmp_skid == NULL && i != -1)
699
0
        tmp_ex_flags |= EXFLAG_INVALID;
700
701
0
    tmp_akid = X509_get_ext_d2i(const_x, NID_authority_key_identifier, &i, NULL);
702
0
    if (tmp_akid == NULL && i != -1)
703
0
        tmp_ex_flags |= EXFLAG_INVALID;
704
705
    /* Setting EXFLAG_SS is equivalent to ossl_x509_likely_issued(const_x, const_x) == X509_V_OK */
706
0
    if (X509_NAME_cmp(X509_get_subject_name(const_x), X509_get_issuer_name(const_x)) == 0) {
707
0
        tmp_ex_flags |= EXFLAG_SI; /* Certificate is self-issued: subject == issuer */
708
        /*
709
         * When the SKID is missing, which is rare for self-issued certs,
710
         * we could afford doing the (accurate) actual self-signature check, but
711
         * decided against it for efficiency reasons and according to RFC 5280,
712
         * CA certs MUST have an SKID and non-root certs MUST have an AKID.
713
         */
714
0
        if (X509_check_akid(const_x, tmp_akid) == X509_V_OK
715
0
            && check_sig_alg_match(X509_get0_pubkey(const_x), const_x) == X509_V_OK) {
716
            /*
717
             * Assume self-signed if the signature alg matches the pkey alg and
718
             * AKID is missing or matches respective fields in the same cert
719
             * Not checking if any given key usage extension allows signing.
720
             */
721
0
            tmp_ex_flags |= EXFLAG_SS;
722
0
        }
723
0
    }
724
725
    /* Handle subject alternative names and various other extensions */
726
0
    tmp_altname = X509_get_ext_d2i(const_x, NID_subject_alt_name, &i, NULL);
727
0
    if (tmp_altname == NULL && i != -1)
728
0
        tmp_ex_flags |= EXFLAG_INVALID;
729
0
    tmp_nc = X509_get_ext_d2i(const_x, NID_name_constraints, &i, NULL);
730
0
    if (tmp_nc == NULL && i != -1)
731
0
        tmp_ex_flags |= EXFLAG_INVALID;
732
0
    if (!check_name_constraints(tmp_nc))
733
0
        tmp_ex_flags |= EXFLAG_INVALID;
734
735
    /* Handle CRL distribution point entries */
736
0
    res = setup_crldp(const_x, &tmp_crldp);
737
0
    if (res == 0)
738
0
        tmp_ex_flags |= EXFLAG_INVALID;
739
740
0
#ifndef OPENSSL_NO_RFC3779
741
0
    STACK_OF(IPAddressFamily) *tmp_rfc3779_addr
742
0
        = X509_get_ext_d2i(const_x, NID_sbgp_ipAddrBlock, &i, NULL);
743
0
    if (tmp_rfc3779_addr == NULL && i != -1)
744
0
        tmp_ex_flags |= EXFLAG_INVALID;
745
746
0
    struct ASIdentifiers_st *tmp_rfc3779_asid
747
0
        = X509_get_ext_d2i(const_x, NID_sbgp_autonomousSysNum, &i, NULL);
748
0
    if (tmp_rfc3779_asid == NULL && i != -1)
749
0
        tmp_ex_flags |= EXFLAG_INVALID;
750
0
#endif
751
752
0
    scan_ext_flags(const_x, &tmp_ex_flags);
753
754
    /* Set x->siginf, ignoring errors due to unsupported algos */
755
0
    (void)ossl_x509_init_sig_info(const_x, &tmp_siginf);
756
757
0
    tmp_ex_flags |= EXFLAG_SET; /* Indicate that cert has been processed */
758
0
    ERR_pop_to_mark();
759
760
0
    CRYPTO_THREAD_unlock(const_x->lock);
761
    /*
762
     * Now that we've done all the compute intensive work under read lock
763
     * do all the updating under a write lock
764
     */
765
0
    if (!CRYPTO_THREAD_write_lock(const_x->lock))
766
0
        return 0;
767
0
    ((X509 *)const_x)->ex_flags = tmp_ex_flags;
768
0
    ((X509 *)const_x)->ex_pathlen = tmp_ex_pathlen;
769
0
    ((X509 *)const_x)->ex_pcpathlen = tmp_ex_pcpathlen;
770
0
    if (!(tmp_ex_flags & EXFLAG_NO_FINGERPRINT))
771
0
        memcpy(((X509 *)const_x)->sha1_hash, tmp_sha1_hash, SHA_DIGEST_LENGTH);
772
0
    if (tmp_ex_flags & EXFLAG_KUSAGE)
773
0
        ((X509 *)const_x)->ex_kusage = tmp_ex_kusage;
774
0
    ((X509 *)const_x)->ex_xkusage = tmp_ex_xkusage;
775
0
    if (tmp_ex_flags & EXFLAG_NSCERT)
776
0
        ((X509 *)const_x)->ex_nscert = tmp_ex_nscert;
777
0
    ASN1_OCTET_STRING_free(((X509 *)const_x)->skid);
778
0
    ((X509 *)const_x)->skid = tmp_skid;
779
0
    AUTHORITY_KEYID_free(((X509 *)const_x)->akid);
780
0
    ((X509 *)const_x)->akid = tmp_akid;
781
0
    sk_GENERAL_NAME_pop_free(((X509 *)const_x)->altname, GENERAL_NAME_free);
782
0
    ((X509 *)const_x)->altname = tmp_altname;
783
0
    NAME_CONSTRAINTS_free(((X509 *)const_x)->nc);
784
0
    ((X509 *)const_x)->nc = tmp_nc;
785
0
    sk_DIST_POINT_pop_free(((X509 *)const_x)->crldp, DIST_POINT_free);
786
0
    ((X509 *)const_x)->crldp = tmp_crldp;
787
0
#ifndef OPENSSL_NO_RFC3779
788
0
    sk_IPAddressFamily_pop_free(((X509 *)const_x)->rfc3779_addr, IPAddressFamily_free);
789
0
    ((X509 *)const_x)->rfc3779_addr = tmp_rfc3779_addr;
790
0
    ASIdentifiers_free(((X509 *)const_x)->rfc3779_asid);
791
0
    ((X509 *)const_x)->rfc3779_asid = tmp_rfc3779_asid;
792
0
#endif
793
0
    ((X509 *)const_x)->siginf = tmp_siginf;
794
795
0
#ifdef tsan_st_rel
796
0
    tsan_st_rel((TSAN_QUALIFIER int *)&const_x->ex_cached, 1);
797
    /*
798
     * Above store triggers fast lock-free check in the beginning of the
799
     * function. But one has to ensure that the structure is "stable", i.e.
800
     * all stores are visible on all processors. Hence the release fence.
801
     */
802
0
#endif
803
0
    CRYPTO_THREAD_unlock(const_x->lock);
804
0
    if (tmp_ex_flags & EXFLAG_INVALID) {
805
0
        ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_CERTIFICATE);
806
0
        return 0;
807
0
    }
808
0
    return 1;
809
0
}
810
811
/*-
812
 * CA checks common to all purposes
813
 * return codes:
814
 * 0 not a CA
815
 * 1 is a CA
816
 * 2 Only possible in older versions of openSSL when basicConstraints are absent
817
 *   new versions will not return this value. May be a CA
818
 * 3 basicConstraints absent but self-signed V1.
819
 * 4 basicConstraints absent but keyUsage present and keyCertSign asserted.
820
 * 5 Netscape specific CA Flags present
821
 */
822
823
static int check_ca(const X509 *x)
824
0
{
825
    /* keyUsage if present should allow cert signing */
826
0
    if (ku_reject(x, KU_KEY_CERT_SIGN))
827
0
        return 0;
828
0
    if ((x->ex_flags & EXFLAG_BCONS) != 0) {
829
        /* If basicConstraints says not a CA then say so */
830
0
        return (x->ex_flags & EXFLAG_CA) != 0;
831
0
    } else {
832
        /* We support V1 roots for...  uh, I don't really know why. */
833
0
        if ((x->ex_flags & V1_ROOT) == V1_ROOT)
834
0
            return 3;
835
        /*
836
         * If key usage present it must have certSign so tolerate it
837
         */
838
0
        else if ((x->ex_flags & EXFLAG_KUSAGE) != 0)
839
0
            return 4;
840
        /* Older certificates could have Netscape-specific CA types */
841
0
        else if ((x->ex_flags & EXFLAG_NSCERT) != 0
842
0
            && (x->ex_nscert & NS_ANY_CA) != 0)
843
0
            return 5;
844
        /* Can this still be regarded a CA certificate?  I doubt it. */
845
0
        return 0;
846
0
    }
847
0
}
848
849
void X509_set_proxy_flag(X509 *x)
850
0
{
851
0
    if (CRYPTO_THREAD_write_lock(x->lock)) {
852
0
        x->ex_flags |= EXFLAG_PROXY;
853
0
        CRYPTO_THREAD_unlock(x->lock);
854
0
    }
855
0
}
856
857
void X509_set_proxy_pathlen(X509 *x, long l)
858
0
{
859
0
    x->ex_pcpathlen = l;
860
0
}
861
862
int X509_check_ca(const X509 *x)
863
0
{
864
    /* Note 0 normally means "not a CA" - but in this case means error. */
865
0
    if (!ossl_x509v3_cache_extensions(x))
866
0
        return 0;
867
868
0
    return check_ca(x);
869
0
}
870
871
/* Check SSL CA: common checks for SSL client and server. */
872
static int check_ssl_ca(const X509 *x)
873
0
{
874
0
    int ca_ret = check_ca(x);
875
876
0
    if (ca_ret == 0)
877
0
        return 0;
878
    /* Check nsCertType if present */
879
0
    return ca_ret != 5 || (x->ex_nscert & NS_SSL_CA) != 0;
880
0
}
881
882
static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
883
    int non_leaf)
884
0
{
885
0
    if (xku_reject(x, XKU_SSL_CLIENT))
886
0
        return 0;
887
0
    if (non_leaf)
888
0
        return check_ssl_ca(x);
889
    /* We need to do digital signatures or key agreement */
890
0
    if (ku_reject(x, KU_DIGITAL_SIGNATURE | KU_KEY_AGREEMENT))
891
0
        return 0;
892
    /* nsCertType if present should allow SSL client use */
893
0
    if (ns_reject(x, NS_SSL_CLIENT))
894
0
        return 0;
895
0
    return 1;
896
0
}
897
898
/*
899
 * Key usage needed for TLS/SSL server: digital signature, encipherment or
900
 * key agreement. The ssl code can check this more thoroughly for individual
901
 * key types.
902
 */
903
#define KU_TLS \
904
    KU_DIGITAL_SIGNATURE | KU_KEY_ENCIPHERMENT | KU_KEY_AGREEMENT
905
906
static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
907
    int non_leaf)
908
0
{
909
0
    if (xku_reject(x, XKU_SSL_SERVER | XKU_SGC))
910
0
        return 0;
911
0
    if (non_leaf)
912
0
        return check_ssl_ca(x);
913
914
0
    if (ns_reject(x, NS_SSL_SERVER))
915
0
        return 0;
916
0
    if (ku_reject(x, KU_TLS))
917
0
        return 0;
918
919
0
    return 1;
920
0
}
921
922
static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x,
923
    int non_leaf)
924
0
{
925
0
    int ret = check_purpose_ssl_server(xp, x, non_leaf);
926
927
0
    if (!ret || non_leaf)
928
0
        return ret;
929
    /* We need to encipher or Netscape complains */
930
0
    return ku_reject(x, KU_KEY_ENCIPHERMENT) ? 0 : ret;
931
0
}
932
933
/* common S/MIME client checks */
934
static int purpose_smime(const X509 *x, int non_leaf)
935
0
{
936
0
    if (xku_reject(x, XKU_SMIME))
937
0
        return 0;
938
0
    if (non_leaf) {
939
0
        int ca_ret = check_ca(x);
940
941
0
        if (ca_ret == 0)
942
0
            return 0;
943
        /* Check nsCertType if present */
944
0
        if (ca_ret != 5 || (x->ex_nscert & NS_SMIME_CA) != 0)
945
0
            return ca_ret;
946
0
        else
947
0
            return 0;
948
0
    }
949
0
    if ((x->ex_flags & EXFLAG_NSCERT) != 0) {
950
0
        if ((x->ex_nscert & NS_SMIME) != 0)
951
0
            return 1;
952
        /* Workaround for some buggy certificates */
953
0
        return (x->ex_nscert & NS_SSL_CLIENT) != 0 ? 2 : 0;
954
0
    }
955
0
    return 1;
956
0
}
957
958
static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x,
959
    int non_leaf)
960
0
{
961
0
    int ret = purpose_smime(x, non_leaf);
962
963
0
    if (!ret || non_leaf)
964
0
        return ret;
965
0
    return ku_reject(x, KU_DIGITAL_SIGNATURE | KU_NON_REPUDIATION) ? 0 : ret;
966
0
}
967
968
static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x,
969
    int non_leaf)
970
0
{
971
0
    int ret = purpose_smime(x, non_leaf);
972
973
0
    if (!ret || non_leaf)
974
0
        return ret;
975
0
    return ku_reject(x, KU_KEY_ENCIPHERMENT) ? 0 : ret;
976
0
}
977
978
static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x,
979
    int non_leaf)
980
0
{
981
0
    if (non_leaf) {
982
0
        int ca_ret = check_ca(x);
983
984
0
        return ca_ret == 2 ? 0 : ca_ret;
985
0
    }
986
0
    return !ku_reject(x, KU_CRL_SIGN);
987
0
}
988
989
/*
990
 * OCSP helper: this is *not* a full OCSP check. It just checks that each CA
991
 * is valid. Additional checks must be made on the chain.
992
 */
993
static int check_purpose_ocsp_helper(const X509_PURPOSE *xp, const X509 *x,
994
    int non_leaf)
995
0
{
996
    /*
997
     * Must be a valid CA.  Should we really support the "I don't know" value
998
     * (2)?
999
     */
1000
0
    if (non_leaf)
1001
0
        return check_ca(x);
1002
    /* Leaf certificate is checked in OCSP_basic_verify() */
1003
0
    return 1;
1004
0
}
1005
1006
static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x,
1007
    int non_leaf)
1008
0
{
1009
0
    int i_ext;
1010
1011
    /*
1012
     * If non_leaf is true we must check if this is a valid CA certificate.
1013
     * The extra requirements by the CA/Browser Forum are not checked.
1014
     */
1015
0
    if (non_leaf)
1016
0
        return check_ca(x);
1017
1018
    /*
1019
     * Key Usage is checked according to RFC 5280 and
1020
     * Extended Key Usage attributes is checked according to RFC 3161.
1021
     * The extra (and somewhat conflicting) CA/Browser Forum
1022
     * Baseline Requirements for the Issuance and Management of
1023
     * Publicly‐Trusted Code Signing Certificates, Version 3.0.0,
1024
     * Section 7.1.2.3: Code signing and Timestamp Certificate are not checked.
1025
     */
1026
    /*
1027
     * Check the optional key usage field:
1028
     * if Key Usage is present, it must be one of digitalSignature
1029
     * and/or nonRepudiation (other values are not consistent and shall
1030
     * be rejected).
1031
     */
1032
0
    if ((x->ex_flags & EXFLAG_KUSAGE) != 0
1033
0
        && ((x->ex_kusage & ~(KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE)) || !(x->ex_kusage & (KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE))))
1034
0
        return 0;
1035
1036
    /* Only timestamp key usage is permitted and it's required. */
1037
0
    if ((x->ex_flags & EXFLAG_XKUSAGE) == 0 || x->ex_xkusage != XKU_TIMESTAMP)
1038
0
        return 0;
1039
1040
    /* Extended Key Usage MUST be critical */
1041
0
    i_ext = X509_get_ext_by_NID(x, NID_ext_key_usage, -1);
1042
0
    if (i_ext >= 0
1043
0
        && !X509_EXTENSION_get_critical(X509_get_ext((X509 *)x, i_ext)))
1044
0
        return 0;
1045
0
    return 1;
1046
0
}
1047
1048
static int check_purpose_code_sign(const X509_PURPOSE *xp, const X509 *x,
1049
    int non_leaf)
1050
0
{
1051
0
    int i_ext;
1052
1053
    /*
1054
     * If non_leaf is true we must check if this is a valid CA certificate.
1055
     * The extra requirements by the CA/Browser Forum are not checked.
1056
     */
1057
0
    if (non_leaf)
1058
0
        return check_ca(x);
1059
1060
    /*
1061
     * Check the key usage and extended key usage fields:
1062
     *
1063
     * Reference: CA/Browser Forum,
1064
     * Baseline Requirements for the Issuance and Management of
1065
     * Publicly‐Trusted Code Signing Certificates, Version 3.0.0,
1066
     * Section 7.1.2.3: Code signing and Timestamp Certificate
1067
     *
1068
     * Checking covers Key Usage and Extended Key Usage attributes.
1069
     * The certificatePolicies, cRLDistributionPoints (CDP), and
1070
     * authorityInformationAccess (AIA) extensions are so far not checked.
1071
     */
1072
    /* Key Usage */
1073
0
    if ((x->ex_flags & EXFLAG_KUSAGE) == 0)
1074
0
        return 0;
1075
0
    if ((x->ex_kusage & KU_DIGITAL_SIGNATURE) == 0)
1076
0
        return 0;
1077
0
    if ((x->ex_kusage & (KU_KEY_CERT_SIGN | KU_CRL_SIGN)) != 0)
1078
0
        return 0;
1079
1080
    /* Key Usage MUST be critical */
1081
0
    i_ext = X509_get_ext_by_NID(x, NID_key_usage, -1);
1082
0
    if (i_ext < 0)
1083
0
        return 0;
1084
0
    if (i_ext >= 0) {
1085
0
        const X509_EXTENSION *ext = X509_get_ext((X509 *)x, i_ext);
1086
0
        if (!X509_EXTENSION_get_critical(ext))
1087
0
            return 0;
1088
0
    }
1089
1090
    /* Extended Key Usage */
1091
0
    if ((x->ex_flags & EXFLAG_XKUSAGE) == 0)
1092
0
        return 0;
1093
0
    if ((x->ex_xkusage & XKU_CODE_SIGN) == 0)
1094
0
        return 0;
1095
0
    if ((x->ex_xkusage & (XKU_ANYEKU | XKU_SSL_SERVER)) != 0)
1096
0
        return 0;
1097
1098
0
    return 1;
1099
0
}
1100
1101
static int no_check_purpose(const X509_PURPOSE *xp, const X509 *x,
1102
    int non_leaf)
1103
0
{
1104
0
    return 1;
1105
0
}
1106
1107
static int check_name_constraints(const NAME_CONSTRAINTS *nc)
1108
0
{
1109
0
    GENERAL_SUBTREE *sub;
1110
0
    int ret = 1;
1111
1112
0
    if (nc == NULL)
1113
0
        goto done;
1114
1115
0
    for (int i = 0; nc->permittedSubtrees != NULL
1116
0
        && i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees);
1117
0
        i++) {
1118
0
        sub = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i);
1119
0
        if (sub->base->type == GEN_OTHERNAME
1120
0
            && OBJ_obj2nid(sub->base->d.otherName->type_id)
1121
0
                == NID_id_on_SmtpUTF8Mailbox) {
1122
            /* RFC 9598 prohibits GEN_OTHERNAME email constraints */
1123
0
            ERR_raise(ERR_LIB_X509V3, X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE);
1124
0
            ret = 0;
1125
0
            goto done;
1126
0
        }
1127
0
    }
1128
0
    for (int i = 0; nc->excludedSubtrees != NULL
1129
0
        && i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees);
1130
0
        i++) {
1131
0
        sub = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i);
1132
0
        if (sub->base->type == GEN_OTHERNAME
1133
0
            && OBJ_obj2nid(sub->base->d.otherName->type_id)
1134
0
                == NID_id_on_SmtpUTF8Mailbox) {
1135
            /* RFC 9598 prohibits GEN_OTHERNAME email constraints */
1136
0
            ERR_raise(ERR_LIB_X509V3, X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE);
1137
0
            ret = 0;
1138
0
            goto done;
1139
0
        }
1140
0
    }
1141
1142
0
done:
1143
0
    return ret;
1144
0
}
1145
1146
/*-
1147
 * Various checks to see if one certificate potentially issued the second.
1148
 * This can be used to prune a set of possible issuer certificates which
1149
 * have been looked up using some simple method such as by subject name.
1150
 * These are:
1151
 * 1. issuer_name(subject) == subject_name(issuer)
1152
 * 2. If akid(subject) exists, it matches the respective issuer fields.
1153
 * 3. subject signature algorithm == issuer public key algorithm
1154
 * 4. If key_usage(issuer) exists, it allows for signing subject.
1155
 * Note that this does not include actually checking the signature.
1156
 * Returns 0 for OK, or positive for reason for mismatch
1157
 * where reason codes match those for X509_verify_cert().
1158
 */
1159
int X509_check_issued(const X509 *issuer, const X509 *subject)
1160
0
{
1161
0
    int ret;
1162
1163
0
    if ((ret = ossl_x509_likely_issued(issuer, subject)) != X509_V_OK)
1164
0
        return ret;
1165
0
    return ossl_x509_signing_allowed(issuer, subject);
1166
0
}
1167
1168
/*
1169
 * Do the checks 1., 2., and 3. as described above for X509_check_issued().
1170
 * These are very similar to a section of ossl_x509v3_cache_extensions().
1171
 * If |issuer| equals |subject| (such that self-signature should be checked),
1172
 * use the EXFLAG_SS result of ossl_x509v3_cache_extensions().
1173
 */
1174
int ossl_x509_likely_issued(const X509 *issuer, const X509 *subject)
1175
0
{
1176
0
    int ret;
1177
1178
0
    if (X509_NAME_cmp(X509_get_subject_name(issuer),
1179
0
            X509_get_issuer_name(subject))
1180
0
        != 0)
1181
0
        return X509_V_ERR_SUBJECT_ISSUER_MISMATCH;
1182
1183
    /* set issuer->skid, subject->akid, and subject->ex_flags */
1184
0
    if (!ossl_x509v3_cache_extensions(issuer)
1185
0
        || !ossl_x509v3_cache_extensions(subject))
1186
0
        return X509_V_ERR_UNSPECIFIED;
1187
1188
0
    if (issuer == subject
1189
0
        || (X509_NAME_cmp(X509_get_issuer_name(issuer), X509_get_issuer_name(subject)) == 0
1190
0
            && ASN1_INTEGER_cmp(X509_get0_serialNumber(issuer), X509_get0_serialNumber(subject)) == 0))
1191
        /*
1192
         * At this point, we can assume that issuer and subject
1193
         * are semantically the same cert because they are identical
1194
         * or at least have the same issuer and serial number,
1195
         * which (for any sane cert issuer) implies equality of the two certs.
1196
         * In this case, for consistency with chain building and validation,
1197
         * we make our issuance judgment depend on the presence of EXFLAG_SS.
1198
         * This is used for corrected chain building in the corner case of
1199
         * a self-issued but not actually self-signed trust anchor cert
1200
         * without subject and issuer key identifiers (i.e., no SKID and AKID).
1201
         */
1202
0
        return (issuer->ex_flags & EXFLAG_SS) != 0
1203
0
            ? X509_V_OK
1204
0
            : X509_V_ERR_CERT_SIGNATURE_FAILURE;
1205
1206
0
    ret = X509_check_akid(issuer, subject->akid);
1207
0
    if (ret != X509_V_OK)
1208
0
        return ret;
1209
1210
    /* Check if the subject signature alg matches the issuer's PUBKEY alg */
1211
0
    return check_sig_alg_match(X509_get0_pubkey(issuer), subject);
1212
0
}
1213
1214
/*-
1215
 * Check if certificate I<issuer> is allowed to issue certificate I<subject>
1216
 * according to the B<keyUsage> field of I<issuer> if present
1217
 * depending on any proxyCertInfo extension of I<subject>.
1218
 * Returns 0 for OK, or positive for reason for rejection
1219
 * where reason codes match those for X509_verify_cert().
1220
 */
1221
int ossl_x509_signing_allowed(const X509 *issuer, const X509 *subject)
1222
0
{
1223
0
    if ((subject->ex_flags & EXFLAG_PROXY) != 0) {
1224
0
        if (ku_reject(issuer, KU_DIGITAL_SIGNATURE))
1225
0
            return X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
1226
0
    } else if (ku_reject(issuer, KU_KEY_CERT_SIGN)) {
1227
0
        return X509_V_ERR_KEYUSAGE_NO_CERTSIGN;
1228
0
    }
1229
0
    return X509_V_OK;
1230
0
}
1231
1232
/*
1233
 * check if all sub-fields of the authority key identifier information akid,
1234
 * as far as present, match the respective subjectKeyIdentifier extension (if
1235
 * present in issuer), serialNumber field, and issuer fields of issuer.
1236
 * returns X509_V_OK also if akid is NULL because this means no restriction.
1237
 */
1238
int X509_check_akid(const X509 *issuer, const AUTHORITY_KEYID *akid)
1239
0
{
1240
0
    if (akid == NULL)
1241
0
        return X509_V_OK;
1242
1243
    /* Check key ids (if present) */
1244
0
    if (akid->keyid && issuer->skid && ASN1_OCTET_STRING_cmp(akid->keyid, issuer->skid))
1245
0
        return X509_V_ERR_AKID_SKID_MISMATCH;
1246
    /* Check serial number */
1247
0
    if (akid->serial && ASN1_INTEGER_cmp(X509_get0_serialNumber(issuer), akid->serial))
1248
0
        return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
1249
    /* Check issuer name */
1250
0
    if (akid->issuer) {
1251
        /*
1252
         * Ugh, for some peculiar reason AKID includes SEQUENCE OF
1253
         * GeneralName. So look for a DirName. There may be more than one but
1254
         * we only take any notice of the first.
1255
         */
1256
0
        GENERAL_NAMES *gens = akid->issuer;
1257
0
        GENERAL_NAME *gen;
1258
0
        X509_NAME *nm = NULL;
1259
0
        int i;
1260
1261
0
        for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1262
0
            gen = sk_GENERAL_NAME_value(gens, i);
1263
0
            if (gen->type == GEN_DIRNAME) {
1264
0
                nm = gen->d.dirn;
1265
0
                break;
1266
0
            }
1267
0
        }
1268
0
        if (nm != NULL && X509_NAME_cmp(nm, X509_get_issuer_name(issuer)) != 0)
1269
0
            return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
1270
0
    }
1271
0
    return X509_V_OK;
1272
0
}
1273
1274
uint32_t X509_get_extension_flags(const X509 *x)
1275
0
{
1276
    /* Call for side-effect of computing hash and caching extensions */
1277
0
    X509_check_purpose(x, -1, 0);
1278
0
    return x->ex_flags;
1279
0
}
1280
1281
uint32_t X509_get_key_usage(const X509 *x)
1282
0
{
1283
    /* Call for side-effect of computing hash and caching extensions */
1284
0
    if (X509_check_purpose(x, -1, 0) != 1)
1285
0
        return 0;
1286
0
    return (x->ex_flags & EXFLAG_KUSAGE) != 0 ? x->ex_kusage : UINT32_MAX;
1287
0
}
1288
1289
uint32_t X509_get_extended_key_usage(const X509 *x)
1290
0
{
1291
    /* Call for side-effect of computing hash and caching extensions */
1292
0
    if (X509_check_purpose(x, -1, 0) != 1)
1293
0
        return 0;
1294
0
    return (x->ex_flags & EXFLAG_XKUSAGE) != 0 ? x->ex_xkusage : UINT32_MAX;
1295
0
}
1296
1297
const ASN1_OCTET_STRING *X509_get0_subject_key_id(const X509 *x)
1298
0
{
1299
    /* Call for side-effect of computing hash and caching extensions */
1300
0
    if (X509_check_purpose(x, -1, 0) != 1)
1301
0
        return NULL;
1302
0
    return x->skid;
1303
0
}
1304
1305
const ASN1_OCTET_STRING *X509_get0_authority_key_id(const X509 *x)
1306
0
{
1307
    /* Call for side-effect of computing hash and caching extensions */
1308
0
    if (X509_check_purpose(x, -1, 0) != 1)
1309
0
        return NULL;
1310
0
    return (x->akid != NULL ? x->akid->keyid : NULL);
1311
0
}
1312
1313
const GENERAL_NAMES *X509_get0_authority_issuer(const X509 *x)
1314
0
{
1315
    /* Call for side-effect of computing hash and caching extensions */
1316
0
    if (X509_check_purpose(x, -1, 0) != 1)
1317
0
        return NULL;
1318
0
    return (x->akid != NULL ? x->akid->issuer : NULL);
1319
0
}
1320
1321
const ASN1_INTEGER *X509_get0_authority_serial(const X509 *x)
1322
0
{
1323
    /* Call for side-effect of computing hash and caching extensions */
1324
0
    if (X509_check_purpose(x, -1, 0) != 1)
1325
0
        return NULL;
1326
0
    return (x->akid != NULL ? x->akid->serial : NULL);
1327
0
}
1328
1329
long X509_get_pathlen(const X509 *x)
1330
0
{
1331
    /* Called for side effect of caching extensions */
1332
0
    if (X509_check_purpose(x, -1, 0) != 1
1333
0
        || (x->ex_flags & EXFLAG_BCONS) == 0)
1334
0
        return -1;
1335
0
    return x->ex_pathlen;
1336
0
}
1337
1338
long X509_get_proxy_pathlen(const X509 *x)
1339
0
{
1340
    /* Called for side effect of caching extensions */
1341
0
    if (X509_check_purpose(x, -1, 0) != 1
1342
0
        || (x->ex_flags & EXFLAG_PROXY) == 0)
1343
0
        return -1;
1344
0
    return x->ex_pcpathlen;
1345
0
}