Coverage Report

Created: 2026-02-14 07:20

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