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