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