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