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