Coverage Report

Created: 2026-09-13 06:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/crypto/x509/x509_vfy.c
Line
Count
Source
1
/*
2
 * Copyright 1995-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
#define OPENSSL_SUPPRESS_DEPRECATED
11
#include "internal/deprecated.h"
12
13
#include <stdio.h>
14
#include <time.h>
15
#include <errno.h>
16
#include <limits.h>
17
18
#include "crypto/ctype.h"
19
#include "internal/cryptlib.h"
20
#include <openssl/crypto.h>
21
#include <openssl/buffer.h>
22
#include <openssl/evp.h>
23
#include <openssl/asn1.h>
24
#include <openssl/x509.h>
25
#include <openssl/x509v3.h>
26
#include <openssl/ocsp.h>
27
#include <openssl/objects.h>
28
#include <openssl/posix_time.h>
29
#include <openssl/core_names.h>
30
#include "internal/dane.h"
31
#include "crypto/x509.h"
32
#include "x509_local.h"
33
34
/* CRL score values */
35
36
0
#define CRL_SCORE_NOCRITICAL 0x100 /* No unhandled critical extensions */
37
0
#define CRL_SCORE_SCOPE 0x080 /* certificate is within CRL scope */
38
0
#define CRL_SCORE_TIME 0x040 /* CRL times valid */
39
0
#define CRL_SCORE_ISSUER_NAME 0x020 /* Issuer name matches certificate */
40
#define CRL_SCORE_VALID /* If this score or above CRL is probably valid */ \
41
0
    (CRL_SCORE_NOCRITICAL | CRL_SCORE_TIME | CRL_SCORE_SCOPE)
42
0
#define CRL_SCORE_ISSUER_CERT 0x018 /* CRL issuer is certificate issuer */
43
0
#define CRL_SCORE_SAME_PATH 0x008 /* CRL issuer is on certificate path */
44
0
#define CRL_SCORE_AKID 0x004 /* CRL issuer matches CRL AKID */
45
0
#define CRL_SCORE_TIME_DELTA 0x002 /* Have a delta CRL with valid times */
46
47
static int x509_verify_x509(X509_STORE_CTX *ctx);
48
static int x509_verify_rpk(X509_STORE_CTX *ctx);
49
static int build_chain(X509_STORE_CTX *ctx);
50
static int verify_chain(X509_STORE_CTX *ctx);
51
static int verify_rpk(X509_STORE_CTX *ctx);
52
static int dane_verify(X509_STORE_CTX *ctx);
53
static int dane_verify_rpk(X509_STORE_CTX *ctx);
54
static int null_callback(int ok, X509_STORE_CTX *e);
55
static int check_issued(X509_STORE_CTX *ctx, const X509 *x, const X509 *issuer);
56
static int check_extensions(X509_STORE_CTX *ctx);
57
static int check_name_constraints(X509_STORE_CTX *ctx);
58
static int check_id(X509_STORE_CTX *ctx);
59
static int check_trust(X509_STORE_CTX *ctx, int num_untrusted);
60
static int check_revocation(X509_STORE_CTX *ctx);
61
static int revocation_check_end(X509_STORE_CTX *ctx, int check_all);
62
#ifndef OPENSSL_NO_OCSP
63
static int check_cert_ocsp_resp(X509_STORE_CTX *ctx);
64
#endif
65
static int check_cert_crl(X509_STORE_CTX *ctx);
66
static int check_policy(X509_STORE_CTX *ctx);
67
static int check_dane_issuer(X509_STORE_CTX *ctx, int depth);
68
static int check_cert_key_level(X509_STORE_CTX *ctx, X509 *cert);
69
static int check_key_level(X509_STORE_CTX *ctx, EVP_PKEY *pkey);
70
static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert);
71
static int check_curve(X509 *cert);
72
73
static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
74
    unsigned int *preasons, X509_CRL *crl, X509 *x);
75
static int get_crl_delta(X509_STORE_CTX *ctx,
76
    X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x);
77
static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl,
78
    int *pcrl_score, X509_CRL *base,
79
    STACK_OF(X509_CRL) *crls);
80
static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
81
    int *pcrl_score);
82
static int matching_crl_issuer_and_akid(const X509_CRL *crl,
83
    const X509 *issuer, const X509_NAME *crl_issuer_name);
84
static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
85
    unsigned int *preasons);
86
static int check_crl_path(X509_STORE_CTX *ctx, X509 *x);
87
static int check_crl_chain(X509_STORE_CTX *ctx,
88
    STACK_OF(X509) *cert_path,
89
    STACK_OF(X509) *crl_path);
90
91
static int internal_verify(X509_STORE_CTX *ctx);
92
93
static int null_callback(int ok, X509_STORE_CTX *e)
94
0
{
95
0
    return ok;
96
0
}
97
98
/*-
99
 * Return 1 if given cert is considered self-signed, 0 if not, or -1 on error.
100
 * This actually verifies self-signedness only if requested.
101
 * It calls ossl_x509v3_cache_extensions()
102
 * to match issuer and subject names (i.e., the cert being self-issued) and any
103
 * present authority key identifier to match the subject key identifier, etc.
104
 */
105
int X509_self_signed(const X509 *cert, int verify_signature)
106
0
{
107
0
    EVP_PKEY *pkey;
108
109
0
    if ((pkey = X509_get0_pubkey(cert)) == NULL) { /* handles cert == NULL */
110
0
        ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
111
0
        return -1;
112
0
    }
113
0
    if (!ossl_x509v3_cache_extensions((X509 *)cert))
114
0
        return -1;
115
0
    if ((cert->ex_flags & EXFLAG_SS) == 0)
116
0
        return 0;
117
0
    if (!verify_signature)
118
0
        return 1;
119
0
    return X509_verify(cert, pkey);
120
0
}
121
122
/*
123
 * Given a certificate, try and find an exact match in the store.
124
 * Returns 1 on success, 0 on not found, -1 on internal error.
125
 */
126
static int lookup_cert_match(X509 **result, X509_STORE_CTX *ctx, X509 *x)
127
0
{
128
0
    STACK_OF(X509) *certs;
129
0
    X509 *xtmp = NULL;
130
0
    int i, ret;
131
132
0
    *result = NULL;
133
    /* Lookup all certs with matching subject name */
134
0
    ERR_set_mark();
135
0
    certs = ctx->lookup_certs(ctx, X509_get_subject_name(x));
136
0
    ERR_pop_to_mark();
137
0
    if (certs == NULL)
138
0
        return -1;
139
140
    /* Look for exact match */
141
0
    for (i = 0; i < sk_X509_num(certs); i++) {
142
0
        xtmp = sk_X509_value(certs, i);
143
0
        if (X509_cmp(xtmp, x) == 0)
144
0
            break;
145
0
        xtmp = NULL;
146
0
    }
147
0
    ret = xtmp != NULL;
148
0
    if (ret) {
149
0
        if (!X509_up_ref(xtmp))
150
0
            ret = -1;
151
0
        else
152
0
            *result = xtmp;
153
0
    }
154
0
    OSSL_STACK_OF_X509_free(certs);
155
0
    return ret;
156
0
}
157
158
/*-
159
 * Inform the verify callback of an error.
160
 * The error code is set to |err| if |err| is not X509_V_OK, else
161
 * |ctx->error| is left unchanged (under the assumption it is set elsewhere).
162
 * The error depth is |depth| if >= 0, else it defaults to |ctx->error_depth|.
163
 * The error cert is |x| if not NULL, else the cert in |ctx->chain| at |depth|.
164
 *
165
 * Returns 0 to abort verification with an error, non-zero to continue.
166
 */
167
static int verify_cb_cert(X509_STORE_CTX *ctx, const X509 *x, int depth, int err)
168
0
{
169
0
    if (depth < 0)
170
0
        depth = ctx->error_depth;
171
0
    else
172
0
        ctx->error_depth = depth;
173
0
    ctx->current_cert = x != NULL ? (X509 *)x : sk_X509_value(ctx->chain, depth);
174
0
    if (err != X509_V_OK)
175
0
        ctx->error = err;
176
0
    return ctx->verify_cb(0, ctx);
177
0
}
178
179
#define CB_FAIL_IF(cond, ctx, cert, depth, err)               \
180
0
    if ((cond) && verify_cb_cert(ctx, cert, depth, err) == 0) \
181
0
    return 0
182
183
/*-
184
 * Inform the verify callback of an error, CRL-specific variant.  Here, the
185
 * error depth and certificate are already set, we just specify the error
186
 * number.
187
 *
188
 * Returns 0 to abort verification with an error, non-zero to continue.
189
 */
190
static int verify_cb_crl(X509_STORE_CTX *ctx, int err)
191
0
{
192
0
    ctx->error = err;
193
0
    return ctx->verify_cb(0, ctx);
194
0
}
195
196
#ifndef OPENSSL_NO_OCSP
197
/*
198
 * Inform the verify callback of an error, OCSP-specific variant.
199
 * It is called also on OCSP response errors, if the
200
 * X509_V_FLAG_OCSP_RESP_CHECK flag is set.
201
 * Here, the error depth and certificate are already set, we just specify
202
 * the error number.
203
 *
204
 * Returns 0 to abort verification with an error, non-zero to continue.
205
 */
206
static int verify_cb_ocsp(X509_STORE_CTX *ctx, int err)
207
0
{
208
0
    ctx->error = err;
209
0
    return ctx->verify_cb(0, ctx);
210
0
}
211
#endif
212
213
/* Sadly, returns 0 also on internal error in ctx->verify_cb(). */
214
static int check_auth_level(X509_STORE_CTX *ctx)
215
0
{
216
0
    int i;
217
0
    int num = sk_X509_num(ctx->chain);
218
219
0
    if (ctx->param->auth_level <= 0)
220
0
        return 1;
221
222
0
    for (i = 0; i < num; ++i) {
223
0
        X509 *cert = sk_X509_value(ctx->chain, i);
224
225
        /*
226
         * We've already checked the security of the leaf key, so here we only
227
         * check the security of issuer keys.
228
         */
229
0
        CB_FAIL_IF(i > 0 && !check_cert_key_level(ctx, cert),
230
0
            ctx, cert, i, X509_V_ERR_CA_KEY_TOO_SMALL);
231
        /*
232
         * We also check the signature algorithm security of all certificates
233
         * except those of the trust anchor at index num-1.
234
         */
235
0
        CB_FAIL_IF(i < num - 1 && !check_sig_level(ctx, cert),
236
0
            ctx, cert, i, X509_V_ERR_CA_MD_TOO_WEAK);
237
0
    }
238
0
    return 1;
239
0
}
240
241
/*-
242
 * Returns -1 on internal error.
243
 * Sadly, returns 0 also on internal error in ctx->verify_cb().
244
 */
245
static int verify_rpk(X509_STORE_CTX *ctx)
246
0
{
247
    /* Not much to verify on a RPK */
248
0
    if (ctx->verify != NULL)
249
0
        return ctx->verify(ctx);
250
251
0
    return !!ctx->verify_cb(ctx->error == X509_V_OK, ctx);
252
0
}
253
254
/*-
255
 * Returns -1 on internal error.
256
 * Sadly, returns 0 also on internal error in ctx->verify_cb().
257
 */
258
static int verify_chain(X509_STORE_CTX *ctx)
259
0
{
260
0
    int err;
261
0
    int ok;
262
263
0
    if ((ok = build_chain(ctx)) <= 0
264
0
        || (ok = check_extensions(ctx)) <= 0
265
0
        || (ok = check_auth_level(ctx)) <= 0
266
0
        || (ok = check_id(ctx)) <= 0
267
0
        || (ok = X509_get_pubkey_parameters(NULL, ctx->chain) ? 1 : -1) <= 0
268
0
        || (ok = ctx->check_revocation(ctx)) <= 0)
269
0
        return ok;
270
271
0
    err = X509_chain_check_suiteb(&ctx->error_depth, NULL, ctx->chain,
272
0
        ctx->param->flags);
273
0
    CB_FAIL_IF(err != X509_V_OK, ctx, NULL, ctx->error_depth, err);
274
275
    /* Verify chain signatures and expiration times */
276
0
    ok = ctx->verify != NULL ? ctx->verify(ctx) : internal_verify(ctx);
277
0
    if (ok <= 0)
278
0
        return ok;
279
280
0
    if ((ok = check_name_constraints(ctx)) <= 0)
281
0
        return ok;
282
283
0
#ifndef OPENSSL_NO_RFC3779
284
    /* RFC 3779 path validation, now that CRL check has been done */
285
0
    if ((ok = X509v3_asid_validate_path(ctx)) <= 0)
286
0
        return ok;
287
0
    if ((ok = X509v3_addr_validate_path(ctx)) <= 0)
288
0
        return ok;
289
0
#endif
290
291
    /* If we get this far evaluate policies */
292
0
    if ((ctx->param->flags & X509_V_FLAG_POLICY_CHECK) != 0)
293
0
        ok = ctx->check_policy(ctx);
294
0
    return ok;
295
0
}
296
297
int X509_STORE_CTX_verify(X509_STORE_CTX *ctx)
298
0
{
299
0
    if (ctx == NULL) {
300
0
        ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
301
0
        return -1;
302
0
    }
303
0
    if (ctx->rpk != NULL)
304
0
        return x509_verify_rpk(ctx);
305
0
    if (ctx->cert == NULL && sk_X509_num(ctx->untrusted) >= 1)
306
0
        ctx->cert = sk_X509_value(ctx->untrusted, 0);
307
0
    return x509_verify_x509(ctx);
308
0
}
309
310
int X509_verify_cert(X509_STORE_CTX *ctx)
311
0
{
312
0
    if (ctx == NULL) {
313
0
        ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
314
0
        return -1;
315
0
    }
316
0
    return (ctx->rpk != NULL) ? x509_verify_rpk(ctx) : x509_verify_x509(ctx);
317
0
}
318
319
/*-
320
 * Returns -1 on internal error.
321
 * Sadly, returns 0 also on internal error in ctx->verify_cb().
322
 */
323
static int x509_verify_rpk(X509_STORE_CTX *ctx)
324
0
{
325
0
    int ret;
326
327
    /* If the peer's public key is too weak, we can stop early. */
328
0
    if (!check_key_level(ctx, ctx->rpk)
329
0
        && verify_cb_cert(ctx, NULL, 0, X509_V_ERR_EE_KEY_TOO_SMALL) == 0)
330
0
        return 0;
331
332
    /* Barring any data to verify the RPK, simply report it as untrusted */
333
0
    ctx->error = X509_V_ERR_RPK_UNTRUSTED;
334
335
0
    ret = DANETLS_ENABLED(ctx->dane) ? dane_verify_rpk(ctx) : verify_rpk(ctx);
336
337
    /*
338
     * Safety-net.  If we are returning an error, we must also set ctx->error,
339
     * so that the chain is not considered verified should the error be ignored
340
     * (e.g. TLS with SSL_VERIFY_NONE).
341
     */
342
0
    if (ret <= 0 && ctx->error == X509_V_OK)
343
0
        ctx->error = X509_V_ERR_UNSPECIFIED;
344
0
    return ret;
345
0
}
346
347
/*-
348
 * Returns -1 on internal error.
349
 * Sadly, returns 0 also on internal error in ctx->verify_cb().
350
 */
351
static int x509_verify_x509(X509_STORE_CTX *ctx)
352
0
{
353
0
    int ret;
354
355
0
    if (ctx->cert == NULL) {
356
0
        ERR_raise(ERR_LIB_X509, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
357
0
        ctx->error = X509_V_ERR_INVALID_CALL;
358
0
        return -1;
359
0
    }
360
361
0
    if (ctx->chain != NULL) {
362
        /*
363
         * This X509_STORE_CTX has already been used to verify a cert. We
364
         * cannot do another one.
365
         */
366
0
        ERR_raise(ERR_LIB_X509, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
367
0
        ctx->error = X509_V_ERR_INVALID_CALL;
368
0
        return -1;
369
0
    }
370
371
0
    if (!ossl_x509_add_cert_new(&ctx->chain, ctx->cert, X509_ADD_FLAG_UP_REF)) {
372
0
        ctx->error = X509_V_ERR_OUT_OF_MEM;
373
0
        return -1;
374
0
    }
375
0
    ctx->num_untrusted = 1;
376
377
    /* If the peer's public key is too weak, we can stop early. */
378
0
    CB_FAIL_IF(!check_cert_key_level(ctx, ctx->cert),
379
0
        ctx, ctx->cert, 0, X509_V_ERR_EE_KEY_TOO_SMALL);
380
381
0
    ret = DANETLS_ENABLED(ctx->dane) ? dane_verify(ctx) : verify_chain(ctx);
382
383
    /*
384
     * Safety-net.  If we are returning an error, we must also set ctx->error,
385
     * so that the chain is not considered verified should the error be ignored
386
     * (e.g. TLS with SSL_VERIFY_NONE).
387
     */
388
0
    if (ret <= 0 && ctx->error == X509_V_OK)
389
0
        ctx->error = X509_V_ERR_UNSPECIFIED;
390
0
    return ret;
391
0
}
392
393
static int sk_X509_contains(STACK_OF(X509) *sk, X509 *cert)
394
0
{
395
0
    int i, n = sk_X509_num(sk);
396
397
0
    for (i = 0; i < n; i++)
398
0
        if (X509_cmp(sk_X509_value(sk, i), cert) == 0)
399
0
            return 1;
400
0
    return 0;
401
0
}
402
403
/*-
404
 * Find in |sk| an issuer cert of cert |x| accepted by |ctx->check_issued|.
405
 * If no_dup, the issuer must not yet be in |ctx->chain|, yet allowing the
406
 *     exception that |x| is self-issued and |ctx->chain| has just one element.
407
 * Prefer the first match with suitable validity period or latest expiration.
408
 */
409
/*
410
 * Note: so far, we do not check during chain building
411
 * whether any key usage extension stands against a candidate issuer cert.
412
 * Likely it would be good if build_chain() sets |check_signing_allowed|.
413
 * Yet if |sk| is a list of trusted certs, as with X509_STORE_CTX_set0_trusted_stack(),
414
 * better not set |check_signing_allowed|.
415
 * Maybe not touch X509_STORE_CTX_get1_issuer(), for API backward compatibility.
416
 */
417
static X509 *get0_best_issuer_sk(X509_STORE_CTX *ctx, int check_signing_allowed,
418
    int no_dup, STACK_OF(X509) *sk, const X509 *x)
419
0
{
420
0
    int i;
421
0
    X509 *candidate, *issuer = NULL;
422
423
0
    for (i = 0; i < sk_X509_num(sk); i++) {
424
0
        candidate = sk_X509_value(sk, i);
425
0
        if (no_dup
426
0
            && !((x->ex_flags & EXFLAG_SI) != 0 && sk_X509_num(ctx->chain) == 1)
427
0
            && sk_X509_contains(ctx->chain, candidate))
428
0
            continue;
429
0
        if (ctx->check_issued(ctx, x, candidate)) {
430
0
            if (check_signing_allowed
431
                /* yet better not check key usage for trust anchors */
432
0
                && ossl_x509_signing_allowed(candidate, x) != X509_V_OK)
433
0
                continue;
434
0
            if (ossl_x509_check_cert_time(ctx, candidate, -1))
435
0
                return candidate;
436
            /*
437
             * Leave in *issuer the first match that has the latest expiration
438
             * date so we return nearest match if no certificate time is OK.
439
             */
440
0
            if (issuer == NULL
441
0
                || ASN1_TIME_compare(X509_get0_notAfter(candidate),
442
0
                       X509_get0_notAfter(issuer))
443
0
                    > 0)
444
0
                issuer = candidate;
445
0
        }
446
0
    }
447
0
    return issuer;
448
0
}
449
450
/*-
451
 * Try to get issuer cert from |ctx->store| accepted by |ctx->check_issued|.
452
 * Prefer the first match with suitable validity period or latest expiration.
453
 *
454
 * Return values are:
455
 *  1 lookup successful.
456
 *  0 certificate not found.
457
 * -1 some other error.
458
 */
459
int X509_STORE_CTX_get1_issuer(X509 **issuer, X509_STORE_CTX *ctx, const X509 *x)
460
0
{
461
0
    const X509_NAME *xn = X509_get_issuer_name(x);
462
0
    X509_OBJECT *obj = X509_OBJECT_new();
463
0
    STACK_OF(X509) *certs;
464
0
    int ret;
465
466
0
    *issuer = NULL;
467
0
    if (obj == NULL)
468
0
        return -1;
469
0
    ret = ossl_x509_store_ctx_get_by_subject(ctx, X509_LU_X509, xn, obj);
470
0
    if (ret != 1)
471
0
        goto end;
472
473
    /* quick happy path: certificate matches and is currently valid */
474
0
    if (ctx->check_issued(ctx, x, obj->data.x509)) {
475
0
        if (ossl_x509_check_cert_time(ctx, obj->data.x509, -1)) {
476
0
            *issuer = obj->data.x509;
477
            /* |*issuer| has taken over the cert reference from |obj| */
478
0
            obj->type = X509_LU_NONE;
479
0
            goto end;
480
0
        }
481
0
    }
482
483
0
    ret = -1;
484
0
    if ((certs = X509_STORE_CTX_get1_certs(ctx, xn)) == NULL)
485
0
        goto end;
486
0
    *issuer = get0_best_issuer_sk(ctx, 0, 0 /* allow duplicates */, certs, x);
487
0
    ret = 0;
488
0
    if (*issuer != NULL)
489
0
        ret = X509_up_ref(*issuer) ? 1 : -1;
490
0
    OSSL_STACK_OF_X509_free(certs);
491
0
end:
492
0
    X509_OBJECT_free(obj);
493
0
    return ret;
494
0
}
495
496
/* Check that the given certificate |x| is issued by the certificate |issuer| */
497
static int check_issued(ossl_unused X509_STORE_CTX *ctx, const X509 *x, const X509 *issuer)
498
0
{
499
0
    int err = ossl_x509_likely_issued(issuer, x);
500
501
0
    if (err == X509_V_OK)
502
0
        return 1;
503
    /*
504
     * SUBJECT_ISSUER_MISMATCH just means 'x' is clearly not issued by 'issuer'.
505
     * Every other error code likely indicates a real error.
506
     */
507
0
    return 0;
508
0
}
509
510
/*-
511
 * Alternative get_issuer method: look up from a STACK_OF(X509) in other_ctx.
512
 * Returns -1 on internal error.
513
 */
514
static int get1_best_issuer_other_sk(X509 **issuer, X509_STORE_CTX *ctx, const X509 *x)
515
0
{
516
0
    *issuer = get0_best_issuer_sk(ctx, 0, 1 /* no_dup */, ctx->other_ctx, x);
517
0
    if (*issuer == NULL)
518
0
        return 0;
519
0
    return X509_up_ref(*issuer) ? 1 : -1;
520
0
}
521
522
/*-
523
 * Alternative lookup method: look from a STACK stored in other_ctx.
524
 * Returns NULL on internal/fatal error, empty stack if not found.
525
 */
526
static STACK_OF(X509) *lookup_certs_sk(const X509_STORE_CTX *ctx, const X509_NAME *nm)
527
0
{
528
0
    STACK_OF(X509) *sk = sk_X509_new_null();
529
0
    X509 *x;
530
0
    int i;
531
532
0
    if (sk == NULL)
533
0
        return NULL;
534
0
    for (i = 0; i < sk_X509_num(ctx->other_ctx); i++) {
535
0
        x = sk_X509_value(ctx->other_ctx, i);
536
0
        if (X509_NAME_cmp(nm, X509_get_subject_name(x)) == 0) {
537
0
            if (!X509_add_cert(sk, x, X509_ADD_FLAG_UP_REF)) {
538
0
                OSSL_STACK_OF_X509_free(sk);
539
0
                return NULL;
540
0
            }
541
0
        }
542
0
    }
543
0
    return sk;
544
0
}
545
546
/*
547
 * Check EE or CA certificate purpose.  For trusted certificates explicit local
548
 * auxiliary trust can be used to override EKU-restrictions.
549
 * Sadly, returns 0 also on internal error in ctx->verify_cb().
550
 */
551
static int check_purpose(X509_STORE_CTX *ctx, X509 *x, int purpose, int depth,
552
    int must_be_ca)
553
0
{
554
0
    int tr_ok = X509_TRUST_UNTRUSTED;
555
556
    /*
557
     * For trusted certificates we want to see whether any auxiliary trust
558
     * settings trump the purpose constraints.
559
     *
560
     * This is complicated by the fact that the trust ordinals in
561
     * ctx->param->trust are entirely independent of the purpose ordinals in
562
     * ctx->param->purpose!
563
     *
564
     * What connects them is their mutual initialization via calls from
565
     * X509_STORE_CTX_set_default() into X509_VERIFY_PARAM_lookup() which sets
566
     * related values of both param->trust and param->purpose.  It is however
567
     * typically possible to infer associated trust values from a purpose value
568
     * via the X509_PURPOSE API.
569
     *
570
     * Therefore, we can only check for trust overrides when the purpose we're
571
     * checking is the same as ctx->param->purpose and ctx->param->trust is
572
     * also set.
573
     */
574
0
    if (depth >= ctx->num_untrusted && purpose == ctx->param->purpose)
575
0
        tr_ok = X509_check_trust(x, ctx->param->trust, X509_TRUST_NO_SS_COMPAT);
576
577
0
    switch (tr_ok) {
578
0
    case X509_TRUST_TRUSTED:
579
0
        return 1;
580
0
    case X509_TRUST_REJECTED:
581
0
        break;
582
0
    default: /* can only be X509_TRUST_UNTRUSTED */
583
0
        switch (X509_check_purpose(x, purpose, must_be_ca > 0)) {
584
0
        case 1:
585
0
            return 1;
586
0
        case 0:
587
0
            break;
588
0
        default:
589
0
            if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) == 0)
590
0
                return 1;
591
0
        }
592
0
        break;
593
0
    }
594
595
0
    return verify_cb_cert(ctx, x, depth, X509_V_ERR_INVALID_PURPOSE);
596
0
}
597
598
/*-
599
 * Check extensions of a cert chain for consistency with the supplied purpose.
600
 * Sadly, returns 0 also on internal error in ctx->verify_cb().
601
 */
