Coverage Report

Created: 2026-04-09 06:50

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