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