602
static int check_extensions(X509_STORE_CTX *ctx)
603
0
{
604
0
    int i, must_be_ca, plen = 0;
605
0
    X509 *x;
606
0
    int ret, proxy_path_length = 0;
607
0
    int purpose, allow_proxy_certs, num = sk_X509_num(ctx->chain);
608
609
    /*-
610
     *  must_be_ca can have 1 of 3 values:
611
     * -1: we accept both CA and non-CA certificates, to allow direct
612
     *     use of self-signed certificates (which are marked as CA).
613
     * 0:  we only accept non-CA certificates.  This is currently not
614
     *     used, but the possibility is present for future extensions.
615
     * 1:  we only accept CA certificates.  This is currently used for
616
     *     all certificates in the chain except the leaf certificate.
617
     */
618
0
    must_be_ca = -1;
619
620
    /* CRL path validation */
621
0
    if (ctx->parent != NULL) {
622
0
        allow_proxy_certs = 0;
623
0
        purpose = X509_PURPOSE_CRL_SIGN;
624
0
    } else {
625
0
        allow_proxy_certs = (ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS) != 0;
626
0
        purpose = ctx->param->purpose;
627
0
    }
628
629
0
    for (i = 0; i < num; i++) {
630
0
        x = sk_X509_value(ctx->chain, i);
631
        /* RFC 5280, 4.2: a given extension MUST NOT appear more than once */
632
0
        CB_FAIL_IF((x->ex_flags & EXFLAG_DUPLICATE) != 0,
633
0
            ctx, x, i, X509_V_ERR_DUPLICATE_EXTENSION);
634
0
        CB_FAIL_IF((ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) == 0
635
0
                && (x->ex_flags & EXFLAG_CRITICAL) != 0,
636
0
            ctx, x, i, X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION);
637
0
        CB_FAIL_IF(!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY) != 0,
638
0
            ctx, x, i, X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED);
639
0
        ret = X509_check_ca(x);
640
0
        switch (must_be_ca) {
641
0
        case -1:
642
0
            CB_FAIL_IF((ctx->param->flags & X509_V_FLAG_X509_STRICT) != 0
643
0
                    && ret != 1 && ret != 0,
644
0
                ctx, x, i, X509_V_ERR_INVALID_CA);
645
0
            break;
646
0
        case 0:
647
0
            CB_FAIL_IF(ret != 0, ctx, x, i, X509_V_ERR_INVALID_NON_CA);
648
0
            break;
649
0
        default:
650
            /* X509_V_FLAG_X509_STRICT is implicit for intermediate CAs */
651
0
            CB_FAIL_IF(ret == 0
652
0
                    || ((i + 1 < num
653
0
                            || (ctx->param->flags & X509_V_FLAG_X509_STRICT) != 0)
654
0
                        && ret != 1),
655
0
                ctx, x, i, X509_V_ERR_INVALID_CA);
656
0
            break;
657
0
        }
658
0
        if (num > 1) {
659
            /* Check for presence of explicit elliptic curve parameters */
660
0
            ret = check_curve(x);
661
0
            CB_FAIL_IF(ret < 0, ctx, x, i, X509_V_ERR_UNSPECIFIED);
662
0
            CB_FAIL_IF(ret == 0, ctx, x, i, X509_V_ERR_EC_KEY_EXPLICIT_PARAMS);
663
0
        }
664
        /*
665
         * Do the following set of checks only if strict checking is requested
666
         * and not for self-issued (including self-signed) EE (non-CA) certs
667
         * because RFC 5280 does not apply to them according RFC 6818 section 2.
668
         */
669
0
        if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) != 0
670
0
            && num > 1) { /*
671
                           * this should imply
672
                           * !(i == 0 && (x->ex_flags & EXFLAG_CA) == 0
673
                           *          && (x->ex_flags & EXFLAG_SI) != 0)
674
                           */
675
            /* Check Basic Constraints according to RFC 5280 section 4.2.1.9 */
676
0
            if (x->ex_pathlen != -1) {
677
0
                CB_FAIL_IF((x->ex_flags & EXFLAG_CA) == 0,
678
0
                    ctx, x, i, X509_V_ERR_PATHLEN_INVALID_FOR_NON_CA);
679
0
                CB_FAIL_IF((x->ex_kusage & KU_KEY_CERT_SIGN) == 0, ctx,
680
0
                    x, i, X509_V_ERR_PATHLEN_WITHOUT_KU_KEY_CERT_SIGN);
681
0
            }
682
            /* Check Key Usage according to RFC 5280 section 4.2.1.3 */
683
0
            if ((x->ex_flags & EXFLAG_CA) != 0) {
684
0
                CB_FAIL_IF((x->ex_flags & EXFLAG_KUSAGE) == 0,
685
0
                    ctx, x, i, X509_V_ERR_CA_CERT_MISSING_KEY_USAGE);
686
0
            } else {
687
0
                CB_FAIL_IF((x->ex_kusage & KU_KEY_CERT_SIGN) != 0, ctx, x, i,
688
0
                    X509_V_ERR_KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA);
689
0
            }
690
            /* Check issuer is non-empty acc. to RFC 5280 section 4.1.2.4 */
691
0
            CB_FAIL_IF(X509_NAME_entry_count(X509_get_issuer_name(x)) == 0,
692
0
                ctx, x, i, X509_V_ERR_ISSUER_NAME_EMPTY);
693
            /* Check subject is non-empty acc. to RFC 5280 section 4.1.2.6 */
694
0
            CB_FAIL_IF(((x->ex_flags & EXFLAG_CA) != 0
695
0
                           || (x->ex_kusage & KU_CRL_SIGN) != 0
696
0
                           || x->altname == NULL)
697
0
                    && X509_NAME_entry_count(X509_get_subject_name(x)) == 0,
698
0
                ctx, x, i, X509_V_ERR_SUBJECT_NAME_EMPTY);
699
            /* Check SAN is non-empty according to RFC 5280 section 4.2.1.6 */
700
0
            CB_FAIL_IF(x->altname != NULL
701
0
                    && sk_GENERAL_NAME_num(x->altname) <= 0,
702
0
                ctx, x, i, X509_V_ERR_EMPTY_SUBJECT_ALT_NAME);
703
            /* Check sig alg consistency acc. to RFC 5280 section 4.1.1.2 */
704
0
            CB_FAIL_IF(X509_ALGOR_cmp(&x->sig_alg, &x->cert_info.signature) != 0,
705
0
                ctx, x, i, X509_V_ERR_SIGNATURE_ALGORITHM_INCONSISTENCY);
706
0
            if (X509_get_version(x) >= X509_VERSION_3) {
707
                /* Check AKID presence acc. to RFC 5280 section 4.2.1.1 */
708
                /*
709
                 * This means not last cert in chain, taken as generated by
710
                 * conforming CAs and not self-signed.
711
                 */
712
0
                unsigned int check_akid = (i + 1 < num)
713
0
                    && ((x->ex_flags & EXFLAG_SS) == 0);
714
0
                CB_FAIL_IF(check_akid != 0 && x->akid == NULL,
715
0
                    ctx, x, i, X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER);
716
0
                CB_FAIL_IF(check_akid != 0 && x->akid != NULL
717
0
                        && x->akid->keyid == NULL && x->akid->issuer == NULL
718
0
                        && x->akid->serial == NULL,
719
0
                    ctx, x, i, X509_V_ERR_EMPTY_AUTHORITY_KEY_IDENTIFIER);
720
                /*
721
                 * The authorityCertIssuer and authorityCertSerialNumber fields
722
                 * are paired and MUST either both be present or both be absent.
723
                 *
724
                 * Issuer without serial is ambiguous, and serial without issuer
725
                 * is meaningless, leading to unresolvable and misleading issuer
726
                 * identification.
727
                 */
728
0
                CB_FAIL_IF(x->akid != NULL
729
0
                        && (x->akid->issuer == NULL) != (x->akid->serial == NULL),
730
0
                    ctx, x, i, X509_V_ERR_AKID_ISSUER_SERIAL_NOT_PAIRED);
731
                /* Check SKID presence acc. to RFC 5280 section 4.2.1.2 */
732
0
                CB_FAIL_IF((x->ex_flags & EXFLAG_CA) != 0 && x->skid == NULL,
733
0
                    ctx, x, i, X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER);
734
0
            } else {
735
0
                CB_FAIL_IF(sk_X509_EXTENSION_num(X509_get0_extensions(x)) > 0,
736
0
                    ctx, x, i, X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3);
737
0
            }
738
0
        }
739
740
        /* check_purpose() makes the callback as needed */
741
0
        if (purpose >= X509_PURPOSE_MIN && !check_purpose(ctx, x, purpose, i, must_be_ca))
742
0
            return 0;
743
        /* Check path length */
744
0
        CB_FAIL_IF(i > 1 && x->ex_pathlen != -1
745
0
                && plen > x->ex_pathlen + proxy_path_length,
746
0
            ctx, x, i, X509_V_ERR_PATH_LENGTH_EXCEEDED);
747
        /* Increment path length if not a self-issued intermediate CA */
748
0
        if (i > 0 && (x->ex_flags & EXFLAG_SI) == 0)
749
0
            plen++;
750
        /*
751
         * If this certificate is a proxy certificate, the next certificate
752
         * must be another proxy certificate or a EE certificate.  If not,
753
         * the next certificate must be a CA certificate.
754
         */
755
0
        if (x->ex_flags & EXFLAG_PROXY) {
756
            /*
757
             * RFC3820, 4.1.3 (b)(1) stipulates that if pCPathLengthConstraint
758
             * is less than max_path_length, the former should be copied to
759
             * the latter, and 4.1.4 (a) stipulates that max_path_length
760
             * should be verified to be larger than zero and decrement it.
761
             *
762
             * Because we're checking the certs in the reverse order, we start
763
             * with verifying that proxy_path_length isn't larger than pcPLC,
764
             * and copy the latter to the former if it is, and finally,
765
             * increment proxy_path_length.
766
             */
767
0
            if (x->ex_pcpathlen != -1) {
768
0
                CB_FAIL_IF(proxy_path_length > x->ex_pcpathlen,
769
0
                    ctx, x, i, X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED);
770
0
                proxy_path_length = x->ex_pcpathlen;
771
0
            }
772
0
            proxy_path_length++;
773
0
            must_be_ca = 0;
774
0
        } else {
775
0
            must_be_ca = 1;
776
0
        }
777
0
    }
778
0
    return 1;
779
0
}
780
781
/*-
782
 * Returns -1 on internal error.
783
 * Sadly, returns 0 also on internal error in ctx->verify_cb().
784
 */
785
static int check_name_constraints(X509_STORE_CTX *ctx)
786
0
{
787
0
    int i;
788
789
    /* Check name constraints for all certificates */
790
0
    for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) {
791
0
        const X509 *x = sk_X509_value(ctx->chain, i);
792
0
        int j;
793
794
        /* Ignore self-issued certs unless last in chain */
795
0
        if (i != 0 && (x->ex_flags & EXFLAG_SI) != 0)
796
0
            continue;
797
798
        /*
799
         * Proxy certificates policy has an extra constraint, where the
800
         * certificate subject MUST be the issuer with a single CN entry
801
         * added.
802
         * (RFC 3820: 3.4, 4.1.3 (a)(4))
803
         */
804
0
        if ((x->ex_flags & EXFLAG_PROXY) != 0) {
805
0
            const X509_NAME *tmpsubject = X509_get_subject_name(x);
806
0
            const X509_NAME *tmpissuer = X509_get_issuer_name(x);
807
0
            X509_NAME *tmpsubject2;
808
0
            X509_NAME_ENTRY *tmpentry = NULL;
809
0
            int last_nid = 0;
810
0
            int err = X509_V_OK;
811
0
            int last_loc = X509_NAME_entry_count(tmpsubject) - 1;
812
813
            /* Check that there are at least two RDNs */
814
0
            if (last_loc < 1) {
815
0
                err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
816
0
                goto proxy_name_done;
817
0
            }
818
819
            /*
820
             * Check that there is exactly one more RDN in subject as
821
             * there is in issuer.
822
             */
823
0
            if (X509_NAME_entry_count(tmpsubject)
824
0
                != X509_NAME_entry_count(tmpissuer) + 1) {
825
0
                err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
826
0
                goto proxy_name_done;
827
0
            }
828
829
            /*
830
             * Check that the last subject component isn't part of a
831
             * multi-valued RDN
832
             */
833
0
            if (X509_NAME_ENTRY_set(X509_NAME_get_entry(tmpsubject, last_loc))
834
0
                == X509_NAME_ENTRY_set(X509_NAME_get_entry(tmpsubject,
835
0
                    last_loc - 1))) {
836
0
                err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
837
0
                goto proxy_name_done;
838
0
            }
839
840
            /*
841
             * Check that the last subject RDN is a commonName, and that
842
             * all the previous RDNs match the issuer exactly
843
             */
844
0
            tmpsubject2 = X509_NAME_dup(tmpsubject);
845
0
            if (tmpsubject2 == NULL) {
846
0
                ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
847
0
                ctx->error = X509_V_ERR_OUT_OF_MEM;
848
0
                return -1;
849
0
            }
850
851
0
            tmpentry = X509_NAME_delete_entry(tmpsubject2, last_loc);
852
0
            last_nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(tmpentry));
853
854
0
            if (last_nid != NID_commonName
855
0
                || X509_NAME_cmp(tmpsubject2, tmpissuer) != 0) {
856
0
                err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
857
0
            }
858
859
0
            X509_NAME_ENTRY_free(tmpentry);
860
0
            X509_NAME_free(tmpsubject2);
861
862
0
        proxy_name_done:
863
0
            CB_FAIL_IF(err != X509_V_OK, ctx, x, i, err);
864
0
        }
865
866
        /*
867
         * Check against constraints for all certificates higher in chain
868
         * including trust anchor. Trust anchor not strictly speaking needed
869
         * but if it includes constraints it is to be assumed it expects them
870
         * to be obeyed.
871
         */
872
0
        for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) {
873
0
            NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc;
874
875
0
            if (nc) {
876
0
                int rv = NAME_CONSTRAINTS_check(x, nc);
877
878
                /*
879
                 * Apply DNS name constraints to the EE subject commonName
880
                 * only when the commonName may be used for host name checks,
881
                 * mirroring do_x509_check(): only when the caller opted in
882
                 * with X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT, and never when
883
                 * X509_CHECK_FLAG_NEVER_CHECK_SUBJECT is set.
884
                 */
885
0
                if (rv == X509_V_OK && i == 0
886
0
                    && (ctx->param->hostflags
887
0
                           & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT)
888
0
                        == 0
889
0
                    && (ctx->param->hostflags
890
0
                           & X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT)
891
0
                        != 0)
892
0
                    rv = NAME_CONSTRAINTS_check_CN(x, nc);
893
894
0
                switch (rv) {
895
0
                case X509_V_OK:
896
0
                    break;
897
0
                case X509_V_ERR_OUT_OF_MEM:
898
0
                    return -1;
899
0
                default:
900
0
                    CB_FAIL_IF(1, ctx, x, i, rv);
901
0
                    break;
902
0
                }
903
0
            }
904
0
        }
905
0
    }
906
0
    return 1;
907
0
}
908
909
static int check_id_error(X509_STORE_CTX *ctx, int errcode)
910
0
{
911
0
    return verify_cb_cert(ctx, ctx->cert, 0, errcode);
912
0
}
913
914
static int check_hosts(X509 *x, X509_VERIFY_PARAM *vpm)
915
0
{
916
0
    const uint8_t *name;
917
0
    int n = sk_X509_BUFFER_num(vpm->hosts);
918
919
0
    if (vpm->peername != NULL) {
920
0
        OPENSSL_free(vpm->peername);
921
0
        vpm->peername = NULL;
922
0
    }
923
0
    for (int i = 0; i < n; ++i) {
924
0
        size_t len = sk_X509_BUFFER_value(vpm->hosts, i)->len;
925
0
        name = sk_X509_BUFFER_value(vpm->hosts, i)->data;
926
0
        if (ossl_x509_check_host(x, (const char *)name, len, vpm->hostflags,
927
0
                &vpm->peername)
928
0
            > 0)
929
0
            return 1;
930
0
    }
931
0
    return n <= 0;
932
0
}
933
934
static int check_email(X509 *x, X509_VERIFY_PARAM *vpm)
935
0
{
936
0
    const uint8_t *name;
937
0
    int nasc = sk_X509_BUFFER_num(vpm->rfc822s);
938
0
    int nutf = sk_X509_BUFFER_num(vpm->smtputf8s);
939
940
0
    for (int i = 0; i < nasc; ++i) {
941
0
        size_t len = sk_X509_BUFFER_value(vpm->rfc822s, i)->len;
942
0
        name = sk_X509_BUFFER_value(vpm->rfc822s, i)->data;
943
0
        if (ossl_x509_check_rfc822(x, (const char *)name, len, vpm->hostflags))
944
0
            return 1;
945
0
    }
946
0
    for (int i = 0; i < nutf; ++i) {
947
0
        size_t len = sk_X509_BUFFER_value(vpm->smtputf8s, i)->len;
948
0
        name = sk_X509_BUFFER_value(vpm->smtputf8s, i)->data;
949
0
        if (ossl_x509_check_smtputf8(x, (const char *)name, len, vpm->hostflags))
950
0
            return 1;
951
0
    }
952
0
    return nasc <= 0 && nutf <= 0;
953
0
}
954
955
static int check_ips(X509 *x, X509_VERIFY_PARAM *vpm)
956
0
{
957
0
    const uint8_t *name;
958
0
    int n = sk_X509_BUFFER_num(vpm->ips);
959
960
0
    for (int i = 0; i < n; ++i) {
961
0
        size_t len = sk_X509_BUFFER_value(vpm->ips, i)->len;
962
0
        name = sk_X509_BUFFER_value(vpm->ips, i)->data;
963
0
        if (ossl_x509_check_ip(x, name, len, vpm->hostflags) > 0)
964
0
            return 1;
965
0
    }
966
0
    return n <= 0;
967
0
}
968
969
static int check_id(X509_STORE_CTX *ctx)
970
0
{
971
0
    X509_VERIFY_PARAM *vpm = ctx->param;
972
0
    X509 *x = ctx->cert;
973
974
0
    if (vpm->hosts != NULL && check_hosts(x, vpm) <= 0) {
975
0
        if (!check_id_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH))
976
0
            return 0;
977
0
    }
978
979
0
    if (!check_email(x, vpm)) {
980
0
        if (!check_id_error(ctx, X509_V_ERR_EMAIL_MISMATCH))
981
0
            return 0;
982
0
    }
983
984
0
    if (vpm->ips != NULL && check_ips(x, vpm) <= 0) {
985
0
        if (!check_id_error(ctx, X509_V_ERR_IP_ADDRESS_MISMATCH))
986
0
            return 0;
987
0
    }
988
0
    return 1;
989
0
}
990
991
/*
992
 * Returns 1 is an ASN1 time is valid for an RFC5280 certificate, 0 otherwise
993
 */
