Debian Codegraph @

debian/rust-vendor/openssl-src/openssl/crypto/x509/x509_vfy.c

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