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