994
static int validate_certificate_time(const ASN1_TIME *ctm)
995
0
{
996
0
    static const size_t utctime_length = sizeof("YYMMDDHHMMSSZ") - 1;
997
0
    static const size_t generalizedtime_length = sizeof("YYYYMMDDHHMMSSZ") - 1;
998
0
    int i;
999
#ifdef CHARSET_EBCDIC
1000
    const char upper_z = 0x5A;
1001
#else
1002
0
    const char upper_z = 'Z';
1003
0
#endif
1004
1005
    /*-
1006
     * Note that ASN.1 allows much more slack in the time format than RFC5280.
1007
     * In RFC5280, the representation is fixed:
1008
     * UTCTime: YYMMDDHHMMSSZ
1009
     * GeneralizedTime: YYYYMMDDHHMMSSZ
1010
     *
1011
     * We do NOT currently enforce the following RFC 5280 requirement:
1012
     * "CAs conforming to this profile MUST always encode certificate
1013
     *  validity dates through the year 2049 as UTCTime; certificate validity
1014
     *  dates in 2050 or later MUST be encoded as GeneralizedTime."
1015
     */
1016
0
    switch (ctm->type) {
1017
0
    case V_ASN1_UTCTIME:
1018
0
        if (ctm->length != (int)(utctime_length))
1019
0
            return 0;
1020
0
        break;
1021
0
    case V_ASN1_GENERALIZEDTIME:
1022
0
        if (ctm->length != (int)(generalizedtime_length))
1023
0
            return 0;
1024
0
        break;
1025
0
    default:
1026
0
        return 0;
1027
0
    }
1028
1029
    /**
1030
     * Verify the format: the ASN.1 functions we use below allow a more
1031
     * flexible format than what's mandated by RFC 5280.
1032
     * Digit and date ranges will be verified in the conversion methods.
1033
     */
1034
0
    for (i = 0; i < ctm->length - 1; i++) {
1035
0
        if (!ossl_ascii_isdigit(ctm->data[i]))
1036
0
            return 0;
1037
0
    }
1038
0
    if (ctm->data[ctm->length - 1] != upper_z)
1039
0
        return 0;
1040
1041
0
    return 1;
1042
0
}
1043
1044
/* Validate and convert certificate time to a posix time */
1045
static int certificate_time_to_posix(const ASN1_TIME *ctm, int64_t *out_time)
1046
0
{
1047
0
    struct tm stm;
1048
1049
0
    if (!validate_certificate_time(ctm))
1050
0
        return 0;
1051
1052
0
    if (!ASN1_TIME_to_tm(ctm, &stm))
1053
0
        return 0;
1054
1055
0
    if (!OPENSSL_tm_to_posix(&stm, out_time))
1056
0
        return 0;
1057
1058
0
    return 1;
1059
0
}
1060
1061
/* Returns -1 on internal error */
1062
static int check_trust(X509_STORE_CTX *ctx, int num_untrusted)
1063
0
{
1064
0
    int i, res;
1065
0
    X509 *x = NULL;
1066
0
    X509 *mx;
1067
0
    SSL_DANE *dane = ctx->dane;
1068
0
    int num = sk_X509_num(ctx->chain);
1069
0
    int trust;
1070
1071
    /*
1072
     * Check for a DANE issuer at depth 1 or greater, if it is a DANE-TA(2)
1073
     * match, we're done, otherwise we'll merely record the match depth.
1074
     */
1075
0
    if (DANETLS_HAS_TA(dane) && num_untrusted > 0 && num_untrusted < num) {
1076
0
        trust = check_dane_issuer(ctx, num_untrusted);
1077
0
        if (trust != X509_TRUST_UNTRUSTED)
1078
0
            return trust;
1079
0
    }
1080
1081
    /*
1082
     * Check trusted certificates in chain at depth num_untrusted and up.
1083
     * Note, that depths 0..num_untrusted-1 may also contain trusted
1084
     * certificates, but the caller is expected to have already checked those,
1085
     * and wants to incrementally check just any added since.
1086
     */
1087
0
    for (i = num_untrusted; i < num; i++) {
1088
0
        x = sk_X509_value(ctx->chain, i);
1089
0
        trust = X509_check_trust(x, ctx->param->trust, 0);
1090
        /* If explicitly trusted (so not neutral nor rejected) return trusted */
1091
0
        if (trust == X509_TRUST_TRUSTED)
1092
0
            goto trusted;
1093
0
        if (trust == X509_TRUST_REJECTED)
1094
0
            goto rejected;
1095
0
    }
1096
1097
    /*
1098
     * If we are looking at a trusted certificate, and accept partial chains,
1099
     * the chain is PKIX trusted.
1100
     */
1101
0
    if (num_untrusted < num) {
1102
0
        if ((ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) != 0)
1103
0
            goto trusted;
1104
0
        return X509_TRUST_UNTRUSTED;
1105
0
    }
1106
1107
0
    if (num_untrusted == num
1108
0
        && (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) != 0) {
1109
        /*
1110
         * Last-resort call with no new trusted certificates, check the leaf
1111
         * for a direct trust store match.
1112
         */
1113
0
        i = 0;
1114
0
        x = sk_X509_value(ctx->chain, i);
1115
0
        res = lookup_cert_match(&mx, ctx, x);
1116
0
        if (res < 0)
1117
0
            return res;
1118
0
        if (res == 0)
1119
0
            return X509_TRUST_UNTRUSTED;
1120
1121
        /*
1122
         * Check explicit auxiliary trust/reject settings.  If none are set,
1123
         * we'll accept X509_TRUST_UNTRUSTED when not self-signed.
1124
         */
1125
0
        trust = X509_check_trust(mx, ctx->param->trust, 0);
1126
0
        if (trust == X509_TRUST_REJECTED) {
1127
0
            X509_free(mx);
1128
0
            goto rejected;
1129
0
        }
1130
1131
        /* Replace leaf with trusted match */
1132
0
        (void)sk_X509_set(ctx->chain, 0, mx);
1133
0
        X509_free(x);
1134
0
        ctx->num_untrusted = 0;
1135
0
        goto trusted;
1136
0
    }
1137
1138
    /*
1139
     * If no trusted certs in chain at all return untrusted and allow
1140
     * standard (no issuer cert) etc errors to be indicated.
1141
     */
1142
0
    return X509_TRUST_UNTRUSTED;
1143
1144
0
rejected:
1145
0
    return verify_cb_cert(ctx, x, i, X509_V_ERR_CERT_REJECTED) == 0
1146
0
        ? X509_TRUST_REJECTED
1147
0
        : X509_TRUST_UNTRUSTED;
1148
1149
0
trusted:
1150
0
    if (!DANETLS_ENABLED(dane))
1151
0
        return X509_TRUST_TRUSTED;
1152
0
    if (dane->pdpth < 0)
1153
0
        dane->pdpth = num_untrusted;
1154
    /* With DANE, PKIX alone is not trusted until we have both */
1155
0
    if (dane->mdpth >= 0)
1156
0
        return X509_TRUST_TRUSTED;
1157
0
    return X509_TRUST_UNTRUSTED;
1158
0
}
1159
1160
/*
1161
 * Return the last chain depth whose revocation status should be checked.
1162
 * With X509_V_FLAG_*_CHECK_ALL and X509_V_FLAG_PARTIAL_CHAIN, revocation
1163
 * checking stops before the first trusted certificate in the chain.
1164
 */
1165
static int revocation_check_end(X509_STORE_CTX *ctx, int check_all)
1166
0
{
1167
0
    if (!check_all)
1168
0
        return 0;
1169
0
    return (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) == 0
1170
0
        ? sk_X509_num(ctx->chain) - 1
1171
0
        : ctx->num_untrusted - 1;
1172
0
}
1173
1174
/* Sadly, returns 0 also on internal error. */
1175
static int check_revocation(X509_STORE_CTX *ctx)
1176
0
{
1177
0
    int i = 0, last = 0, ok = 0;
1178
0
    int crl_check_enabled = (ctx->param->flags & X509_V_FLAG_CRL_CHECK) != 0;
1179
0
    int crl_check_all_enabled = crl_check_enabled && (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL) != 0;
1180
0
    int ocsp_check_enabled = (ctx->param->flags & X509_V_FLAG_OCSP_RESP_CHECK) != 0;
1181
0
    int ocsp_check_all_enabled = ocsp_check_enabled && (ctx->param->flags & X509_V_FLAG_OCSP_RESP_CHECK_ALL) != 0;
1182
1183
0
    if (!crl_check_enabled && !ocsp_check_enabled)
1184
0
        return 1;
1185
1186
0
    if (ocsp_check_enabled) {
1187
0
#ifndef OPENSSL_NO_OCSP
1188
        /*
1189
         * certificate status checking with OCSP
1190
         */
1191
0
        if (!ocsp_check_all_enabled && !crl_check_all_enabled
1192
0
            && ctx->parent != NULL)
1193
0
            return 1; /* If checking CRL paths this isn't the EE certificate */
1194
0
        last = revocation_check_end(ctx, ocsp_check_all_enabled);
1195
1196
0
        for (i = 0; i <= last; i++) {
1197
0
            ctx->error_depth = i;
1198
0
            ctx->current_cert = sk_X509_value(ctx->chain, i);
1199
1200
            /* skip if cert is apparently self-signed */
1201
0
            if (ctx->current_cert->ex_flags & EXFLAG_SS)
1202
0
                continue;
1203
1204
            /* the issuer certificate is the next in the chain */
1205
0
            ctx->current_issuer = sk_X509_value(ctx->chain, i + 1);
1206
0
            if (ctx->current_issuer == NULL) {
1207
                /*
1208
                 * No issuer exists at i+1 — this is the partial-chain
1209
                 * trust anchor. OCSP requires an issuer to build the
1210
                 * CertID, so skip OCSP checking for this certificate.
1211
                 */
1212
0
                if ((ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) != 0)
1213
0
                    continue;
1214
0
                return verify_cb_ocsp(ctx, X509_V_ERR_OCSP_VERIFY_FAILED);
1215
0
            }
1216
1217
0
            ok = check_cert_ocsp_resp(ctx);
1218
1219
            /*
1220
             * In the case the certificate status is REVOKED, the verification
1221
             * can stop here.
1222
             */
1223
0
            if (ok == V_OCSP_CERTSTATUS_REVOKED) {
1224
0
                return verify_cb_ocsp(ctx, ctx->error != 0 ? ctx->error : X509_V_ERR_OCSP_VERIFY_FAILED);
1225
0
            }
1226
1227
            /*
1228
             * In the case the certificate status is GOOD, continue with the next
1229
             * certificate.
1230
             */
1231
0
            if (ok == V_OCSP_CERTSTATUS_GOOD)
1232
0
                continue;
1233
1234
            /*
1235
             * As stated in RFC 6961 section 2.2:
1236
             * If OCSP is not enabled or the client receives a "ocsp_response_list"
1237
             * that does not contain a response for one or more of the certificates
1238
             * in the completed certificate chain, the client SHOULD attempt to
1239
             * validate the certificate using an alternative retrieval method,
1240
             * such as downloading the relevant CRL;
1241
             */
1242
0
            if (crl_check_all_enabled || (crl_check_enabled && i == 0)) {
1243
0
                ok = check_cert_crl(ctx);
1244
0
                if (!ok)
1245
0
                    return ok;
1246
0
            } else {
1247
0
                ok = verify_cb_ocsp(ctx, X509_V_ERR_OCSP_VERIFY_FAILED);
1248
0
                if (!ok)
1249
0
                    return ok;
1250
0
            }
1251
0
        }
1252
0
#endif
1253
0
    }
1254
1255
0
    if (crl_check_enabled && !ocsp_check_all_enabled) {
1256
        /* certificate status check with CRLs */
1257
0
        if (!crl_check_all_enabled && ctx->parent != NULL)
1258
0
            return 1; /* If checking CRL paths this isn't the EE certificate */
1259
0
        last = revocation_check_end(ctx, crl_check_all_enabled);
1260
1261
        /*
1262
         * in the case that OCSP is only enabled for the server certificate
1263
         * and CRL for the complete chain, the rest of the chain has to be
1264
         * checked here
1265
         */
1266
0
        if (ocsp_check_enabled && crl_check_all_enabled)
1267
0
            i = 1;
1268
0
        else
1269
0
            i = 0;
1270
0
        for (; i <= last; i++) {
1271
0
            ctx->error_depth = i;
1272
0
            ok = check_cert_crl(ctx);
1273
0
            if (!ok)
1274
0
                return ok;
1275
0
        }
1276
0
    }
1277
1278
0
    return 1;
1279
0
}
1280
1281
#ifndef OPENSSL_NO_OCSP
1282
static int check_cert_ocsp_resp(X509_STORE_CTX *ctx)
1283
0
{
1284
0
    int cert_status, crl_reason;
1285
0
    int i;
1286
0
    OCSP_RESPONSE *resp = NULL;
1287
0
    OCSP_BASICRESP *bs = NULL;
1288
0
    OCSP_SINGLERESP *sr = NULL;
1289
0
    OCSP_CERTID *sr_cert_id = NULL;
1290
0
    ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1291
0
    ASN1_OBJECT *cert_id_md_oid;
1292
0
    EVP_MD *cert_id_md = NULL;
1293
0
    OCSP_CERTID *cert_id = NULL;
1294
0
    int ret = V_OCSP_CERTSTATUS_UNKNOWN;
1295
0
    int num;
1296
1297
0
    num = sk_OCSP_RESPONSE_num(ctx->ocsp_resp);
1298
1299
0
    if (num < 0 || num <= ctx->error_depth)
1300
0
        return X509_V_ERR_OCSP_NO_RESPONSE;
1301
1302
0
    if ((resp = sk_OCSP_RESPONSE_value(ctx->ocsp_resp, ctx->error_depth)) == NULL
1303
0
        || (bs = OCSP_response_get1_basic(resp)) == NULL)
1304
0
        return X509_V_ERR_OCSP_NO_RESPONSE;
1305
1306
    /*
1307
     * OCSP_response_get1_basic() returns an owning reference, so once bs is
1308
     * non-NULL it must be released via the end: cleanup label. Route an empty
1309
     * BasicResponse (no single responses) through end: rather than returning
1310
     * directly, otherwise bs leaks.
1311
     */
1312
0
    if ((num = OCSP_resp_count(bs)) < 1) {
1313
0
        ret = X509_V_ERR_OCSP_NO_RESPONSE;
1314
0
        goto end;
1315
0
    }
1316
1317
0
    if (OCSP_response_status(resp) != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1318
0
        OCSP_BASICRESP_free(bs);
1319
0
        bs = NULL;
1320
0
        ret = X509_V_ERR_OCSP_RESP_INVALID;
1321
0
        goto end;
1322
0
    }
1323
1324
0
    if (OCSP_basic_verify(bs, ctx->chain, ctx->store, 0) <= 0) {
1325
0
        ret = X509_V_ERR_OCSP_SIGNATURE_FAILURE;
1326
0
        goto end;
1327
0
    }
1328
1329
    /* find the right single response in the OCSP response */
1330
0
    for (i = 0; i < num; i++) {
1331
0
        sr = OCSP_resp_get0(bs, i);
1332
1333
        /* determine the md algorithm which was used to create cert id */
1334
0
        sr_cert_id = (OCSP_CERTID *)OCSP_SINGLERESP_get0_id(sr);
1335
0
        OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, sr_cert_id);
1336
0
        if (cert_id_md_oid != NULL) {
1337
0
            char md_name[80];
1338
1339
0
            if (i2t_ASN1_OBJECT(md_name, sizeof(md_name), cert_id_md_oid) > 0)
1340
0
                cert_id_md = EVP_MD_fetch(ctx->libctx, md_name, ctx->propq);
1341
0
        }
1342
1343
        /* search the stack for the requested OCSP response */
1344
0
        cert_id = OCSP_cert_to_id(cert_id_md, ctx->current_cert, ctx->current_issuer);
1345
0
        EVP_MD_free(cert_id_md);
1346
0
        cert_id_md = NULL;
1347
0
        if (cert_id == NULL) {
1348
0
            ret = X509_V_ERR_OCSP_RESP_INVALID;
1349
0
            goto end;
1350
0
        }
1351
1352
0
        if (!OCSP_id_cmp(cert_id, sr_cert_id))
1353
0
            break;
1354
1355
0
        OCSP_CERTID_free(cert_id);
1356
0
        cert_id = NULL;
1357
0
    }
1358
1359
0
    if (cert_id == NULL) {
1360
0
        ret = X509_V_ERR_OCSP_NO_RESPONSE;
1361
0
        goto end;
1362
0
    }
1363
1364
0
    if (OCSP_resp_find_status(bs, cert_id, &cert_status, &crl_reason, &rev,
1365
0
            &thisupd, &nextupd)
1366
0
        <= 0) {
1367
0
        ret = X509_V_ERR_OCSP_RESP_INVALID;
1368
0
        goto end;
1369
0
    }
1370
1371
0
    if (cert_status == V_OCSP_CERTSTATUS_GOOD) {
1372
        /*
1373
         * Note:
1374
         * A OCSP stapling result will be accepted up to 5 minutes
1375
         * after it expired!
1376
         */
1377
0
        if (!OCSP_check_validity(thisupd, nextupd, 300L, -1L))
1378
0
            ret = X509_V_ERR_OCSP_HAS_EXPIRED;
1379
0
        else
1380
0
            ret = V_OCSP_CERTSTATUS_GOOD;
1381
0
    } else {
1382
0
        ret = cert_status;
1383
0
    }
1384
1385
0
end:
1386
0
    OCSP_CERTID_free(cert_id);
1387
0
    OCSP_BASICRESP_free(bs);
1388
0
    return ret;
1389
0
}
1390
#endif
1391
1392
/* Sadly, returns 0 also on internal error. */
1393
static int check_cert_crl(X509_STORE_CTX *ctx)
1394
0
{
1395
0
    X509_CRL *crl = NULL, *dcrl = NULL;
1396
0
    int ok = 0;
1397
0
    int cnum = ctx->error_depth;
1398
0
    X509 *x = sk_X509_value(ctx->chain, cnum);
1399
1400
0
    ctx->current_cert = x;
1401
0
    ctx->current_issuer = NULL;
1402
0
    ctx->current_crl_score = 0;
1403
0
    ctx->current_reasons = 0;
1404
1405
    /* skip if cert is apparently self-signed */
1406
0
    if (ctx->current_cert->ex_flags & EXFLAG_SS)
1407
0
        return 1;
1408
0
    if ((x->ex_flags & EXFLAG_PROXY) != 0)
1409
0
        return 1;
1410
1411
0
    while (ctx->current_reasons != CRLDP_ALL_REASONS) {
1412
0
        unsigned int last_reasons = ctx->current_reasons;
1413
1414
        /* Try to retrieve relevant CRL */
1415
0
        if (ctx->get_crl != NULL) {
1416
0
            X509 *crl_issuer = NULL;
1417
0
            unsigned int reasons = 0;
1418
1419
0
            ok = ctx->get_crl(ctx, &crl, x);
1420
0
            if (crl != NULL) {
1421
0
                ctx->current_crl_score = get_crl_score(ctx, &crl_issuer,
1422
0
                    &reasons, crl, x);
1423
0
                ctx->current_issuer = crl_issuer;
1424
0
                ctx->current_reasons = reasons;
1425
0
            }
1426
0
        } else {
1427
0
            ok = get_crl_delta(ctx, &crl, &dcrl, x);
1428
0
        }
1429
        /* If error looking up CRL, nothing we can do except notify callback */
1430
0
        if (!ok) {
1431
0
            ok = verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL);
1432
0
            goto done;
1433
0
        }
1434
1435
0
        ok = ctx->check_crl(ctx, crl);
1436
0
        if (!ok)
1437
0
            goto done;
1438
1439
0
        if (dcrl != NULL) {
1440
0
            ok = ctx->check_crl(ctx, dcrl);
1441
0
            if (!ok)
1442
0
                goto done;
1443
0
            ok = ctx->cert_crl(ctx, dcrl, x);
1444
0
            if (!ok)
1445
0
                goto done;
1446
0
        } else {
1447
0
            ok = 1;
1448
0
        }
1449
1450
        /* Don't look in full CRL if delta reason is removefromCRL */
1451
0
        if (ok != 2) {
1452
0
            ok = ctx->cert_crl(ctx, crl, x);
1453
0
            if (!ok)
1454
0
                goto done;
1455
0
        }
1456
1457
0
        ctx->current_crl = NULL;
1458
0
        X509_CRL_free(crl);
1459
0
        X509_CRL_free(dcrl);
1460
0
        crl = NULL;
1461
0
        dcrl = NULL;
1462
        /*
1463
         * If reasons not updated we won't get anywhere by another iteration,
1464
         * so exit loop.
1465
         */
1466
0
        if (last_reasons == ctx->current_reasons) {
1467
0
            ok = verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL);
1468
0
            goto done;
1469
0
        }
1470
0
    }
1471
0
done:
1472
0
    X509_CRL_free(crl);
1473
0
    X509_CRL_free(dcrl);
1474
1475
0
    ctx->current_crl = NULL;
1476
0
    return ok;
1477
0
}
1478
1479
/*
1480
 * returns 1 and sets verification time if time should be checked.
1481
 * returns 0 if time should not be checked.
1482
 */
1483
static int get_verification_time(const X509_VERIFY_PARAM *vpm,
1484
    int64_t *verification_time)
1485
0
{
1486
0
    if (vpm != NULL && (vpm->flags & X509_V_FLAG_USE_CHECK_TIME) != 0)
1487
0
        *verification_time = vpm->check_time;
1488
0
    else
1489
0
        *verification_time = (int64_t)time(NULL);
1490
1491
0
    return vpm == NULL || (vpm->flags & X509_V_FLAG_NO_CHECK_TIME) == 0;
1492
0
}
1493
1494
/* Check CRL times against values in X509_STORE_CTX */
1495
int ossl_x509_check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
1496
0
{
1497
0
    int64_t verification_time, last_update, next_update;
1498
0
    int err;
1499
1500
0
    if (!get_verification_time(ctx->param, &verification_time))
1501
0
        return 1;
1502
1503
0
    if (!certificate_time_to_posix(X509_CRL_get0_lastUpdate(crl),
1504
0
            &last_update)) {
1505
0
        err = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD;
1506
0
        if (!notify || !verify_cb_crl(ctx, err))
1507
0
            return 0;
1508
0
    } else if (verification_time < last_update) {
1509
0
        err = X509_V_ERR_CRL_NOT_YET_VALID;
1510
0
        if (!notify || !verify_cb_crl(ctx, err))
1511
0
            return 0;
1512
0
    }
1513
1514
0
    if (X509_CRL_get0_nextUpdate(crl)) {
1515
0
        if (!certificate_time_to_posix(X509_CRL_get0_nextUpdate(crl),
1516
0
                &next_update)) {
1517
0
            err = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD;
1518
0
            if (!notify || !verify_cb_crl(ctx, err))
1519
0
                return 0;
1520
0
        } else if (verification_time > next_update
1521
            /* Ignore expiration of base CRL is delta is valid */
1522
0
            && (ctx->current_crl_score & CRL_SCORE_TIME_DELTA) == 0) {
1523
0
            err = X509_V_ERR_CRL_HAS_EXPIRED;
1524
0
            if (!notify || !verify_cb_crl(ctx, err))
1525
0
                return 0;
1526
0
        }
1527
0
    }
1528
1529
0
    return 1;
1530
0
}
1531
1532
static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
1533
    X509 **pissuer, int *pscore, unsigned int *preasons,
