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