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