1534
    STACK_OF(X509_CRL) *crls)
1535
0
{
1536
0
    int i, crl_score, best_score = *pscore;
1537
0
    unsigned int reasons, best_reasons = 0;
1538
0
    X509 *x = ctx->current_cert;
1539
0
    X509_CRL *crl, *best_crl = NULL;
1540
0
    X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
1541
1542
0
    for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1543
0
        crl = sk_X509_CRL_value(crls, i);
1544
0
        reasons = *preasons;
1545
0
        crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
1546
0
        if (crl_score < best_score || crl_score == 0)
1547
0
            continue;
1548
        /* If current CRL is equivalent use it if it is newer */
1549
0
        if (crl_score == best_score && best_crl != NULL) {
1550
0
            int day, sec;
1551
1552
0
            if (ASN1_TIME_diff(&day, &sec, X509_CRL_get0_lastUpdate(best_crl),
1553
0
                    X509_CRL_get0_lastUpdate(crl))
1554
0
                == 0)
1555
0
                continue;
1556
            /*
1557
             * ASN1_TIME_diff never returns inconsistent signs for |day|
1558
             * and |sec|.
1559
             */
1560
0
            if (day <= 0 && sec <= 0)
1561
0
                continue;
1562
0
        }
1563
0
        best_crl = crl;
1564
0
        best_crl_issuer = crl_issuer;
1565
0
        best_score = crl_score;
1566
0
        best_reasons = reasons;
1567
0
    }
1568
1569
0
    if (best_crl != NULL) {
1570
0
        if (!X509_CRL_up_ref(best_crl))
1571
0
            return 0;
1572
0
        X509_CRL_free(*pcrl);
1573
0
        *pcrl = best_crl;
1574
0
        *pissuer = best_crl_issuer;
1575
0
        *pscore = best_score;
1576
0
        *preasons = best_reasons;
1577
0
        X509_CRL_free(*pdcrl);
1578
0
        *pdcrl = NULL;
1579
0
        get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
1580
0
    }
1581
1582
0
    if (best_score >= CRL_SCORE_VALID)
1583
0
        return 1;
1584
1585
0
    return 0;
1586
0
}
1587
1588
/*
1589
 * Compare two CRL extensions for delta checking purposes. They should be
1590
 * both present or both absent. If both present all fields must be identical.
1591
 */
1592
static int crl_extension_match(X509_CRL *a, X509_CRL *b, int nid)
1593
0
{
1594
0
    const ASN1_OCTET_STRING *exta = NULL, *extb = NULL;
1595
0
    int i = X509_CRL_get_ext_by_NID(a, nid, -1);
1596
1597
0
    if (i >= 0) {
1598
        /* Can't have multiple occurrences */
1599
0
        if (X509_CRL_get_ext_by_NID(a, nid, i) != -1)
1600
0
            return 0;
1601
0
        exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i));
1602
0
    }
1603
1604
0
    i = X509_CRL_get_ext_by_NID(b, nid, -1);
1605
0
    if (i >= 0) {
1606
0
        if (X509_CRL_get_ext_by_NID(b, nid, i) != -1)
1607
0
            return 0;
1608
0
        extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i));
1609
0
    }
1610
1611
0
    if (exta == NULL && extb == NULL)
1612
0
        return 1;
1613
1614
0
    if (exta == NULL || extb == NULL)
1615
0
        return 0;
1616
1617
0
    return ASN1_OCTET_STRING_cmp(exta, extb) == 0;
1618
0
}
1619
1620
/* See if a base and delta are compatible */
1621
static int check_delta_base(X509_CRL *delta, X509_CRL *base)
1622
0
{
1623
    /* Delta CRL must be a delta */
1624
0
    if (delta->base_crl_number == NULL)
1625
0
        return 0;
1626
    /* Base must have a CRL number */
1627
0
    if (base->crl_number == NULL)
1628
0
        return 0;
1629
    /* Issuer names must match */
1630
0
    if (X509_NAME_cmp(X509_CRL_get_issuer(base),
1631
0
            X509_CRL_get_issuer(delta))
1632
0
        != 0)
1633
0
        return 0;
1634
    /* AKID and IDP must match */
1635
0
    if (!crl_extension_match(delta, base, NID_authority_key_identifier))
1636
0
        return 0;
1637
0
    if (!crl_extension_match(delta, base, NID_issuing_distribution_point))
1638
0
        return 0;
1639
    /* Delta CRL base number must not exceed Full CRL number. */
1640
0
    if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0)
1641
0
        return 0;
1642
    /* Delta CRL number must exceed full CRL number */
1643
0
    if (delta->crl_number == NULL)
1644
0
        return 0;
1645
0
    return ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0;
1646
0
}
1647
1648
/*
1649
 * For a given base CRL find a delta... maybe extend to delta scoring or
1650
 * retrieve a chain of deltas...
1651
 */
1652
static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore,
1653
    X509_CRL *base, STACK_OF(X509_CRL) *crls)
1654
0
{
1655
0
    X509_CRL *delta;
1656
0
    int i;
1657
1658
0
    if ((ctx->param->flags & X509_V_FLAG_USE_DELTAS) == 0)
1659
0
        return;
1660
0
    if (((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST) == 0)
1661
0
        return;
1662
0
    for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1663
0
        delta = sk_X509_CRL_value(crls, i);
1664
0
        if (check_delta_base(delta, base)) {
1665
0
            if (!X509_CRL_up_ref(delta)) {
1666
0
                *dcrl = NULL;
1667
0
                return;
1668
0
            }
1669
1670
0
            *dcrl = delta;
1671
1672
0
            if (ossl_x509_check_crl_time(ctx, delta, 0))
1673
0
                *pscore |= CRL_SCORE_TIME_DELTA;
1674
1675
0
            return;
1676
0
        }
1677
0
    }
1678
0
    *dcrl = NULL;
1679
0
}
1680
1681
/*
1682
 * For a given CRL return how suitable it is for the supplied certificate
1683
 * 'x'. The return value is a mask of several criteria. If the issuer is not
1684
 * the certificate issuer this is returned in *pissuer. The reasons mask is
1685
 * also used to determine if the CRL is suitable: if no new reasons the CRL
1686
 * is rejected, otherwise reasons is updated.
1687
 */
1688
static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
1689
    unsigned int *preasons, X509_CRL *crl, X509 *x)
1690
0
{
1691
0
    int crl_score = 0;
1692
0
    unsigned int tmp_reasons = *preasons, crl_reasons;
1693
1694
    /* First see if we can reject CRL straight away */
1695
1696
    /* Invalid IDP cannot be processed */
1697
0
    if ((crl->idp_flags & IDP_INVALID) != 0)
1698
0
        return 0;
1699
    /*
1700
     * Reject delta CRLs unconditionally here. They are considered by
1701
     * get_delta_sk() after a base CRL is selected.
1702
     */
1703
0
    if (crl->base_crl_number != NULL)
1704
0
        return 0;
1705
    /* Reason codes or indirect CRLs need extended CRL support */
1706
0
    if ((ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT) == 0) {
1707
0
        if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
1708
0
            return 0;
1709
0
    } else if ((crl->idp_flags & IDP_REASONS) != 0) {
1710
        /* If no new reasons reject */
1711
0
        if ((crl->idp_reasons & ~tmp_reasons) == 0)
1712
0
            return 0;
1713
0
    }
1714
    /* If issuer name doesn't match certificate need indirect CRL */
1715
0
    if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl)) != 0) {
1716
0
        if ((crl->idp_flags & IDP_INDIRECT) == 0)
1717
0
            return 0;
1718
0
    } else {
1719
0
        crl_score |= CRL_SCORE_ISSUER_NAME;
1720
0
    }
1721
1722
0
    if ((crl->flags & EXFLAG_CRITICAL) == 0)
1723
0
        crl_score |= CRL_SCORE_NOCRITICAL;
1724
1725
    /* Check expiration */
1726
0
    if (ossl_x509_check_crl_time(ctx, crl, 0))
1727
0
        crl_score |= CRL_SCORE_TIME;
1728
1729
    /* Check authority key ID and locate certificate issuer */
1730
0
    crl_akid_check(ctx, crl, pissuer, &crl_score);
1731
1732
    /* If we can't locate certificate issuer at this point forget it */
1733
0
    if ((crl_score & CRL_SCORE_AKID) == 0)
1734
0
        return 0;
1735
1736
    /* Check cert for matching CRL distribution points */
1737
0
    if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
1738
        /* If no new reasons reject */
1739
0
        if ((crl_reasons & ~tmp_reasons) == 0)
1740
0
            return 0;
1741
0
        tmp_reasons |= crl_reasons;
1742
0
        crl_score |= CRL_SCORE_SCOPE;
1743
0
    }
1744
1745
0
    *preasons = tmp_reasons;
1746
0
    return crl_score;
1747
0
}
1748
1749
static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl,
1750
    X509 **pissuer, int *pcrl_score)
1751
0
{
1752
0
    X509 *crl_issuer = NULL;
1753
0
    const X509_NAME *cnm = X509_CRL_get_issuer(crl);
1754
0
    int cidx = ctx->error_depth;
1755
0
    int i;
1756
1757
0
    if (cidx != sk_X509_num(ctx->chain) - 1)
1758
0
        cidx++;
1759
1760
0
    crl_issuer = sk_X509_value(ctx->chain, cidx);
1761
1762
0
    if (matching_crl_issuer_and_akid(crl, crl_issuer, cnm)) {
1763
0
        if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
1764
0
            *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT;
1765
0
            *pissuer = crl_issuer;
1766
0
            return;
1767
0
        }
1768
0
    }
1769
1770
0
    for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) {
1771
0
        crl_issuer = sk_X509_value(ctx->chain, cidx);
1772
0
        if (matching_crl_issuer_and_akid(crl, crl_issuer, cnm)) {
1773
0
            *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH;
1774
0
            *pissuer = crl_issuer;
1775
0
            return;
1776
0
        }
1777
0
    }
1778
1779
    /* Anything else needs extended CRL support */
1780
0
    if ((ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT) == 0)
1781
0
        return;
1782
1783
    /*
1784
     * Otherwise the CRL issuer is not on the path. Look for it in the set of
1785
     * untrusted certificates.
1786
     */
1787
0
    for (i = 0; i < sk_X509_num(ctx->untrusted); i++) {
1788
0
        crl_issuer = sk_X509_value(ctx->untrusted, i);
1789
0
        if (matching_crl_issuer_and_akid(crl, crl_issuer, cnm)) {
1790
0
            *pissuer = crl_issuer;
1791
0
            *pcrl_score |= CRL_SCORE_AKID;
1792
0
            return;
1793
0
        }
1794
0
    }
1795
0
}
1796
1797
static int matching_crl_issuer_and_akid(const X509_CRL *crl,
1798
    const X509 *issuer, const X509_NAME *crl_issuer_name)
1799
0
{
1800
0
    if (issuer == NULL)
1801
0
        return 0;
1802
0
    if (X509_NAME_cmp(X509_get_subject_name(issuer), crl_issuer_name) != 0)
1803
0
        return 0;
1804
0
    return X509_check_akid(issuer, crl->akid) == X509_V_OK;
1805
0
}
1806
1807
/*
1808
 * Check the path of a CRL issuer certificate. This creates a new
1809
 * X509_STORE_CTX and populates it with most of the parameters from the
1810
 * parent. This could be optimised somewhat since a lot of path checking will
1811
 * be duplicated by the parent, but this will rarely be used in practice.
1812
 */
1813
static int check_crl_path(X509_STORE_CTX *ctx, X509 *x)
1814
0
{
1815
0
    X509_STORE_CTX crl_ctx = { 0 };
1816
0
    int ret;
1817
1818
    /* Don't allow recursive CRL path validation */
1819
0
    if (ctx->parent != NULL)
1820
0
        return 0;
1821
0
    if (!X509_STORE_CTX_init(&crl_ctx, ctx->store, x, ctx->untrusted))
1822
0
        return -1;
1823
1824
0
    crl_ctx.crls = ctx->crls;
1825
    /* Copy verify params across */
1826
0
    X509_STORE_CTX_set0_param(&crl_ctx, ctx->param);
1827
1828
0
    crl_ctx.parent = ctx;
1829
0
    crl_ctx.verify_cb = ctx->verify_cb;
1830
1831
    /* Verify CRL issuer */
1832
0
    ret = X509_verify_cert(&crl_ctx);
1833
0
    if (ret <= 0)
1834
0
        goto err;
1835
1836
    /* Check chain is acceptable */
1837
0
    ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain);
1838
0
err:
1839
0
    X509_STORE_CTX_cleanup(&crl_ctx);
1840
0
    return ret;
1841
0
}
1842
1843
/*
1844
 * RFC3280 says nothing about the relationship between CRL path and
1845
 * certificate path, which could lead to situations where a certificate could
1846
 * be revoked or validated by a CA not authorized to do so. RFC5280 is more
1847
 * strict and states that the two paths must end in the same trust anchor,
1848
 * though some discussions remain... until this is resolved we use the
1849
 * RFC5280 version
1850
 */
1851
static int check_crl_chain(X509_STORE_CTX *ctx,
1852
    STACK_OF(X509) *cert_path,
1853
    STACK_OF(X509) *crl_path)
1854
0
{
1855
0
    X509 *cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1);
1856
0
    X509 *crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1);
1857
1858
0
    return X509_cmp(cert_ta, crl_ta) == 0;
1859
0
}
1860
1861
/*-
1862
 * Check for match between two dist point names: three separate cases.
1863
 * 1. Both are relative names and compare X509_NAME types.
1864
 * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
1865
 * 3. Both are full names and compare two GENERAL_NAMES.
1866
 * 4. One is NULL: automatic match.
1867
 */
1868
static int idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b)
1869
0
{
1870
0
    X509_NAME *nm = NULL;
1871
0
    GENERAL_NAMES *gens = NULL;
1872
0
    GENERAL_NAME *gena, *genb;
1873
0
    int i, j;
1874
1875
0
    if (a == NULL || b == NULL)
1876
0
        return 1;
1877
0
    if (a->type == 1) {
1878
0
        if (a->dpname == NULL)
1879
0
            return 0;
1880
        /* Case 1: two X509_NAME */
1881
0
        if (b->type == 1) {
1882
0
            if (b->dpname == NULL)
1883
0
                return 0;
1884
0
            return X509_NAME_cmp(a->dpname, b->dpname) == 0;
1885
0
        }
1886
        /* Case 2: set name and GENERAL_NAMES appropriately */
1887
0
        nm = a->dpname;
1888
0
        gens = b->name.fullname;
1889
0
    } else if (b->type == 1) {
1890
0
        if (b->dpname == NULL)
1891
0
            return 0;
1892
        /* Case 2: set name and GENERAL_NAMES appropriately */
1893
0
        gens = a->name.fullname;
1894
0
        nm = b->dpname;
1895
0
    }
1896
1897
    /* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
1898
0
    if (nm != NULL) {
1899
0
        for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1900
0
            gena = sk_GENERAL_NAME_value(gens, i);
1901
0
            if (gena->type != GEN_DIRNAME)
1902
0
                continue;
1903
0
            if (X509_NAME_cmp(nm, gena->d.directoryName) == 0)
1904
0
                return 1;
1905
0
        }
1906
0
        return 0;
1907
0
    }
1908
1909
    /* Else case 3: two GENERAL_NAMES */
1910
1911
0
    for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
1912
0
        gena = sk_GENERAL_NAME_value(a->name.fullname, i);
1913
0
        for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
1914
0
            genb = sk_GENERAL_NAME_value(b->name.fullname, j);
1915
0
            if (GENERAL_NAME_cmp(gena, genb) == 0)
1916
0
                return 1;
1917
0
        }
1918
0
    }
1919
1920
0
    return 0;
1921
0
}
1922
1923
static int crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
1924
0
{
1925
0
    int i;
1926
0
    const X509_NAME *nm = X509_CRL_get_issuer(crl);
1927
1928
    /* If no CRLissuer return is successful iff don't need a match */
1929
0
    if (dp->CRLissuer == NULL)
1930
0
        return (crl_score & CRL_SCORE_ISSUER_NAME) != 0;
1931
0
    for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1932
0
        GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1933
1934
0
        if (gen->type != GEN_DIRNAME)
1935
0
            continue;
1936
0
        if (X509_NAME_cmp(gen->d.directoryName, nm) == 0)
1937
0
            return 1;
1938
0
    }
1939
0
    return 0;
1940
0
}
1941
1942
/*
1943
 * Check whether the distribution point name |idpname| of a CRL's IDP extension
1944
 * matches the default distribution point that RFC 5280, section 6.3.3, assumes
1945
 * for CRLs not specified in any of the certificate's distribution points: one
1946
 * whose fullName consists of the certificate issuer name and the names in the
1947
 * certificate's issuerAltName extension.  The assumed distribution point is
1948
 * constructed and matched with idp_check_dp().
1949
 */
1950
static int idp_check_issuer(DIST_POINT_NAME *idpname, X509 *x)
1951
0
{
1952
0
    DIST_POINT_NAME dpname;
1953
0
    GENERAL_NAMES *gens;
1954
0
    GENERAL_NAME *gen = NULL;
1955
0
    X509_NAME *iname = NULL;
1956
0
    int ret = 0;
1957
1958
    /*
1959
     * An undecodable issuerAltName extension is treated as an absent one;
1960
     * any decoding errors are not left in the error queue.
1961
     */
1962
0
    ERR_set_mark();
1963
0
    gens = X509_get_ext_d2i(x, NID_issuer_alt_name, NULL, NULL);
1964
0
    ERR_pop_to_mark();
1965
0
    if (gens == NULL && (gens = sk_GENERAL_NAME_new_null()) == NULL)
1966
0
        return 0;
1967
0
    if ((gen = GENERAL_NAME_new()) == NULL
1968
0
        || (iname = X509_NAME_dup(X509_get_issuer_name(x))) == NULL)
1969
0
        goto end;
1970
0
    GENERAL_NAME_set0_value(gen, GEN_DIRNAME, iname);
1971
0
    iname = NULL; /* now owned by |gen| */
1972
0
    if (!sk_GENERAL_NAME_push(gens, gen))
1973
0
        goto end;
1974
0
    gen = NULL; /* now owned by |gens| */
1975
1976
0
    dpname.type = 0; /* fullName */
1977
0
    dpname.name.fullname = gens;
1978
0
    dpname.dpname = NULL;
1979
0
    ret = idp_check_dp(&dpname, idpname);
1980
1981
0
end:
1982
0
    GENERAL_NAME_free(gen);
1983
0
    X509_NAME_free(iname);
1984
0
    GENERAL_NAMES_free(gens);
1985
0
    return ret;
1986
0
}
1987
1988
/* Check CRLDP and IDP */
1989
static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
1990
    unsigned int *preasons)
1991
0
{
1992
0
    int i;
1993
1994
0
    if ((crl->idp_flags & IDP_ONLYATTR) != 0)
1995
0
        return 0;
1996
0
    if ((x->ex_flags & EXFLAG_CA) != 0) {
1997
0
        if ((crl->idp_flags & IDP_ONLYUSER) != 0)
1998
0
            return 0;
1999
0
    } else {
2000
0
        if ((crl->idp_flags & IDP_ONLYCA) != 0)
2001
0
            return 0;
2002
0
    }
2003
0
    *preasons = crl->idp_reasons;
2004
0
    for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
2005
0
        DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
2006
2007
0
        if (crldp_check_crlissuer(dp, crl, crl_score)) {
2008
0
            if (crl->idp == NULL
2009
0
                || idp_check_dp(dp->distpoint, crl->idp->distpoint)) {
2010
0
                *preasons &= dp->dp_reasons;
2011
0
                return 1;
2012
0
            }
2013
0
        }
2014
0
    }
2015
    /*
2016
     * The CRL is not specified in any distribution point of the certificate.
2017
     * RFC 5280, section 6.3.3, allows such a CRL if it is issued by the
2018
     * certificate issuer, assuming a distribution point with the reasons and
2019
     * cRLIssuer fields omitted and a distribution point name consisting of
2020
     * the certificate issuer name and any issuerAltName entries.
2021
     */
2022
0
    return (crl_score & CRL_SCORE_ISSUER_NAME) != 0
2023
0
        && (crl->idp == NULL || crl->idp->distpoint == NULL
2024
0
            || idp_check_issuer(crl->idp->distpoint, x));
2025
0
}
2026
2027
/*
2028
 * Retrieve CRL corresponding to current certificate. If deltas enabled try
2029
 * to find a delta CRL too
2030
 */
