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