Coverage Report

Created: 2025-12-14 06:48

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