2031
static int get_crl_delta(X509_STORE_CTX *ctx,
2032
    X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
2033
0
{
2034
0
    int ok;
2035
0
    X509 *issuer = NULL;
2036
0
    int crl_score = 0;
2037
0
    unsigned int reasons;
2038
0
    X509_CRL *crl = NULL, *dcrl = NULL;
2039
0
    STACK_OF(X509_CRL) *skcrl;
2040
0
    const X509_NAME *nm = X509_get_issuer_name(x);
2041
2042
0
    reasons = ctx->current_reasons;
2043
0
    ok = get_crl_sk(ctx, &crl, &dcrl,
2044
0
        &issuer, &crl_score, &reasons, ctx->crls);
2045
0
    if (ok)
2046
0
        goto done;
2047
2048
    /* Lookup CRLs from store */
2049
0
    skcrl = ctx->lookup_crls(ctx, nm);
2050
2051
    /* If no CRLs found and a near match from get_crl_sk use that */
2052
0
    if (skcrl == NULL && crl != NULL)
2053
0
        goto done;
2054
2055
0
    get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
2056
2057
0
    sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
2058
2059
0
done:
2060
    /* If we got any kind of CRL use it and return success */
2061
0
    if (crl != NULL) {
2062
0
        ctx->current_issuer = issuer;
2063
0
        ctx->current_crl_score = crl_score;
2064
0
        ctx->current_reasons = reasons;
2065
0
        *pcrl = crl;
2066
0
        *pdcrl = dcrl;
2067
0
        return 1;
2068
0
    }
2069
0
    return 0;
2070
0
}
2071
2072
/* Check CRL validity */
2073
static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
2074
0
{
2075
0
    X509 *issuer = NULL;
2076
0
    EVP_PKEY *ikey = NULL;
2077
0
    int cnum = ctx->error_depth;
2078
0
    int chnum = sk_X509_num(ctx->chain) - 1;
2079
2080
0
    ctx->current_crl = crl;
2081
2082
    /* If we have an alternative CRL issuer cert use that */
2083
0
    if (ctx->current_issuer != NULL) {
2084
0
        issuer = ctx->current_issuer;
2085
        /*
2086
         * Else find CRL issuer: if not last certificate then issuer is next
2087
         * certificate in chain.
2088
         */
2089
0
    } else if (cnum < chnum) {
2090
0
        issuer = sk_X509_value(ctx->chain, cnum + 1);
2091
0
    } else {
2092
0
        issuer = sk_X509_value(ctx->chain, chnum);
2093
0
        if (!ossl_assert(issuer != NULL))
2094
0
            return 0;
2095
        /* If not self-issued, can't check signature */
2096
0
        if (!ctx->check_issued(ctx, issuer, issuer) && !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER))
2097
0
            return 0;
2098
0
    }
2099
2100
0
    if (issuer == NULL)
2101
0
        return 1;
2102
2103
    /*
2104
     * Skip most tests for deltas because they have already been done
2105
     */
2106
0
    if (crl->base_crl_number == NULL) {
2107
        /* Check for cRLSign bit if keyUsage present */
2108
0
        if ((issuer->ex_flags & EXFLAG_KUSAGE) != 0 && (issuer->ex_kusage & KU_CRL_SIGN) == 0 && !verify_cb_crl(ctx, X509_V_ERR_KEYUSAGE_NO_CRL_SIGN))
2109
0
            return 0;
2110
2111
0
        if ((ctx->current_crl_score & CRL_SCORE_SCOPE) == 0 && !verify_cb_crl(ctx, X509_V_ERR_DIFFERENT_CRL_SCOPE))
2112
0
            return 0;
2113
2114
0
        if ((ctx->current_crl_score & CRL_SCORE_SAME_PATH) == 0 && check_crl_path(ctx, ctx->current_issuer) <= 0 && !verify_cb_crl(ctx, X509_V_ERR_CRL_PATH_VALIDATION_ERROR))
2115
0
            return 0;
2116
2117
0
        if ((crl->idp_flags & IDP_INVALID) != 0 && !verify_cb_crl(ctx, X509_V_ERR_INVALID_EXTENSION))
2118
0
            return 0;
2119
0
    }
2120
2121
0
    if ((ctx->current_crl_score & CRL_SCORE_TIME) == 0 && !ossl_x509_check_crl_time(ctx, crl, 1))
2122
0
        return 0;
2123
2124
    /* Attempt to get issuer certificate public key */
2125
0
    ikey = X509_get0_pubkey(issuer);
2126
0
    if (ikey == NULL && !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY))
2127
0
        return 0;
2128
2129
0
    if (ikey != NULL) {
2130
0
        int rv = X509_CRL_check_suiteb(crl, ikey, ctx->param->flags);
2131
2132
0
        if (rv != X509_V_OK && !verify_cb_crl(ctx, rv))
2133
0
            return 0;
2134
        /* Verify CRL signature */
2135
0
        if (X509_CRL_verify(crl, ikey) <= 0 && !verify_cb_crl(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE))
2136
0
            return 0;
2137
0
    }
2138
0
    return 1;
2139
0
}
2140
2141
/* Check certificate against CRL */
2142
static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
2143
0
{
2144
0
    X509_REVOKED *rev;
2145
2146
    /*
2147
     * The rules changed for this... previously if a CRL contained unhandled
2148
     * critical extensions it could still be used to indicate a certificate
2149
     * was revoked. This has since been changed since critical extensions can
2150
     * change the meaning of CRL entries.
2151
     */
2152
0
    if ((ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) == 0
2153
0
        && (crl->flags & EXFLAG_CRITICAL) != 0 && !verify_cb_crl(ctx, X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION))
2154
0
        return 0;
2155
    /*
2156
     * Look for serial number of certificate in CRL.  If found, make sure
2157
     * reason is not removeFromCRL.
2158
     */
2159
0
    if (X509_CRL_get0_by_cert(crl, &rev, x)) {
2160
0
        if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
2161
0
            return 2;
2162
0
        if (!verify_cb_crl(ctx, X509_V_ERR_CERT_REVOKED))
2163
0
            return 0;
2164
0
    }
2165
2166
0
    return 1;
2167
0
}
2168
2169
/* Sadly, returns 0 also on internal error in ctx->verify_cb(). */
2170
static int check_policy(X509_STORE_CTX *ctx)
2171
0
{
2172
0
    int ret;
2173
2174
0
    if (ctx->parent)
2175
0
        return 1;
2176
    /*
2177
     * With DANE, the trust anchor might be a bare public key, not a
2178
     * certificate!  In that case our chain does not have the trust anchor
2179
     * certificate as a top-most element.  This comports well with RFC5280
2180
     * chain verification, since there too, the trust anchor is not part of the
2181
     * chain to be verified.  In particular, X509_policy_check() does not look
2182
     * at the TA cert, but assumes that it is present as the top-most chain
2183
     * element.  We therefore temporarily push a NULL cert onto the chain if it
2184
     * was verified via a bare public key, and pop it off right after the
2185
     * X509_policy_check() call.
2186
     */
2187
0
    if (ctx->bare_ta_signed && !sk_X509_push(ctx->chain, NULL)) {
2188
0
        ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
2189
0
        goto memerr;
2190
0
    }
2191
0
    ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
2192
0
        ctx->param->policies, ctx->param->flags);
2193
0
    if (ctx->bare_ta_signed)
2194
0
        (void)sk_X509_pop(ctx->chain);
2195
2196
0
    if (ret == X509_PCY_TREE_INTERNAL) {
2197
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2198
0
        goto memerr;
2199
0
    }
2200
    /* Invalid or inconsistent extensions */
2201
0
    if (ret == X509_PCY_TREE_INVALID) {
2202
0
        int i, cbcalled = 0;
2203
2204
        /* Locate certificates with bad extensions and notify callback. */
2205
0
        for (i = 0; i < sk_X509_num(ctx->chain); i++) {
2206
0
            X509 *x = sk_X509_value(ctx->chain, i);
2207
2208
0
            if ((x->ex_flags & EXFLAG_INVALID_POLICY) != 0)
2209
0
                cbcalled = 1;
2210
0
            CB_FAIL_IF((x->ex_flags & EXFLAG_INVALID_POLICY) != 0,
2211
0
                ctx, x, i, X509_V_ERR_INVALID_POLICY_EXTENSION);
2212
0
        }
2213
0
        if (!cbcalled) {
2214
            /* Should not be able to get here */
2215
0
            ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
2216
0
            return 0;
2217
0
        }
2218
        /* The callback ignored the error so we return success */
2219
0
        return 1;
2220
0
    }
2221
0
    if (ret == X509_PCY_TREE_FAILURE) {
2222
0
        ctx->current_cert = NULL;
2223
0
        ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
2224
0
        return ctx->verify_cb(0, ctx);
2225
0
    }
2226
0
    if (ret != X509_PCY_TREE_VALID) {
2227
0
        ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
2228
0
        return 0;
2229
0
    }
2230
2231
0
    if ((ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) != 0) {
2232
0
        ctx->current_cert = NULL;
2233
        /*
2234
         * Verification errors need to be "sticky", a callback may have allowed
2235
         * an SSL handshake to continue despite an error, and we must then
2236
         * remain in an error state.  Therefore, we MUST NOT clear earlier
2237
         * verification errors by setting the error to X509_V_OK.
2238
         */
2239
0
        if (!ctx->verify_cb(2, ctx))
2240
0
            return 0;
2241
0
    }
2242
2243
0
    return 1;
2244
2245
0
memerr:
2246
0
    ctx->error = X509_V_ERR_OUT_OF_MEM;
2247
0
    return -1;
2248
0
}
2249
2250
/*-
2251
 * Check certificate validity times.
2252
 *
2253
 * Returns 1 if the certificate |x| is temporally valid at the
2254
 * verification time requested by |vpm|, or 0 otherwise. if |error| is
2255
 * non-NULL, |*error| will be set to 0 when the certificate is
2256
 * temporally valid, otherwise it will be set to a non-zero error
2257
 * code.
2258
 */
2259
int X509_check_certificate_times(const X509_VERIFY_PARAM *vpm, const X509 *x,
2260
    int *error)
2261
0
{
2262
0
    int ret = 0, err = 0;
2263
0
    int64_t notafter_seconds, notbefore_seconds, verification_time;
2264
2265
0
    if (!get_verification_time(vpm, &verification_time)) {
2266
0
        ret = 1;
2267
0
        goto done;
2268
0
    }
2269
2270
0
    if (!certificate_time_to_posix(X509_get0_notBefore(x), &notbefore_seconds)) {
2271
0
        err = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
2272
0
        goto done;
2273
0
    }
2274
2275
0
    if (verification_time < notbefore_seconds) {
2276
0
        err = X509_V_ERR_CERT_NOT_YET_VALID;
2277
0
        goto done;
2278
0
    }
2279
2280
0
    if (!certificate_time_to_posix(X509_get0_notAfter(x), &notafter_seconds)) {
2281
0
        err = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
2282
0
        goto done;
2283
0
    }
2284
2285
    /*
2286
     * RFC 5280 4.1.2.5:
2287
     * To indicate that a certificate has no well-defined expiration date,
2288
     * the notAfter SHOULD be assigned the GeneralizedTime value of
2289
     * 99991231235959Z. This is INT64_C(253402300799) in epoch seconds.
2290
     */
2291
0
    if (notafter_seconds == INT64_C(253402300799)) {
2292
0
        ret = 1;
2293
0
        goto done;
2294
0
    }
2295
2296
0
    if (verification_time > notafter_seconds) {
2297
0
        err = X509_V_ERR_CERT_HAS_EXPIRED;
2298
0
        goto done;
2299
0
    }
2300
2301
0
    ret = 1;
2302
2303
0
done:
2304
0
    if (error != NULL)
2305
0
        *error = err;
2306
2307
0
    return ret;
2308
0
}
2309
2310
/*-
2311
 * Check certificate validity times.
2312
 * If depth >= 0, invoke verification callbacks on error, otherwise just return
2313
 * the validation status.
2314
 *
2315
 * Return 1 on success, 0 otherwise.
2316
 * Sadly, returns 0 also on internal error in ctx->verify_cb().
2317
 */
2318
int ossl_x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int depth)
2319
0
{
2320
0
    const X509_VERIFY_PARAM *vpm = ctx->param;
2321
0
    int64_t notafter_seconds, notbefore_seconds, verification_time;
2322
0
    int err;
2323
2324
0
    if (!get_verification_time(vpm, &verification_time))
2325
0
        return 1;
2326
2327
0
    if (!certificate_time_to_posix(X509_get0_notBefore(x), &notbefore_seconds)) {
2328
0
        err = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
2329
0
        if (depth < 0 || verify_cb_cert(ctx, x, depth, err) == 0)
2330
0
            return 0;
2331
0
    } else if (verification_time < notbefore_seconds) {
2332
0
        err = X509_V_ERR_CERT_NOT_YET_VALID;
2333
0
        if (depth < 0 || verify_cb_cert(ctx, x, depth, err) == 0)
2334
0
            return 0;
2335
0
    }
2336
2337
0
    if (!certificate_time_to_posix(X509_get0_notAfter(x), &notafter_seconds)) {
2338
0
        err = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
2339
0
        if (depth < 0 || verify_cb_cert(ctx, x, depth, err) == 0)
2340
0
            return 0;
2341
0
    } else {
2342
        /*
2343
         * RFC 5280 4.1.2.5:
2344
         * To indicate that a certificate has no well-defined expiration date,
2345
         * the notAfter SHOULD be assigned the GeneralizedTime value of
2346
         * 99991231235959Z. This is INT64_C(253402300799) in epoch seconds.
2347
         */
2348
0
        if (notafter_seconds == INT64_C(253402300799))
2349
0
            return 1;
2350
0
        if (verification_time > notafter_seconds) {
2351
0
            err = X509_V_ERR_CERT_HAS_EXPIRED;
2352
0
            if (depth < 0 || verify_cb_cert(ctx, x, depth, err) == 0)
2353
0
                return 0;
2354
0
        }
2355
0
    }
2356
2357
0
    return 1;
2358
0
}
2359
2360
/*
2361
 * Verify the issuer signatures and cert times of ctx->chain.
2362
 * Sadly, returns 0 also on internal error in ctx->verify_cb().
2363
 */
2364
static int internal_verify(X509_STORE_CTX *ctx)
2365
0
{
2366
0
    int n;
2367
0
    X509 *xi;
2368
0
    X509 *xs;
2369
2370
    /* For RPK: just do the verify callback */
2371
0
    if (ctx->rpk != NULL) {
2372
0
        if (!ctx->verify_cb(ctx->error == X509_V_OK, ctx))
2373
0
            return 0;
2374
0
        return 1;
2375
0
    }
2376
0
    n = sk_X509_num(ctx->chain) - 1;
2377
0
    xi = sk_X509_value(ctx->chain, n);
2378
0
    xs = xi;
2379
2380
0
    ctx->error_depth = n;
2381
0
    if (ctx->bare_ta_signed) {
2382
        /*
2383
         * With DANE-verified bare public key TA signatures,
2384
         * on the top certificate we check only the timestamps.
2385
         * We report the issuer as NULL because all we have is a bare key.
2386
         */
2387
0
        xi = NULL;
2388
0
    } else if (ossl_x509_likely_issued(xi, xi) != X509_V_OK
2389
        /* exceptional case: last cert in the chain is not self-issued */
2390
0
        && ((ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) == 0)) {
2391
0
        if (n > 0) {
2392
0
            n--;
2393
0
            ctx->error_depth = n;
2394
0
            xs = sk_X509_value(ctx->chain, n);
2395
0
        } else {
2396
0
            CB_FAIL_IF(1, ctx, xi, 0,
2397
0
                X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
2398
0
        }
2399
        /*
2400
         * The below code will certainly not do a
2401
         * self-signature check on xi because it is not self-issued.
2402
         */
2403
0
    }
2404
2405
    /*
2406
     * Do not clear error (by ctx->error = X509_V_OK), it must be "sticky",
2407
     * only the user's callback is allowed to reset errors (at its own peril).
2408
     */
2409
0
    while (n >= 0) {
2410
        /*-
2411
         * For each iteration of this loop:
2412
         * n is the subject depth
2413
         * xs is the subject cert, for which the signature is to be checked
2414
         * xi is NULL for DANE-verified bare public key TA signatures
2415
         *       else the supposed issuer cert containing the public key to use
2416
         * Initially xs == xi if the last cert in the chain is self-issued.
2417
         */
2418
        /*
2419
         * Do signature check for self-signed certificates only if explicitly
2420
         * asked for because it does not add any security and just wastes time.
2421
         */
2422
0
        if (xi != NULL
2423
0
            && (xs != xi
2424
0
                || ((ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE) != 0
2425
0
                    && (xi->ex_flags & EXFLAG_SS) != 0))) {
2426
0
            EVP_PKEY *pkey;
2427
            /*
2428
             * If the issuer's public key is not available or its key usage
2429
             * does not support issuing the subject cert, report the issuer
2430
             * cert and its depth (rather than n, the depth of the subject).
2431
             */
2432
0
            int issuer_depth = n + (xs == xi ? 0 : 1);
2433
            /*
2434
             * According to https://tools.ietf.org/html/rfc5280#section-6.1.4
2435
             * step (n) we must check any given key usage extension in a CA cert
2436
             * when preparing the verification of a certificate issued by it.
2437
             * According to https://tools.ietf.org/html/rfc5280#section-4.2.1.3
2438
             * we must not verify a certificate signature if the key usage of
2439
             * the CA certificate that issued the certificate prohibits signing.
2440
             * In case the 'issuing' certificate is the last in the chain and is
2441
             * not a CA certificate but a 'self-issued' end-entity cert (i.e.,
2442
             * xs == xi && !(xi->ex_flags & EXFLAG_CA)) RFC 5280 does not apply
2443
             * (see https://tools.ietf.org/html/rfc6818#section-2) and thus
2444
             * we are free to ignore any key usage restrictions on such certs.
2445
             */
2446
0
            int ret = xs == xi && (xi->ex_flags & EXFLAG_CA) == 0
2447
0
                ? X509_V_OK
2448
0
                : ossl_x509_signing_allowed(xi, xs);
2449
2450
0
            CB_FAIL_IF(ret != X509_V_OK, ctx, xi, issuer_depth, ret);
2451
0
            if ((pkey = X509_get0_pubkey(xi)) == NULL) {
2452
0
                CB_FAIL_IF(1, ctx, xi, issuer_depth,
2453
0
                    X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY);
2454
0
            } else {
2455
0
                CB_FAIL_IF(X509_verify(xs, pkey) <= 0,
2456
0
                    ctx, xs, n, X509_V_ERR_CERT_SIGNATURE_FAILURE);
2457
0
            }
2458
0
        }
2459
2460
        /* In addition to RFC 5280 requirements do also for trust anchor cert */
2461
        /* Calls verify callback as needed */
2462
0
        if (!ossl_x509_check_cert_time(ctx, xs, n))
2463
0
            return 0;
2464
2465
        /*
2466
         * Signal success at this depth.  However, the previous error (if any)
2467
         * is retained.
2468
         */
2469
0
        ctx->current_issuer = xi;
2470
0
        ctx->current_cert = xs;
2471
0
        ctx->error_depth = n;
2472
0
        if (!ctx->verify_cb(1, ctx))
2473
0
            return 0;
2474
2475
0
        if (--n >= 0) {
2476
0
            xi = xs;
2477
0
            xs = sk_X509_value(ctx->chain, n);
2478
0
        }
2479
0
    }
2480
0
    return 1;
2481
0
}
2482
2483
#if !defined(OPENSSL_NO_DEPRECATED_4_0)
2484
int X509_cmp_current_time(const ASN1_TIME *ctm)
2485
0
{
2486
0
    return X509_cmp_time(ctm, NULL);
2487
0
}
2488
2489
/* returns 0 on error, otherwise 1 if ctm > cmp_time, else -1 */
2490
int X509_cmp_time(const ASN1_TIME *ctm, const time_t *cmp_time)
2491
0
{
2492
0
    int64_t cert_time, posix_time = cmp_time == NULL ? (int64_t)time(NULL) : (int64_t)*cmp_time;
2493
2494
0
    if (!certificate_time_to_posix(ctm, &cert_time))
2495
0
        return 0;
2496
2497
0
    if (cert_time > posix_time)
2498
0
        return 1;
2499
2500
    /* It's tradition, that makes it OK. Hyrum's law bites forever */
2501
0
    return -1;
2502
0
}
2503
2504
/*
2505
 * Return 0 if time should not be checked or reference time is in range,
2506
 * or else 1 if it is past the end, or -1 if it is before the start
2507
 * treats invalid start and end as times infinitely in the past or
2508
 * future, respectively. Do not use on untrusted input (meaning
2509
 * do not use this when validating certificates for actual use)
2510
 */
2511
int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
2512
    const ASN1_TIME *start, const ASN1_TIME *end)
2513
0
{
2514
0
    unsigned long flags = vpm == NULL ? 0 : X509_VERIFY_PARAM_get_flags(vpm);
2515
0
    time_t ref_time;
2516
0
    time_t *time = NULL;
2517
2518
0
    if ((flags & X509_V_FLAG_USE_CHECK_TIME) != 0) {
2519
0
        ref_time = X509_VERIFY_PARAM_get_time(vpm);
2520
0
        time = &ref_time;
2521
0
    } else if ((flags & X509_V_FLAG_NO_CHECK_TIME) != 0) {
2522
0
        return 0; /* this means ok */
2523
0
    } /* else reference time is the current time */
2524
2525
    /*
2526
     * XXX this is public API so we have the entertaining property
2527
     * that invalid asn1 times for |start| or |end| are effectively
2528
     * treated as infinitely in the past or future, due to the use
2529
     * X509_cmp_time, and the 0 return for an invalid time.
2530
     *
2531
     * Treating NULL as infinite a bit off but probably mostly harmless
2532
     * in practice because X509_get0_notBefore and friends do not
2533
     * return NULL. However, if you can end up using a cert with an
2534
     * invalid time that whatever signed it did not validate it in a
2535
     * compatible way with us, You can end up with infinite validity
2536
     * when you did not expect it. Depending on how you got the
2537
     * certificate and what you are doing based upon this decision
2538
     * this could have undesirable consequences.
2539
     *
2540
     * (invalid) (invalid) -> 0;
2541
     * start (invalid) -> returns 0 if start if after time
2542
     * (invalid) end -> returns 0 if end is before time
2543
     *
2544
     * So for better or worse we keep this the way it is and update
2545
     * the documentation accordingly.
2546
     */
2547
0
    if (end != NULL && X509_cmp_time(end, time) < 0)
2548
0
        return 1;
2549
0
    if (start != NULL && X509_cmp_time(start, time) > 0)
2550
0
        return -1;
2551
0
    return 0;
2552
0
}
2553
#endif /* !defined(OPENSSL_NO_DEPRECATED_4_0) */
2554
2555
ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
2556
0
{
2557
0
    return X509_time_adj(s, adj, NULL);
2558
0
}
2559
2560
ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, const time_t *in_tm)
2561
0
{
2562
0
    return X509_time_adj_ex(s, 0, offset_sec, in_tm);
2563
0
}
2564
2565
ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
2566
    int offset_day, long offset_sec, const time_t *in_tm)
