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