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