2567
0
{
2568
0
    time_t t;
2569
2570
0
    if (in_tm)
2571
0
        t = *in_tm;
2572
0
    else
2573
0
        time(&t);
2574
2575
0
    if (s != NULL && (s->flags & ASN1_STRING_FLAG_MSTRING) == 0) {
2576
0
        if (s->type == V_ASN1_UTCTIME)
2577
0
            return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
2578
0
        if (s->type == V_ASN1_GENERALIZEDTIME)
2579
0
            return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
2580
0
    }
2581
0
    return ASN1_TIME_adj(s, t, offset_day, offset_sec);
2582
0
}
2583
2584
/* Copy any missing public key parameters up the chain towards pkey */
2585
int X509_get_pubkey_parameters(EVP_PKEY *pkey, const STACK_OF(X509) *chain)
2586
0
{
2587
0
    EVP_PKEY *ktmp = NULL, *ktmp2;
2588
0
    int i, j;
2589
2590
0
    if (pkey != NULL && !EVP_PKEY_missing_parameters(pkey))
2591
0
        return 1;
2592
2593
0
    for (i = 0; i < sk_X509_num(chain); i++) {
2594
0
        ktmp = X509_get0_pubkey(sk_X509_value(chain, i));
2595
0
        if (ktmp == NULL) {
2596
0
            ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
2597
0
            return 0;
2598
0
        }
2599
0
        if (!EVP_PKEY_missing_parameters(ktmp))
2600
0
            break;
2601
0
        ktmp = NULL;
2602
0
    }
2603
0
    if (ktmp == NULL) {
2604
0
        ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
2605
0
        return 0;
2606
0
    }
2607
2608
    /* first, populate the other certs */
2609
0
    for (j = i - 1; j >= 0; j--) {
2610
0
        ktmp2 = X509_get0_pubkey(sk_X509_value(chain, j));
2611
0
        if (!EVP_PKEY_copy_parameters(ktmp2, ktmp))
2612
0
            return 0;
2613
0
    }
2614
2615
0
    if (pkey != NULL)
2616
0
        return EVP_PKEY_copy_parameters(pkey, ktmp);
2617
0
    return 1;
2618
0
}
2619
2620
/*
2621
 * Make a delta CRL as the difference between two full CRLs.
2622
 * Sadly, returns NULL also on internal error.
2623
 */
2624
X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
2625
    EVP_PKEY *skey, const EVP_MD *md, unsigned int flags)
2626
0
{
2627
0
    X509_CRL *crl = NULL;
2628
0
    int i;
2629
0
    STACK_OF(X509_REVOKED) *revs = NULL;
2630
2631
    /* CRLs can't be delta already */
2632
0
    if (base->base_crl_number != NULL || newer->base_crl_number != NULL) {
2633
0
        ERR_raise(ERR_LIB_X509, X509_R_CRL_ALREADY_DELTA);
2634
0
        return NULL;
2635
0
    }
2636
    /* Base and new CRL must have a CRL number */
2637
0
    if (base->crl_number == NULL || newer->crl_number == NULL) {
2638
0
        ERR_raise(ERR_LIB_X509, X509_R_NO_CRL_NUMBER);
2639
0
        return NULL;
2640
0
    }
2641
    /* Issuer names must match */
2642
0
    if (X509_NAME_cmp(X509_CRL_get_issuer(base),
2643
0
            X509_CRL_get_issuer(newer))
2644
0
        != 0) {
2645
0
        ERR_raise(ERR_LIB_X509, X509_R_ISSUER_MISMATCH);
2646
0
        return NULL;
2647
0
    }
2648
    /* AKID and IDP must match */
2649
0
    if (!crl_extension_match(base, newer, NID_authority_key_identifier)) {
2650
0
        ERR_raise(ERR_LIB_X509, X509_R_AKID_MISMATCH);
2651
0
        return NULL;
2652
0
    }
2653
0
    if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) {
2654
0
        ERR_raise(ERR_LIB_X509, X509_R_IDP_MISMATCH);
2655
0
        return NULL;
2656
0
    }
2657
    /* Newer CRL number must exceed full CRL number */
2658
0
    if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) {
2659
0
        ERR_raise(ERR_LIB_X509, X509_R_NEWER_CRL_NOT_NEWER);
2660
0
        return NULL;
2661
0
    }
2662
    /* CRLs must verify */
2663
0
    if (skey != NULL && (X509_CRL_verify(base, skey) <= 0 || X509_CRL_verify(newer, skey) <= 0)) {
2664
0
        ERR_raise(ERR_LIB_X509, X509_R_CRL_VERIFY_FAILURE);
2665
0
        return NULL;
2666
0
    }
2667
    /* Create new CRL */
2668
0
    crl = X509_CRL_new_ex(base->libctx, base->propq);
2669
0
    if (crl == NULL || !X509_CRL_set_version(crl, X509_CRL_VERSION_2)) {
2670
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2671
0
        goto err;
2672
0
    }
2673
    /* Set issuer name */
2674
0
    if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer))) {
2675
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2676
0
        goto err;
2677
0
    }
2678
2679
0
    if (!X509_CRL_set1_lastUpdate(crl, X509_CRL_get0_lastUpdate(newer))) {
2680
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2681
0
        goto err;
2682
0
    }
2683
0
    if (!X509_CRL_set1_nextUpdate(crl, X509_CRL_get0_nextUpdate(newer))) {
2684
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2685
0
        goto err;
2686
0
    }
2687
2688
    /* Set base CRL number: must be critical */
2689
0
    if (X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0) <= 0) {
2690
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2691
0
        goto err;
2692
0
    }
2693
2694
    /*
2695
     * Copy extensions across from newest CRL to delta: this will set CRL
2696
     * number to correct value too.
2697
     */
2698
0
    for (i = 0; i < X509_CRL_get_ext_count(newer); i++) {
2699
0
        const X509_EXTENSION *ext = X509_CRL_get_ext(newer, i);
2700
0
        if (!X509_CRL_add_ext(crl, ext, -1)) {
2701
0
            ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2702
0
            goto err;
2703
0
        }
2704
0
    }
2705
2706
    /* Go through revoked entries, copying as needed */
2707
0
    revs = X509_CRL_get_REVOKED(newer);
2708
2709
0
    for (i = 0; i < sk_X509_REVOKED_num(revs); i++) {
2710
0
        X509_REVOKED *rvn, *rvtmp;
2711
2712
0
        rvn = sk_X509_REVOKED_value(revs, i);
2713
        /*
2714
         * Add only if not also in base.
2715
         * Need something cleverer here for some more complex CRLs covering
2716
         * multiple CAs.
2717
         */
2718
0
        if (!X509_CRL_get0_by_serial(base, &rvtmp, &rvn->serialNumber)) {
2719
0
            rvtmp = X509_REVOKED_dup(rvn);
2720
0
            if (rvtmp == NULL) {
2721
0
                ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
2722
0
                goto err;
2723
0
            }
2724
0
            if (!X509_CRL_add0_revoked(crl, rvtmp)) {
2725
0
                X509_REVOKED_free(rvtmp);
2726
0
                ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2727
0
                goto err;
2728
0
            }
2729
0
        }
2730
0
    }
2731
2732
0
    if (skey != NULL && md != NULL && !X509_CRL_sign(crl, skey, md)) {
2733
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2734
0
        goto err;
2735
0
    }
2736
2737
0
    return crl;
2738
2739
0
err:
2740
0
    X509_CRL_free(crl);
2741
0
    return NULL;
2742
0
}
2743
2744
int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
2745
0
{
2746
0
    return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
2747
0
}
2748
2749
void *X509_STORE_CTX_get_ex_data(const X509_STORE_CTX *ctx, int idx)
2750
0
{
2751
0
    return CRYPTO_get_ex_data(&ctx->ex_data, idx);
2752
0
}
2753
2754
int X509_STORE_CTX_get_error(const X509_STORE_CTX *ctx)
2755
0
{
2756
0
    return ctx->error;
2757
0
}
2758
2759
void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
2760
0
{
2761
0
    ctx->error = err;
2762
0
}
2763
2764
int X509_STORE_CTX_get_error_depth(const X509_STORE_CTX *ctx)
2765
0
{
2766
0
    return ctx->error_depth;
2767
0
}
2768
2769
void X509_STORE_CTX_set_error_depth(X509_STORE_CTX *ctx, int depth)
2770
0
{
2771
0
    ctx->error_depth = depth;
2772
0
}
2773
2774
X509 *X509_STORE_CTX_get_current_cert(const X509_STORE_CTX *ctx)
2775
0
{
2776
0
    return ctx->current_cert;
2777
0
}
2778
2779
void X509_STORE_CTX_set_current_cert(X509_STORE_CTX *ctx, X509 *x)
2780
0
{
2781
0
    ctx->current_cert = x;
2782
0
}
2783
2784
STACK_OF(X509) *X509_STORE_CTX_get0_chain(const X509_STORE_CTX *ctx)
2785
0
{
2786
0
    return ctx->chain;
2787
0
}
2788
2789
STACK_OF(X509) *X509_STORE_CTX_get1_chain(const X509_STORE_CTX *ctx)
2790
0
{
2791
0
    if (ctx->chain == NULL)
2792
0
        return NULL;
2793
0
    return X509_chain_up_ref(ctx->chain);
2794
0
}
2795
2796
X509 *X509_STORE_CTX_get0_current_issuer(const X509_STORE_CTX *ctx)
2797
0
{
2798
0
    return ctx->current_issuer;
2799
0
}
2800
2801
X509_CRL *X509_STORE_CTX_get0_current_crl(const X509_STORE_CTX *ctx)
2802
0
{
2803
0
    return ctx->current_crl;
2804
0
}
2805
2806
X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(const X509_STORE_CTX *ctx)
2807
0
{
2808
0
    return ctx->parent;
2809
0
}
2810
2811
void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
2812
0
{
2813
0
    ctx->cert = x;
2814
0
}
2815
2816
void X509_STORE_CTX_set0_rpk(X509_STORE_CTX *ctx, EVP_PKEY *rpk)
2817
0
{
2818
0
    ctx->rpk = rpk;
2819
0
}
2820
2821
void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
2822
0
{
2823
0
    ctx->crls = sk;
2824
0
}
2825
2826
#ifndef OPENSSL_NO_OCSP
2827
void X509_STORE_CTX_set_ocsp_resp(X509_STORE_CTX *ctx, STACK_OF(OCSP_RESPONSE) *sk)
2828
0
{
2829
0
    ctx->ocsp_resp = sk;
2830
0
}
2831
#endif
2832
2833
int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
2834
0
{
2835
    /*
2836
     * XXX: Why isn't this function always used to set the associated trust?
2837
     * Should there even be a VPM->trust field at all?  Or should the trust
2838
     * always be inferred from the purpose by X509_STORE_CTX_init().
2839
     */
2840
0
    return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
2841
0
}
2842
2843
int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
2844
0
{
2845
    /*
2846
     * XXX: See above, this function would only be needed when the default
2847
     * trust for the purpose needs an override in a corner case.
2848
     */
2849
0
    return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
2850
0
}
2851
2852
/*
2853
 * Use this function to set the X509_STORE_CTX purpose and/or trust id values.
2854
 * The |def_purpose| argument is used if the given purpose value is 0.
2855
 * The |purpose| is unchanged if also the def_purpose argument is 0.
2856
 * The |trust| is unchanged if the given trust value is X509_TRUST_DEFAULT.
2857
 * This is intended to be used when another structure has its own trust and
2858
 * purpose values, which (if set) will be inherited by the |ctx|. If they aren't
2859
 * set then we will usually have a default purpose in mind, which should then
2860
 * be used to set the trust id. An example of this is SSL use: an SSL
2861
 * structure will have its own purpose and trust settings, which the
2862
 * application can set: if they aren't set then we use the default of SSL
2863
 * client/server.
2864
 */
2865
int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
2866
    int purpose, int trust)
2867
0
{
2868
0
    int idx;
2869
2870
    /* If purpose not set use default */
2871
0
    if (purpose == 0)
2872
0
        purpose = def_purpose;
2873
    /*
2874
     * If purpose is set but we don't have a default then set the default to
2875
     * the current purpose
2876
     */
2877
0
    else if (def_purpose == 0)
2878
0
        def_purpose = purpose;
2879
    /* If we have a purpose then check it is valid */
2880
0
    if (purpose != 0) {
2881
0
        X509_PURPOSE *ptmp;
2882
2883
0
        idx = X509_PURPOSE_get_by_id(purpose);
2884
0
        if (idx == -1) {
2885
0
            ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID);
2886
0
            return 0;
2887
0
        }
2888
0
        ptmp = X509_PURPOSE_get0(idx);
2889
0
        if (ptmp->trust == X509_TRUST_DEFAULT) {
2890
0
            idx = X509_PURPOSE_get_by_id(def_purpose);
2891
0
            if (idx == -1) {
2892
0
                ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID);
2893
0
                return 0;
2894
0
            }
2895
0
            ptmp = X509_PURPOSE_get0(idx);
2896
0
        }
2897
        /* If trust not set then get from purpose default */
2898
0
        if (trust == X509_TRUST_DEFAULT)
2899
0
            trust = ptmp->trust;
2900
0
    }
2901
0
    if (trust != X509_TRUST_DEFAULT) {
2902
0
        idx = X509_TRUST_get_by_id(trust);
2903
0
        if (idx == -1) {
2904
0
            ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_TRUST_ID);
2905
0
            return 0;
2906
0
        }
2907
0
    }
2908
2909
0
    if (ctx->param->purpose == 0 && purpose != 0)
2910
0
        ctx->param->purpose = purpose;
2911
0
    if (ctx->param->trust == X509_TRUST_DEFAULT && trust != X509_TRUST_DEFAULT)
2912
0
        ctx->param->trust = trust;
2913
0
    return 1;
2914
0
}
2915
2916
X509_STORE_CTX *X509_STORE_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq)
2917
0
{
2918
0
    X509_STORE_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
2919
2920
0
    if (ctx == NULL)
2921
0
        return NULL;
2922
2923
0
    ctx->libctx = libctx;
2924
0
    if (propq != NULL) {
2925
0
        ctx->propq = OPENSSL_strdup(propq);
2926
0
        if (ctx->propq == NULL) {
2927
0
            OPENSSL_free(ctx);
2928
0
            return NULL;
2929
0
        }
2930
0
    }
2931
2932
0
    return ctx;
2933
0
}
2934
2935
X509_STORE_CTX *X509_STORE_CTX_new(void)
2936
0
{
2937
0
    return X509_STORE_CTX_new_ex(NULL, NULL);
2938
0
}
2939
2940
void X509_STORE_CTX_free(X509_STORE_CTX *ctx)
2941
0
{
2942
0
    if (ctx == NULL)
2943
0
        return;
2944
2945
0
    X509_STORE_CTX_cleanup(ctx);
2946
2947
    /* libctx and propq survive X509_STORE_CTX_cleanup() */
2948
0
    OPENSSL_free(ctx->propq);
2949
0
    OPENSSL_free(ctx);
2950
0
}
2951
2952
int X509_STORE_CTX_init_rpk(X509_STORE_CTX *ctx, X509_STORE *store, EVP_PKEY *rpk)
2953
0
{
2954
0
    if (!X509_STORE_CTX_init(ctx, store, NULL, NULL))
2955
0
        return 0;
2956
0
    ctx->rpk = rpk;
2957
0
    return 1;
2958
0
}
2959
2960
int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, const X509 *x509,
2961
    STACK_OF(X509) *chain)
2962
0
{
2963
0
    if (ctx == NULL) {
2964
0
        ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
2965
0
        return 0;
2966
0
    }
2967
0
    X509_STORE_CTX_cleanup(ctx);
2968
2969
0
    ctx->store = store;
2970
0
    ctx->cert = (X509 *)x509; /* XXX casts away const */
2971
0
    ctx->untrusted = chain;
2972
0
    ctx->crls = NULL;
2973
0
    ctx->num_untrusted = 0;
2974
0
    ctx->other_ctx = NULL;
2975
0
    ctx->valid = 0;
2976
0
    ctx->chain = NULL;
2977
0
    ctx->error = X509_V_OK;
2978
0
    ctx->explicit_policy = 0;
2979
0
    ctx->error_depth = 0;
2980
0
    ctx->current_cert = NULL;
2981
0
    ctx->current_issuer = NULL;
2982
0
    ctx->current_crl = NULL;
2983
0
    ctx->current_crl_score = 0;
2984
0
    ctx->current_reasons = 0;
2985
0
    ctx->tree = NULL;
2986
0
    ctx->parent = NULL;
2987
0
    ctx->dane = NULL;
2988
0
    ctx->bare_ta_signed = 0;
2989
0
    ctx->rpk = NULL;
2990
    /* Zero ex_data to make sure we're cleanup-safe */
2991
0
    memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2992
0
    ctx->ocsp_resp = NULL;
2993
2994
    /* store->cleanup is always 0 in OpenSSL, if set must be idempotent */
2995
0
    if (store != NULL)
2996
0
        ctx->cleanup = store->cleanup;
2997
0
    else
2998
0
        ctx->cleanup = NULL;
2999
3000
0
    if (store != NULL && store->check_issued != NULL)
3001
0
        ctx->check_issued = store->check_issued;
3002
0
    else
3003
0
        ctx->check_issued = check_issued;
3004
3005
0
    if (store != NULL && store->get_issuer != NULL)
3006
0
        ctx->get_issuer = store->get_issuer;
3007
0
    else
3008
0
        ctx->get_issuer = X509_STORE_CTX_get1_issuer;
3009
3010
0
    if (store != NULL && store->verify_cb != NULL)
3011
0
        ctx->verify_cb = store->verify_cb;
3012
0
    else
3013
0
        ctx->verify_cb = null_callback;
3014
3015
0
    if (store != NULL && store->verify != NULL)
3016
0
        ctx->verify = store->verify;
3017
0
    else
3018
0
        ctx->verify = internal_verify;
3019
3020
0
    if (store != NULL && store->check_revocation != NULL)
3021
0
        ctx->check_revocation = store->check_revocation;
3022
0
    else
3023
0
        ctx->check_revocation = check_revocation;
3024
3025
0
    if (store != NULL && store->get_crl != NULL)
3026
0
        ctx->get_crl = store->get_crl;
3027
0
    else
3028
0
        ctx->get_crl = NULL;
3029
3030
0
    if (store != NULL && store->check_crl != NULL)
3031
0
        ctx->check_crl = store->check_crl;
3032
0
    else
3033
0
        ctx->check_crl = check_crl;
3034
3035
0
    if (store != NULL && store->cert_crl != NULL)
3036
0
        ctx->cert_crl = store->cert_crl;
3037
0
    else
3038
0
        ctx->cert_crl = cert_crl;
3039
3040
0
    if (store != NULL && store->check_policy != NULL)
3041
0
        ctx->check_policy = store->check_policy;
3042
0
    else
3043
0
        ctx->check_policy = check_policy;
3044
3045
0
    if (store != NULL && store->lookup_certs != NULL)
3046
0
        ctx->lookup_certs = store->lookup_certs;
3047
0
    else
3048
0
        ctx->lookup_certs = X509_STORE_CTX_get1_certs;
3049
3050
0
    if (store != NULL && store->lookup_crls != NULL)
3051
0
        ctx->lookup_crls = store->lookup_crls;
3052
0
    else
3053
0
        ctx->lookup_crls = X509_STORE_CTX_get1_crls;
3054
3055
0
    ctx->param = X509_VERIFY_PARAM_new();
3056
0
    if (ctx->param == NULL) {
3057
0
        ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
3058
0
        goto err;
3059
0
    }
3060
3061
    /* Inherit callbacks and flags from X509_STORE if not set use defaults. */
3062
0
    if (store == NULL)
3063
0
        ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE;
3064
0
    else if (X509_VERIFY_PARAM_inherit(ctx->param, store->param) == 0)
3065
0
        goto err;
3066
3067
0
    if (!X509_STORE_CTX_set_default(ctx, "default"))
3068
0
        goto err;
3069
3070
    /*
3071
     * XXX: For now, continue to inherit trust from VPM, but infer from the
3072
     * purpose if this still yields the default value.
3073
     */
3074
0
    if (ctx->param->trust == X509_TRUST_DEFAULT) {
3075
0
        int idx = X509_PURPOSE_get_by_id(ctx->param->purpose);
3076
0
        X509_PURPOSE *xp = X509_PURPOSE_get0(idx);
3077
3078
0
        if (xp != NULL)
3079
0
            ctx->param->trust = X509_PURPOSE_get_trust(xp);
3080
0
    }
3081
3082
0
    if (CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
3083
0
            &ctx->ex_data))
3084
0
        return 1;
3085
0
    ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
3086
3087
0
err:
3088
    /*
3089
     * On error clean up allocated storage, if the store context was not
3090
     * allocated with X509_STORE_CTX_new() this is our last chance to do so.
3091
     */
3092
0
    X509_STORE_CTX_cleanup(ctx);
3093
0
    return 0;
3094
0
}
3095
3096
/*
3097
 * Set alternative get_issuer method: just from a STACK of trusted certificates.
3098
 * This avoids the complexity of X509_STORE where it is not needed.
3099
 */
3100
void X509_STORE_CTX_set0_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
3101
0
{
3102
0
    ctx->other_ctx = sk;
3103
0
    ctx->get_issuer = get1_best_issuer_other_sk;
3104
0
    ctx->lookup_certs = lookup_certs_sk;
3105
0
}
3106
3107
void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
3108
0
{
3109
    /*
3110
     * We need to be idempotent because, unfortunately, free() also calls
3111
     * cleanup(), so the natural call sequence new(), init(), cleanup(), free()
3112
     * calls cleanup() for the same object twice!  Thus we must zero the
3113
     * pointers below after they're freed!
3114
     */
3115
    /* Seems to always be NULL in OpenSSL, do this at most once. */
3116
0
    if (ctx->cleanup != NULL) {
3117
0
        ctx->cleanup(ctx);
3118
0
        ctx->cleanup = NULL;
3119
0
    }
3120
0
    if (ctx->param != NULL) {
3121
0
        if (ctx->parent == NULL)
3122
0
            X509_VERIFY_PARAM_free(ctx->param);
3123
0
        ctx->param = NULL;
3124
0
    }
3125
0
    X509_policy_tree_free(ctx->tree);
3126
0
    ctx->tree = NULL;
3127
0
    OSSL_STACK_OF_X509_free(ctx->chain);
3128
0
    ctx->chain = NULL;
3129
0
    CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data));
3130
0
    memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
3131
0
}
3132
3133
void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
3134
0
{
3135
0
    X509_VERIFY_PARAM_set_depth(ctx->param, depth);
3136
0
}
3137
3138
void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
3139
0
{
3140
0
    X509_VERIFY_PARAM_set_flags(ctx->param, flags);
3141
0
}
3142
3143
void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
3144
    time_t t)
3145
0
{
3146
0
    X509_VERIFY_PARAM_set_time(ctx->param, t);
3147
0
}
3148
3149
void X509_STORE_CTX_set_current_reasons(X509_STORE_CTX *ctx,
3150
    unsigned int current_reasons)
