Coverage Report

Created: 2026-03-03 06:43

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