Coverage Report

Created: 2026-04-08 06:20

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