3151
0
{
3152
0
    ctx->current_reasons = current_reasons;
3153
0
}
3154
3155
X509 *X509_STORE_CTX_get0_cert(const X509_STORE_CTX *ctx)
3156
0
{
3157
0
    return ctx->cert;
3158
0
}
3159
3160
EVP_PKEY *X509_STORE_CTX_get0_rpk(const X509_STORE_CTX *ctx)
3161
0
{
3162
0
    return ctx->rpk;
3163
0
}
3164
3165
STACK_OF(X509) *X509_STORE_CTX_get0_untrusted(const X509_STORE_CTX *ctx)
3166
0
{
3167
0
    return ctx->untrusted;
3168
0
}
3169
3170
void X509_STORE_CTX_set0_untrusted(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
3171
0
{
3172
0
    ctx->untrusted = sk;
3173
0
}
3174
3175
void X509_STORE_CTX_set0_verified_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
3176
0
{
3177
0
    OSSL_STACK_OF_X509_free(ctx->chain);
3178
0
    ctx->chain = sk;
3179
0
}
3180
3181
void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
3182
    X509_STORE_CTX_verify_cb verify_cb)
3183
0
{
3184
0
    ctx->verify_cb = verify_cb;
3185
0
}
3186
3187
X509_STORE_CTX_verify_cb X509_STORE_CTX_get_verify_cb(const X509_STORE_CTX *ctx)
3188
0
{
3189
0
    return ctx->verify_cb;
3190
0
}
3191
3192
void X509_STORE_CTX_set_verify(X509_STORE_CTX *ctx,
3193
    X509_STORE_CTX_verify_fn verify)
3194
0
{
3195
0
    ctx->verify = verify;
3196
0
}
3197
3198
X509_STORE_CTX_verify_fn X509_STORE_CTX_get_verify(const X509_STORE_CTX *ctx)
3199
0
{
3200
0
    return ctx->verify;
3201
0
}
3202
3203
X509_STORE_CTX_get_issuer_fn
3204
X509_STORE_CTX_get_get_issuer(const X509_STORE_CTX *ctx)
3205
0
{
3206
0
    return ctx->get_issuer;
3207
0
}
3208
3209
X509_STORE_CTX_check_issued_fn
3210
X509_STORE_CTX_get_check_issued(const X509_STORE_CTX *ctx)
3211
0
{
3212
0
    return ctx->check_issued;
3213
0
}
3214
3215
X509_STORE_CTX_check_revocation_fn
3216
X509_STORE_CTX_get_check_revocation(const X509_STORE_CTX *ctx)
3217
0
{
3218
0
    return ctx->check_revocation;
3219
0
}
3220
3221
X509_STORE_CTX_get_crl_fn X509_STORE_CTX_get_get_crl(const X509_STORE_CTX *ctx)
3222
0
{
3223
0
    return ctx->get_crl;
3224
0
}
3225
3226
void X509_STORE_CTX_set_get_crl(X509_STORE_CTX *ctx,
3227
    X509_STORE_CTX_get_crl_fn get_crl)
3228
0
{
3229
0
    ctx->get_crl = get_crl;
3230
0
}
3231
3232
X509_STORE_CTX_check_crl_fn
3233
X509_STORE_CTX_get_check_crl(const X509_STORE_CTX *ctx)
3234
0
{
3235
0
    return ctx->check_crl;
3236
0
}
3237
3238
X509_STORE_CTX_cert_crl_fn
3239
X509_STORE_CTX_get_cert_crl(const X509_STORE_CTX *ctx)
3240
0
{
3241
0
    return ctx->cert_crl;
3242
0
}
3243
3244
X509_STORE_CTX_check_policy_fn
3245
X509_STORE_CTX_get_check_policy(const X509_STORE_CTX *ctx)
3246
0
{
3247
0
    return ctx->check_policy;
3248
0
}
3249
3250
X509_STORE_CTX_lookup_certs_fn
3251
X509_STORE_CTX_get_lookup_certs(const X509_STORE_CTX *ctx)
3252
0
{
3253
0
    return ctx->lookup_certs;
3254
0
}
3255
3256
X509_STORE_CTX_lookup_crls_fn
3257
X509_STORE_CTX_get_lookup_crls(const X509_STORE_CTX *ctx)
3258
0
{
3259
0
    return ctx->lookup_crls;
3260
0
}
3261
3262
X509_STORE_CTX_cleanup_fn X509_STORE_CTX_get_cleanup(const X509_STORE_CTX *ctx)
3263
0
{
3264
0
    return ctx->cleanup;
3265
0
}
3266
3267
X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(const X509_STORE_CTX *ctx)
3268
0
{
3269
0
    return ctx->tree;
3270
0
}
3271
3272
int X509_STORE_CTX_get_explicit_policy(const X509_STORE_CTX *ctx)
3273
0
{
3274
0
    return ctx->explicit_policy;
3275
0
}
3276
3277
int X509_STORE_CTX_get_num_untrusted(const X509_STORE_CTX *ctx)
3278
0
{
3279
0
    return ctx->num_untrusted;
3280
0
}
3281
3282
int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
3283
0
{
3284
0
    const X509_VERIFY_PARAM *param;
3285
3286
0
    param = X509_VERIFY_PARAM_lookup(name);
3287
0
    if (param == NULL) {
3288
0
        ERR_raise_data(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID, "name=%s", name);
3289
0
        return 0;
3290
0
    }
3291
0
    return X509_VERIFY_PARAM_inherit(ctx->param, param);
3292
0
}
3293
3294
X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(const X509_STORE_CTX *ctx)
3295
0
{
3296
0
    return ctx->param;
3297
0
}
3298
3299
void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
3300
0
{
3301
0
    X509_VERIFY_PARAM_free(ctx->param);
3302
0
    ctx->param = param;
3303
0
}
3304
3305
void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, SSL_DANE *dane)
3306
0
{
3307
0
    ctx->dane = dane;
3308
0
}
3309
3310
static unsigned char *dane_i2d(X509 *cert, uint8_t selector,
3311
    unsigned int *i2dlen)
3312
0
{
3313
0
    unsigned char *buf = NULL;
3314
0
    int len;
3315
3316
    /*
3317
     * Extract ASN.1 DER form of certificate or public key.
3318
     */
3319
0
    switch (selector) {
3320
0
    case DANETLS_SELECTOR_CERT:
3321
0
        len = i2d_X509(cert, &buf);
3322
0
        break;
3323
0
    case DANETLS_SELECTOR_SPKI:
3324
0
        len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf);
3325
0
        break;
3326
0
    default:
3327
0
        ERR_raise(ERR_LIB_X509, X509_R_BAD_SELECTOR);
3328
0
        return NULL;
3329
0
    }
3330
3331
0
    if (len < 0 || buf == NULL) {
3332
0
        ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
3333
0
        return NULL;
3334
0
    }
3335
3336
0
    *i2dlen = (unsigned int)len;
3337
0
    return buf;
3338
0
}
3339
3340
0
#define DANETLS_NONE 256 /* impossible uint8_t */
3341
3342
/* Returns -1 on internal error */
3343
static int dane_match_cert(X509_STORE_CTX *ctx, X509 *cert, int depth)
3344
0
{
3345
0
    SSL_DANE *dane = ctx->dane;
3346
0
    unsigned usage = DANETLS_NONE;
3347
0
    unsigned selector = DANETLS_NONE;
3348
0
    unsigned ordinal = DANETLS_NONE;
3349
0
    unsigned mtype = DANETLS_NONE;
3350
0
    unsigned char *i2dbuf = NULL;
3351
0
    unsigned int i2dlen = 0;
3352
0
    unsigned char mdbuf[EVP_MAX_MD_SIZE];
3353
0
    unsigned char *cmpbuf = NULL;
3354
0
    unsigned int cmplen = 0;
3355
0
    int i;
3356
0
    int recnum;
3357
0
    int matched = 0;
3358
0
    danetls_record *t = NULL;
3359
0
    uint32_t mask;
3360
3361
0
    mask = (depth == 0) ? DANETLS_EE_MASK : DANETLS_TA_MASK;
3362
3363
    /* The trust store is not applicable with DANE-TA(2) */
3364
0
    if (depth >= ctx->num_untrusted)
3365
0
        mask &= DANETLS_PKIX_MASK;
3366
3367
    /*
3368
     * If we've previously matched a PKIX-?? record, no need to test any
3369
     * further PKIX-?? records, it remains to just build the PKIX chain.
3370
     * Had the match been a DANE-?? record, we'd be done already.
3371
     */
3372
0
    if (dane->mdpth >= 0)
3373
0
        mask &= ~DANETLS_PKIX_MASK;
3374
3375
    /*-
3376
     * https://tools.ietf.org/html/rfc7671#section-5.1
3377
     * https://tools.ietf.org/html/rfc7671#section-5.2
3378
     * https://tools.ietf.org/html/rfc7671#section-5.3
3379
     * https://tools.ietf.org/html/rfc7671#section-5.4
3380
     *
3381
     * We handle DANE-EE(3) records first as they require no chain building
3382
     * and no expiration or hostname checks.  We also process digests with
3383
     * higher ordinals first and ignore lower priorities except Full(0) which
3384
     * is always processed (last).  If none match, we then process PKIX-EE(1).
3385
     *
3386
     * NOTE: This relies on DANE usages sorting before the corresponding PKIX
3387
     * usages in SSL_dane_tlsa_add(), and also on descending sorting of digest
3388
     * priorities.  See twin comment in ssl/ssl_lib.c.
3389
     *
3390
     * We expect that most TLSA RRsets will have just a single usage, so we
3391
     * don't go out of our way to cache multiple selector-specific i2d buffers
3392
     * across usages, but if the selector happens to remain the same as switch
3393
     * usages, that's OK.  Thus, a set of "3 1 1", "3 0 1", "1 1 1", "1 0 1",
3394
     * records would result in us generating each of the certificate and public
3395
     * key DER forms twice, but more typically we'd just see multiple "3 1 1"
3396
     * or multiple "3 0 1" records.
3397
     *
3398
     * As soon as we find a match at any given depth, we stop, because either
3399
     * we've matched a DANE-?? record and the peer is authenticated, or, after
3400
     * exhausting all DANE-?? records, we've matched a PKIX-?? record, which is
3401
     * sufficient for DANE, and what remains to do is ordinary PKIX validation.
3402
     */
3403
0
    recnum = (dane->umask & mask) != 0 ? sk_danetls_record_num(dane->trecs) : 0;
3404
0
    for (i = 0; matched == 0 && i < recnum; ++i) {
3405
0
        t = sk_danetls_record_value(dane->trecs, i);
3406
0
        if ((DANETLS_USAGE_BIT(t->usage) & mask) == 0)
3407
0
            continue;
3408
0
        if (t->usage != usage) {
3409
0
            usage = t->usage;
3410
3411
            /* Reset digest agility for each usage/selector pair */
3412
0
            mtype = DANETLS_NONE;
3413
0
            ordinal = dane->dctx->mdord[t->mtype];
3414
0
        }
3415
0
        if (t->selector != selector) {
3416
0
            selector = t->selector;
3417
3418
            /* Update per-selector state */
3419
0
            OPENSSL_free(i2dbuf);
3420
0
            i2dbuf = dane_i2d(cert, selector, &i2dlen);
3421
0
            if (i2dbuf == NULL)
3422
0
                return -1;
3423
3424
            /* Reset digest agility for each usage/selector pair */
3425
0
            mtype = DANETLS_NONE;
3426
0
            ordinal = dane->dctx->mdord[t->mtype];
3427
0
        } else if (t->mtype != DANETLS_MATCHING_FULL) {
3428
            /*-
3429
             * Digest agility:
3430
             *
3431
             *     <https://tools.ietf.org/html/rfc7671#section-9>
3432
             *
3433
             * For a fixed selector, after processing all records with the
3434
             * highest mtype ordinal, ignore all mtypes with lower ordinals
3435
             * other than "Full".
3436
             */
3437
0
            if (dane->dctx->mdord[t->mtype] < ordinal)
3438
0
                continue;
3439
0
        }
3440
3441
        /*
3442
         * Each time we hit a (new selector or) mtype, re-compute the relevant
3443
         * digest, more complex caching is not worth the code space.
3444
         */
3445
0
        if (t->mtype != mtype) {
3446
0
            const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype];
3447
3448
0
            cmpbuf = i2dbuf;
3449
0
            cmplen = i2dlen;
3450
3451
0
            if (md != NULL) {
3452
0
                cmpbuf = mdbuf;
3453
0
                if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) {
3454
0
                    matched = -1;
3455
0
                    break;
3456
0
                }
3457
0
            }
3458
0
        }
3459
3460
        /*
3461
         * Squirrel away the certificate and depth if we have a match.  Any
3462
         * DANE match is dispositive, but with PKIX we still need to build a
3463
         * full chain.
3464
         */
3465
0
        if (cmplen == t->dlen && memcmp(cmpbuf, t->data, cmplen) == 0) {
3466
0
            if (DANETLS_USAGE_BIT(usage) & DANETLS_DANE_MASK)
3467
0
                matched = 1;
3468
0
            if (matched || dane->mdpth < 0) {
3469
0
                if (!X509_up_ref(cert)) {
3470
0
                    matched = -1;
3471
0
                    break;
3472
0
                }
3473
3474
0
                X509_free(dane->mcert);
3475
0
                dane->mcert = cert;
3476
0
                dane->mdpth = depth;
3477
0
                dane->mtlsa = t;
3478
0
            }
3479
0
            break;
3480
0
        }
3481
0
    }
3482
3483
    /* Clear the one-element DER cache */
3484
0
    OPENSSL_free(i2dbuf);
3485
0
    return matched;
3486
0
}
3487
3488
/* Returns -1 on internal error */
3489
static int check_dane_issuer(X509_STORE_CTX *ctx, int depth)
3490
0
{
3491
0
    SSL_DANE *dane = ctx->dane;
3492
0
    int matched = 0;
3493
0
    X509 *cert;
3494
3495
0
    if (!DANETLS_HAS_TA(dane) || depth == 0)
3496
0
        return X509_TRUST_UNTRUSTED;
3497
3498
    /*
3499
     * Record any DANE trust anchor matches, for the first depth to test, if
3500
     * there's one at that depth. (This'll be false for length 1 chains looking
3501
     * for an exact match for the leaf certificate).
3502
     */
3503
0
    cert = sk_X509_value(ctx->chain, depth);
3504
0
    if (cert != NULL && (matched = dane_match_cert(ctx, cert, depth)) < 0)
3505
0
        return matched;
3506
0
    if (matched > 0) {
3507
0
        ctx->num_untrusted = depth - 1;
3508
0
        return X509_TRUST_TRUSTED;
3509
0
    }
3510
3511
0
    return X509_TRUST_UNTRUSTED;
3512
0
}
3513
3514
static int check_dane_pkeys(X509_STORE_CTX *ctx)
3515
0
{
3516
0
    SSL_DANE *dane = ctx->dane;
3517
0
    danetls_record *t;
3518
0
    int num = ctx->num_untrusted;
3519
0
    X509 *cert = sk_X509_value(ctx->chain, num - 1);
3520
0
    int recnum = sk_danetls_record_num(dane->trecs);
3521
0
    int i;
3522
3523
0
    for (i = 0; i < recnum; ++i) {
3524
0
        t = sk_danetls_record_value(dane->trecs, i);
3525
0
        if (t->usage != DANETLS_USAGE_DANE_TA || t->selector != DANETLS_SELECTOR_SPKI || t->mtype != DANETLS_MATCHING_FULL || X509_verify(cert, t->spki) <= 0)
3526
0
            continue;
3527
3528
        /* Clear any PKIX-?? matches that failed to extend to a full chain */
3529
0
        X509_free(dane->mcert);
3530
0
        dane->mcert = NULL;
3531
3532
        /* Record match via a bare TA public key */
3533
0
        ctx->bare_ta_signed = 1;
3534
0
        dane->mdpth = num - 1;
3535
0
        dane->mtlsa = t;
3536
3537
        /* Prune any excess chain certificates */
3538
0
        num = sk_X509_num(ctx->chain);
3539
0
        for (; num > ctx->num_untrusted; --num)
3540
0
            X509_free(sk_X509_pop(ctx->chain));
3541
3542
0
        return X509_TRUST_TRUSTED;
3543
0
    }
3544
3545
0
    return X509_TRUST_UNTRUSTED;
3546
0
}
3547
3548
/*
3549
 * Only DANE-EE and SPKI are supported
3550
 * Returns -1 on internal error
3551
 */
3552
static int dane_match_rpk(X509_STORE_CTX *ctx, EVP_PKEY *rpk)
3553
0
{
3554
0
    SSL_DANE *dane = ctx->dane;
3555
0
    danetls_record *t = NULL;
3556
0
    int mtype = DANETLS_MATCHING_FULL;
3557
0
    unsigned char *i2dbuf = NULL;
3558
0
    unsigned int i2dlen = 0;
3559
0
    unsigned char mdbuf[EVP_MAX_MD_SIZE];
3560
0
    unsigned char *cmpbuf;
3561
0
    unsigned int cmplen = 0;
3562
0
    int len;
3563
0
    int recnum = sk_danetls_record_num(dane->trecs);
3564
0
    int i;
3565
0
    int matched = 0;
3566
3567
    /* Calculate ASN.1 DER of RPK */
3568
0
    if ((len = i2d_PUBKEY(rpk, &i2dbuf)) <= 0)
3569
0
        return -1;
3570
0
    cmplen = i2dlen = (unsigned int)len;
3571
0
    cmpbuf = i2dbuf;
3572
3573
0
    for (i = 0; i < recnum; i++) {
3574
0
        t = sk_danetls_record_value(dane->trecs, i);
3575
0
        if (t->usage != DANETLS_USAGE_DANE_EE || t->selector != DANETLS_SELECTOR_SPKI)
3576
0
            continue;
3577
3578
        /* Calculate hash - keep only one around */
3579
0
        if (t->mtype != mtype) {
3580
0
            const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype];
3581
3582
0
            cmpbuf = i2dbuf;
3583
0
            cmplen = i2dlen;
3584
3585
0
            if (md != NULL) {
3586
0
                cmpbuf = mdbuf;
3587
0
                if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) {
3588
0
                    matched = -1;
3589
0
                    break;
3590
0
                }
3591
0
            }
3592
0
        }
3593
0
        if (cmplen == t->dlen && memcmp(cmpbuf, t->data, cmplen) == 0) {
3594
0
            matched = 1;
3595
0
            dane->mdpth = 0;
3596
0
            dane->mtlsa = t;
3597
0
            break;
3598
0
        }
3599
0
    }
3600
0
    OPENSSL_free(i2dbuf);
3601
0
    return matched;
3602
0
}
3603
3604
static void dane_reset(SSL_DANE *dane)
3605
0
{
3606
    /* Reset state to verify another chain, or clear after failure. */
3607
0
    X509_free(dane->mcert);
3608
0
    dane->mcert = NULL;
3609
0
    dane->mtlsa = NULL;
3610
0
    dane->mdpth = -1;
3611
0
    dane->pdpth = -1;
3612
0
}
3613
3614
/* Sadly, returns 0 also on internal error in ctx->verify_cb(). */
3615
static int check_leaf_suiteb(X509_STORE_CTX *ctx, X509 *cert)
3616
0
{
3617
0
    int err = X509_chain_check_suiteb(NULL, cert, NULL, ctx->param->flags);
3618
3619
0
    CB_FAIL_IF(err != X509_V_OK, ctx, cert, 0, err);
3620
0
    return 1;
3621
0
}
3622
3623
/* Returns -1 on internal error */
3624
static int dane_verify_rpk(X509_STORE_CTX *ctx)
3625
0
{
3626
0
    SSL_DANE *dane = ctx->dane;
3627
0
    int matched;
3628
3629
0
    dane_reset(dane);
3630
3631
    /*
3632
     * Look for a DANE record for RPK
3633
     * If error, return -1
3634
     * If found, call ctx->verify_cb(1, ctx)
3635
     * If not found call ctx->verify_cb(0, ctx)
3636
     */
3637
0
    matched = dane_match_rpk(ctx, ctx->rpk);
3638
0
    ctx->error_depth = 0;
3639
3640
0
    if (matched < 0) {
3641
0
        ctx->error = X509_V_ERR_UNSPECIFIED;
3642
0
        return -1;
3643
0
    }
3644
3645
0
    if (matched > 0)
3646
0
        ctx->error = X509_V_OK;
3647
0
    else
3648
0
        ctx->error = X509_V_ERR_DANE_NO_MATCH;
3649
3650
0
    return verify_rpk(ctx);
3651
0
}
3652
3653
/* Returns -1 on internal error */
3654
static int dane_verify(X509_STORE_CTX *ctx)
3655
0
{
3656
0
    X509 *cert = ctx->cert;
3657
0
    SSL_DANE *dane = ctx->dane;
3658
0
    int matched;
3659
0
    int done;
3660
3661
0
    dane_reset(dane);
3662
3663
    /*-
3664
     * When testing the leaf certificate, if we match a DANE-EE(3) record,
3665
     * dane_match() returns 1 and we're done.  If however we match a PKIX-EE(1)
3666
     * record, the match depth and matching TLSA record are recorded, but the
3667
     * return value is 0, because we still need to find a PKIX trust anchor.
3668
     * Therefore, when DANE authentication is enabled (required), we're done
3669
     * if:
3670
     *   + matched < 0, internal error.
3671
     *   + matched == 1, we matched a DANE-EE(3) record
3672
     *   + matched == 0, mdepth < 0 (no PKIX-EE match) and there are no
3673
     *     DANE-TA(2) or PKIX-TA(0) to test.
3674
     */
3675
0
    matched = dane_match_cert(ctx, ctx->cert, 0);
3676
0
    done = matched != 0 || (!DANETLS_HAS_TA(dane) && dane->mdpth < 0);
3677
3678
0
    if (done && !X509_get_pubkey_parameters(NULL, ctx->chain))
3679
0
        return -1;
3680
3681
0
    if (matched > 0) {
3682
        /* Callback invoked as needed */
3683
0
        if (!check_leaf_suiteb(ctx, cert))
3684
0
            return 0;
3685
        /* Callback invoked as needed */
3686
0
        if ((dane->flags & DANE_FLAG_NO_DANE_EE_NAMECHECKS) == 0 && !check_id(ctx))
3687
0
            return 0;
3688
        /* Bypass internal_verify(), issue depth 0 success callback */
3689
0
        ctx->error_depth = 0;
3690
0
        ctx->current_cert = cert;
3691
0
        return ctx->verify_cb(1, ctx);
3692
0
    }
3693
3694
0
    if (matched < 0) {
3695
0
        ctx->error_depth = 0;
3696
0
        ctx->current_cert = cert;
3697
0
        ctx->error = X509_V_ERR_OUT_OF_MEM;
3698
0
        return -1;
3699
0
    }
3700
3701
0
    if (done) {
3702
        /* Fail early, TA-based success is not possible */
3703
0
        if (!check_leaf_suiteb(ctx, cert))
3704
0
            return 0;
3705
0
        return verify_cb_cert(ctx, cert, 0, X509_V_ERR_DANE_NO_MATCH);
3706
0
    }
3707
3708
    /*
3709
     * Chain verification for usages 0/1/2.  TLSA record matching of depth > 0
3710
     * certificates happens in-line with building the rest of the chain.
3711
     */
3712
0
    return verify_chain(ctx);
3713
0
}
3714
3715
/*
3716
 * Get trusted issuer, without duplicate suppression
3717
 * Returns -1 on internal error.
3718
 */
