Coverage Report

Created: 2025-12-10 06:24

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