3719
static int get1_trusted_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *cert)
3720
0
{
3721
0
    STACK_OF(X509) *saved_chain = ctx->chain;
3722
0
    int ok;
3723
3724
0
    ctx->chain = NULL;
3725
0
    ok = ctx->get_issuer(issuer, ctx, cert);
3726
0
    ctx->chain = saved_chain;
3727
3728
0
    return ok;
3729
0
}
3730
3731
/*-
3732
 * Returns -1 on internal error.
3733
 * Sadly, returns 0 also on internal error in ctx->verify_cb().
3734
 */
3735
static int build_chain(X509_STORE_CTX *ctx)
3736
0
{
3737
0
    SSL_DANE *dane = ctx->dane;
3738
0
    int num = sk_X509_num(ctx->chain);
3739
0
    STACK_OF(X509) *sk_untrusted = NULL;
3740
0
    unsigned int search;
3741
0
    int may_trusted = 0;
3742
0
    int may_alternate = 0;
3743
0
    int trust = X509_TRUST_UNTRUSTED;
3744
0
    int alt_untrusted = 0;
3745
0
    int max_depth;
3746
0
    int ok = 0;
3747
0
    int i;
3748
3749
    /* Our chain starts with a single untrusted element. */
3750
0
    if (!ossl_assert(num == 1 && ctx->num_untrusted == num))
3751
0
        goto int_err;
3752
3753
0
#define S_DOUNTRUSTED (1 << 0) /* Search untrusted chain */
3754
0
#define S_DOTRUSTED (1 << 1) /* Search trusted store */
3755
0
#define S_DOALTERNATE (1 << 2) /* Retry with pruned alternate chain */
3756
    /*
3757
     * Set up search policy, untrusted if possible, trusted-first if enabled,
3758
     * which is the default.
3759
     * If we're doing DANE and not doing PKIX-TA/PKIX-EE, we never look in the
3760
     * trust_store, otherwise we might look there first.  If not trusted-first,
3761
     * and alternate chains are not disabled, try building an alternate chain
3762
     * if no luck with untrusted first.
3763
     */
3764
0
    search = ctx->untrusted != NULL ? S_DOUNTRUSTED : 0;
3765
0
    if (DANETLS_HAS_PKIX(dane) || !DANETLS_HAS_DANE(dane)) {
3766
0
        if (search == 0 || (ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST) != 0)
3767
0
            search |= S_DOTRUSTED;
3768
0
        else if (!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS))
3769
0
            may_alternate = 1;
3770
0
        may_trusted = 1;
3771
0
    }
3772
3773
    /* Initialize empty untrusted stack. */
3774
0
    if ((sk_untrusted = sk_X509_new_null()) == NULL) {
3775
0
        ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
3776
0
        goto memerr;
3777
0
    }
3778
3779
    /*
3780
     * If we got any "Cert(0) Full(0)" trust anchors from DNS, *prepend* them
3781
     * to our working copy of the untrusted certificate stack.
3782
     */
3783
0
    if (DANETLS_ENABLED(dane) && dane->certs != NULL
3784
0
        && !X509_add_certs(sk_untrusted, dane->certs, X509_ADD_FLAG_DEFAULT)) {
3785
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
3786
0
        goto memerr;
3787
0
    }
3788
3789
    /*
3790
     * Shallow-copy the stack of untrusted certificates (with TLS, this is
3791
     * typically the content of the peer's certificate message) so we can make
3792
     * multiple passes over it, while free to remove elements as we go.
3793
     */
3794
0
    if (!X509_add_certs(sk_untrusted, ctx->untrusted, X509_ADD_FLAG_DEFAULT)) {
3795
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
3796
0
        goto memerr;
3797
0
    }
3798
3799
    /*
3800
     * Still absurdly large, but arithmetically safe, a lower hard upper bound
3801
     * might be reasonable.
3802
     */
3803
0
    if (ctx->param->depth > INT_MAX / 2)
3804
0
        ctx->param->depth = INT_MAX / 2;
3805
3806
    /*
3807
     * Try to extend the chain until we reach an ultimately trusted issuer.
3808
     * Build chains up to one longer the limit, later fail if we hit the limit,
3809
     * with an X509_V_ERR_CERT_CHAIN_TOO_LONG error code.
3810
     */
3811
0
    max_depth = ctx->param->depth + 1;
3812
3813
0
    while (search != 0) {
3814
0
        X509 *curr, *issuer = NULL;
3815
3816
0
        num = sk_X509_num(ctx->chain);
3817
0
        ctx->error_depth = num - 1;
3818
        /*
3819
         * Look in the trust store if enabled for first lookup, or we've run
3820
         * out of untrusted issuers and search here is not disabled.  When we
3821
         * reach the depth limit, we stop extending the chain, if by that point
3822
         * we've not found a trust anchor, any trusted chain would be too long.
3823
         *
3824
         * The error reported to the application verify callback is at the
3825
         * maximal valid depth with the current certificate equal to the last
3826
         * not ultimately-trusted issuer.  For example, with verify_depth = 0,
3827
         * the callback will report errors at depth=1 when the immediate issuer
3828
         * of the leaf certificate is not a trust anchor.  No attempt will be
3829
         * made to locate an issuer for that certificate, since such a chain
3830
         * would be a-priori too long.
3831
         */
3832
0
        if ((search & S_DOTRUSTED) != 0) {
3833
0
            i = num;
3834
0
            if ((search & S_DOALTERNATE) != 0) {
3835
                /*
3836
                 * As high up the chain as we can, look for an alternative
3837
                 * trusted issuer of an untrusted certificate that currently
3838
                 * has an untrusted issuer.  We use the alt_untrusted variable
3839
                 * to track how far up the chain we find the first match.  It
3840
                 * is only if and when we find a match, that we prune the chain
3841
                 * and reset ctx->num_untrusted to the reduced count of
3842
                 * untrusted certificates.  While we're searching for such a
3843
                 * match (which may never be found), it is neither safe nor
3844
                 * wise to preemptively modify either the chain or
3845
                 * ctx->num_untrusted.
3846
                 *
3847
                 * Note, like ctx->num_untrusted, alt_untrusted is a count of
3848
                 * untrusted certificates, not a "depth".
3849
                 */
3850
0
                i = alt_untrusted;
3851
0
            }
3852
0
            curr = sk_X509_value(ctx->chain, i - 1);
3853
3854
            /* Note: get1_trusted_issuer() must be used even if self-signed. */
3855
0
            ok = num > max_depth ? 0 : get1_trusted_issuer(&issuer, ctx, curr);
3856
3857
0
            if (ok < 0) {
3858
0
                trust = -1;
3859
0
                ctx->error = X509_V_ERR_STORE_LOOKUP;
3860
0
                break;
3861
0
            }
3862
3863
0
            if (ok > 0) {
3864
0
                int self_signed = X509_self_signed(curr, 0);
3865
3866
0
                if (self_signed < 0) {
3867
0
                    X509_free(issuer);
3868
0
                    goto int_err;
3869
0
                }
3870
                /*
3871
                 * Alternative trusted issuer for a mid-chain untrusted cert?
3872
                 * Pop the untrusted cert's successors and retry.  We might now
3873
                 * be able to complete a valid chain via the trust store.  Note
3874
                 * that despite the current trust store match we might still
3875
                 * fail complete the chain to a suitable trust anchor, in which
3876
                 * case we may prune some more untrusted certificates and try
3877
                 * again.  Thus the S_DOALTERNATE bit may yet be turned on
3878
                 * again with an even shorter untrusted chain!
3879
                 *
3880
                 * If in the process we threw away our matching PKIX-TA trust
3881
                 * anchor, reset DANE trust.  We might find a suitable trusted
3882
                 * certificate among the ones from the trust store.
3883
                 */
3884
0
                if ((search & S_DOALTERNATE) != 0) {
3885
0
                    if (!ossl_assert(num > i && i > 0 && !self_signed)) {
3886
0
                        X509_free(issuer);
3887
0
                        goto int_err;
3888
0
                    }
3889
0
                    search &= ~S_DOALTERNATE;
3890
0
                    for (; num > i; --num)
3891
0
                        X509_free(sk_X509_pop(ctx->chain));
3892
0
                    ctx->num_untrusted = num;
3893
3894
0
                    if (DANETLS_ENABLED(dane) && dane->mdpth >= ctx->num_untrusted) {
3895
0
                        dane->mdpth = -1;
3896
0
                        X509_free(dane->mcert);
3897
0
                        dane->mcert = NULL;
3898
0
                    }
3899
0
                    if (DANETLS_ENABLED(dane) && dane->pdpth >= ctx->num_untrusted)
3900
0
                        dane->pdpth = -1;
3901
0
                }
3902
3903
0
                if (!self_signed) { /* untrusted not self-signed certificate */
3904
                    /* Grow the chain by trusted issuer */
3905
0
                    if (!sk_X509_push(ctx->chain, issuer)) {
3906
0
                        X509_free(issuer);
3907
0
                        ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
3908
0
                        goto memerr;
3909
0
                    }
3910
0
                    if ((self_signed = X509_self_signed(issuer, 0)) < 0)
3911
0
                        goto int_err;
3912
0
                } else {
3913
                    /*
3914
                     * We have a self-signed untrusted cert that has the same
3915
                     * subject name (and perhaps keyid and/or serial number) as
3916
                     * a trust anchor.  We must have an exact match to avoid
3917
                     * possible impersonation via key substitution etc.
3918
                     */
3919
0
                    if (X509_cmp(curr, issuer) != 0) {
3920
                        /* Self-signed untrusted mimic. */
3921
0
                        X509_free(issuer);
3922
0
                        ok = 0;
3923
0
                    } else { /* curr "==" issuer */
3924
                        /*
3925
                         * Replace self-signed untrusted certificate
3926
                         * by its trusted matching issuer.
3927
                         */
3928
0
                        X509_free(curr);
3929
0
                        ctx->num_untrusted = --num;
3930
0
                        (void)sk_X509_set(ctx->chain, num, issuer);
3931
0
                    }
3932
0
                }
3933
3934
                /*
3935
                 * We've added a new trusted certificate to the chain, re-check
3936
                 * trust.  If not done, and not self-signed look deeper.
3937
                 * Whether or not we're doing "trusted first", we no longer
3938
                 * look for untrusted certificates from the peer's chain.
3939
                 *
3940
                 * At this point ctx->num_trusted and num must reflect the
3941
                 * correct number of untrusted certificates, since the DANE
3942
                 * logic in check_trust() depends on distinguishing CAs from
3943
                 * "the wire" from CAs from the trust store.  In particular, the
3944
                 * certificate at depth "num" should be the new trusted
3945
                 * certificate with ctx->num_untrusted <= num.
3946
                 */
3947
0
                if (ok) {
3948
0
                    if (!ossl_assert(ctx->num_untrusted <= num))
3949
0
                        goto int_err;
3950
0
                    search &= ~S_DOUNTRUSTED;
3951
0
                    trust = check_trust(ctx, num);
3952
0
                    if (trust != X509_TRUST_UNTRUSTED)
3953
0
                        break;
3954
0
                    if (!self_signed)
3955
0
                        continue;
3956
0
                }
3957
0
            }
3958
3959
            /*
3960
             * No dispositive decision, and either self-signed or no match, if
3961
             * we were doing untrusted-first, and alt-chains are not disabled,
3962
             * do that, by repeatedly losing one untrusted element at a time,
3963
             * and trying to extend the shorted chain.
3964
             */
3965
0
            if ((search & S_DOUNTRUSTED) == 0) {
3966
                /* Continue search for a trusted issuer of a shorter chain? */
3967
0
                if ((search & S_DOALTERNATE) != 0 && --alt_untrusted > 0)
3968
0
                    continue;
3969
                /* Still no luck and no fallbacks left? */
3970
0
                if (!may_alternate || (search & S_DOALTERNATE) != 0 || ctx->num_untrusted < 2)
3971
0
                    break;
3972
                /* Search for a trusted issuer of a shorter chain */
3973
0
                search |= S_DOALTERNATE;
3974
0
                alt_untrusted = ctx->num_untrusted - 1;
3975
0
            }
3976
0
        }
3977
3978
        /*
3979
         * Try to extend chain with peer-provided untrusted certificate
3980
         */
3981
0
        if ((search & S_DOUNTRUSTED) != 0) {
3982
0
            num = sk_X509_num(ctx->chain);
3983
0
            if (!ossl_assert(num == ctx->num_untrusted))
3984
0
                goto int_err;
3985
0
            curr = sk_X509_value(ctx->chain, num - 1);
3986
0
            issuer = (X509_self_signed(curr, 0) > 0 || num > max_depth) ? NULL : get0_best_issuer_sk(ctx, 0, 1 /* no_dup */, sk_untrusted, curr);
3987
0
            if (issuer == NULL) {
3988
                /*
3989
                 * Once we have reached a self-signed cert or num > max_depth
3990
                 * or can't find an issuer in the untrusted list we stop looking
3991
                 * there and start looking only in the trust store if enabled.
3992
                 */
3993
0
                search &= ~S_DOUNTRUSTED;
3994
0
                if (may_trusted)
3995
0
                    search |= S_DOTRUSTED;
3996
0
                continue;
3997
0
            }
3998
3999
            /* Drop this issuer from future consideration */
4000
0
            (void)sk_X509_delete_ptr(sk_untrusted, issuer);
4001
4002
            /* Grow the chain by untrusted issuer */
4003
0
            if (!X509_add_cert(ctx->chain, issuer, X509_ADD_FLAG_UP_REF))
4004
0
                goto int_err;
4005
4006
0
            ++ctx->num_untrusted;
4007
4008
            /* Check for DANE-TA trust of the topmost untrusted certificate. */
4009
0
            trust = check_dane_issuer(ctx, ctx->num_untrusted - 1);
4010
0
            if (trust == X509_TRUST_TRUSTED || trust == X509_TRUST_REJECTED)
4011
0
                break;
4012
0
        }
4013
0
    }
4014
0
    sk_X509_free(sk_untrusted);
4015
4016
0
    if (trust < 0) /* internal error */
4017
0
        return trust;
4018
4019
    /*
4020
     * Last chance to make a trusted chain, either bare DANE-TA public-key
4021
     * signers, or else direct leaf PKIX trust.
4022
     */
4023
0
    num = sk_X509_num(ctx->chain);
4024
0
    if (num <= max_depth) {
4025
0
        if (trust == X509_TRUST_UNTRUSTED && DANETLS_HAS_DANE_TA(dane))
4026
0
            trust = check_dane_pkeys(ctx);
4027
0
        if (trust == X509_TRUST_UNTRUSTED && num == ctx->num_untrusted)
4028
0
            trust = check_trust(ctx, num);
4029
0
    }
4030
4031
0
    switch (trust) {
4032
0
    case X509_TRUST_TRUSTED:
4033
0
        return 1;
4034
0
    case X509_TRUST_REJECTED:
4035
        /* Callback already issued */
4036
0
        return 0;
4037
0
    case X509_TRUST_UNTRUSTED:
4038
0
    default:
4039
0
        switch (ctx->error) {
4040
0
        case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
4041
0
        case X509_V_ERR_CERT_NOT_YET_VALID:
4042
0
        case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
4043
0
        case X509_V_ERR_CERT_HAS_EXPIRED:
4044
0
            return 0; /* Callback already done by ossl_x509_check_cert_time() */
4045
0
        default: /* A preliminary error has become final */
4046
0
            return verify_cb_cert(ctx, NULL, num - 1, ctx->error);
4047
0
        case X509_V_OK:
4048
0
            break;
4049
0
        }
4050
0
        CB_FAIL_IF(num > max_depth,
4051
0
            ctx, NULL, num - 1, X509_V_ERR_CERT_CHAIN_TOO_LONG);
4052
0
        CB_FAIL_IF(DANETLS_ENABLED(dane)
4053
0
                && (!DANETLS_HAS_PKIX(dane) || dane->pdpth >= 0),
4054
0
            ctx, NULL, num - 1, X509_V_ERR_DANE_NO_MATCH);
4055
0
        if (X509_self_signed(sk_X509_value(ctx->chain, num - 1), 0) > 0)
4056
0
            return verify_cb_cert(ctx, NULL, num - 1,
4057
0
                num == 1
4058
0
                    ? X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
4059
0
                    : X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN);
4060
0
        return verify_cb_cert(ctx, NULL, num - 1,
4061
0
            ctx->num_untrusted < num
4062
0
                ? X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT
4063
0
                : X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY);
4064
0
    }
4065
4066
0
int_err:
4067
0
    ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
4068
0
    ctx->error = X509_V_ERR_UNSPECIFIED;
4069
0
    sk_X509_free(sk_untrusted);
4070
0
    return -1;
4071
4072
0
memerr:
4073
0
    ctx->error = X509_V_ERR_OUT_OF_MEM;
4074
0
    sk_X509_free(sk_untrusted);
4075
0
    return -1;
4076
0
}
4077
4078
STACK_OF(X509) *X509_build_chain(const X509 *target, STACK_OF(X509) *certs,
4079
    X509_STORE *store, int with_self_signed,
4080
    OSSL_LIB_CTX *libctx, const char *propq)
4081
0
{
4082
0
    int finish_chain = store != NULL;
4083
0
    X509_STORE_CTX *ctx;
4084
0
    int flags = X509_ADD_FLAG_UP_REF;
4085
0
    STACK_OF(X509) *result = NULL;
4086
4087
0
    if (target == NULL) {
4088
0
        ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
4089
0
        return NULL;
4090
0
    }
4091
4092
0
    if ((ctx = X509_STORE_CTX_new_ex(libctx, propq)) == NULL)
4093
0
        return NULL;
4094
0
    if (!X509_STORE_CTX_init(ctx, store, target, finish_chain ? certs : NULL))
4095
0
        goto err;
4096
0
    if (!finish_chain)
4097
0
        X509_STORE_CTX_set0_trusted_stack(ctx, certs);
4098
    /* XXX casts away const */
4099
0
    if (!ossl_x509_add_cert_new(&ctx->chain, (X509 *)target, X509_ADD_FLAG_UP_REF)) {
4100
0
        ctx->error = X509_V_ERR_OUT_OF_MEM;
4101
0
        goto err;
4102
0
    }
4103
0
    ctx->num_untrusted = 1;
4104
4105
0
    if (!build_chain(ctx) && finish_chain)
4106
0
        goto err;
4107
4108
    /* result list to store the up_ref'ed certificates */
4109
0
    if (sk_X509_num(ctx->chain) > 1 && !with_self_signed)
4110
0
        flags |= X509_ADD_FLAG_NO_SS;
4111
0
    if (!ossl_x509_add_certs_new(&result, ctx->chain, flags)) {
4112
0
        sk_X509_free(result);
4113
0
        result = NULL;
4114
0
    }
4115
4116
0
err:
4117
0
    X509_STORE_CTX_free(ctx);
4118
0
    return result;
4119
0
}
4120
4121
/*
4122
 * note that there's a corresponding minbits_table in ssl/ssl_cert.c
4123
 * in ssl_get_security_level_bits that's used for selection of DH parameters
4124
 */
4125
static const int minbits_table[] = { 80, 112, 128, 192, 256 };
4126
static const int NUM_AUTH_LEVELS = OSSL_NELEM(minbits_table);
4127
4128
/*-
4129
 * Check whether the given public key meets the security level of `ctx`.
4130
 * Returns 1 on success, 0 otherwise.
4131
 */
4132
static int check_key_level(X509_STORE_CTX *ctx, EVP_PKEY *pkey)
4133
0
{
4134
0
    int level = ctx->param->auth_level;
4135
4136
    /*
4137
     * At security level zero, return without checking for a supported public
4138
     * key type.  Some engines support key types not understood outside the
4139
     * engine, and we only need to understand the key when enforcing a security
4140
     * floor.
4141
     */
4142
0
    if (level <= 0)
4143
0
        return 1;
4144
4145
    /* Unsupported or malformed keys are not secure */
4146
0
    if (pkey == NULL)
4147
0
        return 0;
4148
4149
0
    if (level > NUM_AUTH_LEVELS)
4150
0
        level = NUM_AUTH_LEVELS;
4151
4152
0
    return EVP_PKEY_get_security_bits(pkey) >= minbits_table[level - 1];
4153
0
}
4154
4155
/*-
4156
 * Check whether the public key of `cert` meets the security level of `ctx`.
4157
 * Returns 1 on success, 0 otherwise.
4158
 */
4159
static int check_cert_key_level(X509_STORE_CTX *ctx, X509 *cert)
4160
0
{
4161
0
    return check_key_level(ctx, X509_get0_pubkey(cert));
4162
0
}
4163
4164
/*-
4165
 * Check whether the public key of ``cert`` does not use explicit params
4166
 * for an elliptic curve.
4167
 *
4168
 * Returns 1 on success, 0 if check fails, -1 for other errors.
4169
 */
4170
static int check_curve(X509 *cert)
4171
0
{
4172
0
    EVP_PKEY *pkey = X509_get0_pubkey(cert);
4173
0
    int ret, val;
4174
4175
    /* Unsupported or malformed key */
4176
0
    if (pkey == NULL)
4177
0
        return -1;
4178
0
    if (EVP_PKEY_get_id(pkey) != EVP_PKEY_EC)
4179
0
        return 1;
4180
4181
0
    ret = EVP_PKEY_get_int_param(pkey,
4182
0
        OSSL_PKEY_PARAM_EC_DECODED_FROM_EXPLICIT_PARAMS,
4183
0
        &val);
4184
0
    return ret == 1 ? !val : -1;
4185
0
}
4186
4187
/*-
4188
 * Check whether the signature digest algorithm of ``cert`` meets the security
4189
 * level of ``ctx``.  Should not be checked for trust anchors (whether
4190
 * self-signed or otherwise).
4191
 *
4192
 * Returns 1 on success, 0 otherwise.
4193
 */
4194
static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert)
4195
0
{
4196
0
    int secbits = -1;
4197
0
    int level = ctx->param->auth_level;
4198
4199
0
    if (level <= 0)
4200
0
        return 1;
4201
0
    if (level > NUM_AUTH_LEVELS)
4202
0
        level = NUM_AUTH_LEVELS;
4203
4204
0
    if (!X509_get_signature_info(cert, NULL, NULL, &secbits, NULL))
4205
0
        return 0;
4206
4207
0
    return secbits >= minbits_table[level - 1];
4208
0
}