xref: /aosp_15_r20/external/cronet/third_party/boringssl/src/crypto/x509/policy.c (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 /* Copyright (c) 2022, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <openssl/x509.h>
16 
17 #include <assert.h>
18 
19 #include <openssl/mem.h>
20 #include <openssl/obj.h>
21 #include <openssl/stack.h>
22 
23 #include "../internal.h"
24 #include "internal.h"
25 
26 
27 // This file computes the X.509 policy tree, as described in RFC 5280, section
28 // 6.1. It differs in that:
29 //
30 //  (1) It does not track "qualifier_set". This is not needed as it is not
31 //      output by this implementation.
32 //
33 //  (2) It builds a directed acyclic graph, rather than a tree. When a given
34 //      policy matches multiple parents, RFC 5280 makes a separate node for
35 //      each parent. This representation condenses them into one node with
36 //      multiple parents. Thus we refer to this structure as a "policy graph",
37 //      rather than a "policy tree".
38 //
39 //  (3) "expected_policy_set" is not tracked explicitly and built temporarily
40 //      as part of building the graph.
41 //
42 //  (4) anyPolicy nodes are not tracked explicitly.
43 //
44 //  (5) Some pruning steps are deferred to when policies are evaluated, as a
45 //      reachability pass.
46 
47 // An X509_POLICY_NODE is a node in the policy graph. It corresponds to a node
48 // from RFC 5280, section 6.1.2, step (a), but we store some fields differently.
49 typedef struct x509_policy_node_st {
50   // policy is the "valid_policy" field from RFC 5280.
51   ASN1_OBJECT *policy;
52 
53   // parent_policies, if non-empty, is the list of "valid_policy" values for all
54   // nodes which are a parent of this node. In this case, no entry in this list
55   // will be anyPolicy. This list is in no particular order and may contain
56   // duplicates if the corresponding certificate had duplicate mappings.
57   //
58   // If empty, this node has a single parent, anyPolicy. The node is then a root
59   // policies, and is in authorities-constrained-policy-set if it has a path to
60   // a leaf node.
61   //
62   // Note it is not possible for a policy to have both anyPolicy and a
63   // concrete policy as a parent. Section 6.1.3, step (d.1.ii) only runs if
64   // there was no match in step (d.1.i). We do not need to represent a parent
65   // list of, say, {anyPolicy, OID1, OID2}.
66   STACK_OF(ASN1_OBJECT) *parent_policies;
67 
68   // mapped is one if this node matches a policy mapping in the certificate and
69   // zero otherwise.
70   int mapped;
71 
72   // reachable is one if this node is reachable from some valid policy in the
73   // end-entity certificate. It is computed during |has_explicit_policy|.
74   int reachable;
75 } X509_POLICY_NODE;
76 
77 DEFINE_STACK_OF(X509_POLICY_NODE)
78 
79 // An X509_POLICY_LEVEL is the collection of nodes at the same depth in the
80 // policy graph. This structure can also be used to represent a level's
81 // "expected_policy_set" values. See |process_policy_mappings|.
82 typedef struct x509_policy_level_st {
83   // nodes is the list of nodes at this depth, except for the anyPolicy node, if
84   // any. This list is sorted by policy OID for efficient lookup.
85   STACK_OF(X509_POLICY_NODE) *nodes;
86 
87   // has_any_policy is one if there is an anyPolicy node at this depth, and zero
88   // otherwise.
89   int has_any_policy;
90 } X509_POLICY_LEVEL;
91 
DEFINE_STACK_OF(X509_POLICY_LEVEL)92 DEFINE_STACK_OF(X509_POLICY_LEVEL)
93 
94 static int is_any_policy(const ASN1_OBJECT *obj) {
95   return OBJ_obj2nid(obj) == NID_any_policy;
96 }
97 
x509_policy_node_free(X509_POLICY_NODE * node)98 static void x509_policy_node_free(X509_POLICY_NODE *node) {
99   if (node != NULL) {
100     ASN1_OBJECT_free(node->policy);
101     sk_ASN1_OBJECT_pop_free(node->parent_policies, ASN1_OBJECT_free);
102     OPENSSL_free(node);
103   }
104 }
105 
x509_policy_node_new(const ASN1_OBJECT * policy)106 static X509_POLICY_NODE *x509_policy_node_new(const ASN1_OBJECT *policy) {
107   assert(!is_any_policy(policy));
108   X509_POLICY_NODE *node = OPENSSL_zalloc(sizeof(X509_POLICY_NODE));
109   if (node == NULL) {
110     return NULL;
111   }
112   node->policy = OBJ_dup(policy);
113   node->parent_policies = sk_ASN1_OBJECT_new_null();
114   if (node->policy == NULL || node->parent_policies == NULL) {
115     x509_policy_node_free(node);
116     return NULL;
117   }
118   return node;
119 }
120 
x509_policy_node_cmp(const X509_POLICY_NODE * const * a,const X509_POLICY_NODE * const * b)121 static int x509_policy_node_cmp(const X509_POLICY_NODE *const *a,
122                                 const X509_POLICY_NODE *const *b) {
123   return OBJ_cmp((*a)->policy, (*b)->policy);
124 }
125 
x509_policy_level_free(X509_POLICY_LEVEL * level)126 static void x509_policy_level_free(X509_POLICY_LEVEL *level) {
127   if (level != NULL) {
128     sk_X509_POLICY_NODE_pop_free(level->nodes, x509_policy_node_free);
129     OPENSSL_free(level);
130   }
131 }
132 
x509_policy_level_new(void)133 static X509_POLICY_LEVEL *x509_policy_level_new(void) {
134   X509_POLICY_LEVEL *level = OPENSSL_zalloc(sizeof(X509_POLICY_LEVEL));
135   if (level == NULL) {
136     return NULL;
137   }
138   level->nodes = sk_X509_POLICY_NODE_new(x509_policy_node_cmp);
139   if (level->nodes == NULL) {
140     x509_policy_level_free(level);
141     return NULL;
142   }
143   return level;
144 }
145 
x509_policy_level_is_empty(const X509_POLICY_LEVEL * level)146 static int x509_policy_level_is_empty(const X509_POLICY_LEVEL *level) {
147   return !level->has_any_policy && sk_X509_POLICY_NODE_num(level->nodes) == 0;
148 }
149 
x509_policy_level_clear(X509_POLICY_LEVEL * level)150 static void x509_policy_level_clear(X509_POLICY_LEVEL *level) {
151   level->has_any_policy = 0;
152   for (size_t i = 0; i < sk_X509_POLICY_NODE_num(level->nodes); i++) {
153     x509_policy_node_free(sk_X509_POLICY_NODE_value(level->nodes, i));
154   }
155   sk_X509_POLICY_NODE_zero(level->nodes);
156 }
157 
158 // x509_policy_level_find returns the node in |level| corresponding to |policy|,
159 // or NULL if none exists.
x509_policy_level_find(X509_POLICY_LEVEL * level,const ASN1_OBJECT * policy)160 static X509_POLICY_NODE *x509_policy_level_find(X509_POLICY_LEVEL *level,
161                                                 const ASN1_OBJECT *policy) {
162   assert(sk_X509_POLICY_NODE_is_sorted(level->nodes));
163   X509_POLICY_NODE node;
164   node.policy = (ASN1_OBJECT *)policy;
165   size_t idx;
166   if (!sk_X509_POLICY_NODE_find(level->nodes, &idx, &node)) {
167     return NULL;
168   }
169   return sk_X509_POLICY_NODE_value(level->nodes, idx);
170 }
171 
172 // x509_policy_level_add_nodes adds the nodes in |nodes| to |level|. It returns
173 // one on success and zero on error. No policy in |nodes| may already be present
174 // in |level|. This function modifies |nodes| to avoid making a copy, but the
175 // caller is still responsible for releasing |nodes| itself.
176 //
177 // This function is used to add nodes to |level| in bulk, and avoid resorting
178 // |level| after each addition.
x509_policy_level_add_nodes(X509_POLICY_LEVEL * level,STACK_OF (X509_POLICY_NODE)* nodes)179 static int x509_policy_level_add_nodes(X509_POLICY_LEVEL *level,
180                                        STACK_OF(X509_POLICY_NODE) *nodes) {
181   for (size_t i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
182     X509_POLICY_NODE *node = sk_X509_POLICY_NODE_value(nodes, i);
183     if (!sk_X509_POLICY_NODE_push(level->nodes, node)) {
184       return 0;
185     }
186     sk_X509_POLICY_NODE_set(nodes, i, NULL);
187   }
188   sk_X509_POLICY_NODE_sort(level->nodes);
189 
190 #if !defined(NDEBUG)
191   // There should be no duplicate nodes.
192   for (size_t i = 1; i < sk_X509_POLICY_NODE_num(level->nodes); i++) {
193     assert(OBJ_cmp(sk_X509_POLICY_NODE_value(level->nodes, i - 1)->policy,
194                    sk_X509_POLICY_NODE_value(level->nodes, i)->policy) != 0);
195   }
196 #endif
197   return 1;
198 }
199 
policyinfo_cmp(const POLICYINFO * const * a,const POLICYINFO * const * b)200 static int policyinfo_cmp(const POLICYINFO *const *a,
201                           const POLICYINFO *const *b) {
202   return OBJ_cmp((*a)->policyid, (*b)->policyid);
203 }
204 
delete_if_not_in_policies(X509_POLICY_NODE * node,void * data)205 static int delete_if_not_in_policies(X509_POLICY_NODE *node, void *data) {
206   const CERTIFICATEPOLICIES *policies = data;
207   assert(sk_POLICYINFO_is_sorted(policies));
208   POLICYINFO info;
209   info.policyid = node->policy;
210   if (sk_POLICYINFO_find(policies, NULL, &info)) {
211     return 0;
212   }
213   x509_policy_node_free(node);
214   return 1;
215 }
216 
217 // process_certificate_policies updates |level| to incorporate |x509|'s
218 // certificate policies extension. This implements steps (d) and (e) of RFC
219 // 5280, section 6.1.3. |level| must contain the previous level's
220 // "expected_policy_set" information. For all but the top-most level, this is
221 // the output of |process_policy_mappings|. |any_policy_allowed| specifies
222 // whether anyPolicy is allowed or inhibited, taking into account the exception
223 // for self-issued certificates.
process_certificate_policies(const X509 * x509,X509_POLICY_LEVEL * level,int any_policy_allowed)224 static int process_certificate_policies(const X509 *x509,
225                                         X509_POLICY_LEVEL *level,
226                                         int any_policy_allowed) {
227   int ret = 0;
228   int critical;
229   STACK_OF(X509_POLICY_NODE) *new_nodes = NULL;
230   CERTIFICATEPOLICIES *policies =
231       X509_get_ext_d2i(x509, NID_certificate_policies, &critical, NULL);
232   if (policies == NULL) {
233     if (critical != -1) {
234       return 0;  // Syntax error in the extension.
235     }
236 
237     // RFC 5280, section 6.1.3, step (e).
238     x509_policy_level_clear(level);
239     return 1;
240   }
241 
242   // certificatePolicies may not be empty. See RFC 5280, section 4.2.1.4.
243   // TODO(https://crbug.com/boringssl/443): Move this check into the parser.
244   if (sk_POLICYINFO_num(policies) == 0) {
245     OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION);
246     goto err;
247   }
248 
249   sk_POLICYINFO_set_cmp_func(policies, policyinfo_cmp);
250   sk_POLICYINFO_sort(policies);
251   int cert_has_any_policy = 0;
252   for (size_t i = 0; i < sk_POLICYINFO_num(policies); i++) {
253     const POLICYINFO *policy = sk_POLICYINFO_value(policies, i);
254     if (is_any_policy(policy->policyid)) {
255       cert_has_any_policy = 1;
256     }
257     if (i > 0 && OBJ_cmp(sk_POLICYINFO_value(policies, i - 1)->policyid,
258                          policy->policyid) == 0) {
259       // Per RFC 5280, section 4.2.1.4, |policies| may not have duplicates.
260       OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION);
261       goto err;
262     }
263   }
264 
265   // This does the same thing as RFC 5280, section 6.1.3, step (d), though in
266   // a slighty different order. |level| currently contains "expected_policy_set"
267   // values of the previous level. See |process_policy_mappings| for details.
268   const int previous_level_has_any_policy = level->has_any_policy;
269 
270   // First, we handle steps (d.1.i) and (d.2). The net effect of these two steps
271   // is to intersect |level| with |policies|, ignoring anyPolicy if it is
272   // inhibited.
273   if (!cert_has_any_policy || !any_policy_allowed) {
274     sk_X509_POLICY_NODE_delete_if(level->nodes, delete_if_not_in_policies,
275                                   policies);
276     level->has_any_policy = 0;
277   }
278 
279   // Step (d.1.ii) may attach new nodes to the previous level's anyPolicy node.
280   if (previous_level_has_any_policy) {
281     new_nodes = sk_X509_POLICY_NODE_new_null();
282     if (new_nodes == NULL) {
283       goto err;
284     }
285     for (size_t i = 0; i < sk_POLICYINFO_num(policies); i++) {
286       const POLICYINFO *policy = sk_POLICYINFO_value(policies, i);
287       // Though we've reordered the steps slightly, |policy| is in |level| if
288       // and only if it would have been a match in step (d.1.ii).
289       if (!is_any_policy(policy->policyid) &&
290           x509_policy_level_find(level, policy->policyid) == NULL) {
291         X509_POLICY_NODE *node = x509_policy_node_new(policy->policyid);
292         if (node == NULL ||  //
293             !sk_X509_POLICY_NODE_push(new_nodes, node)) {
294           x509_policy_node_free(node);
295           goto err;
296         }
297       }
298     }
299     if (!x509_policy_level_add_nodes(level, new_nodes)) {
300       goto err;
301     }
302   }
303 
304   ret = 1;
305 
306 err:
307   sk_X509_POLICY_NODE_pop_free(new_nodes, x509_policy_node_free);
308   CERTIFICATEPOLICIES_free(policies);
309   return ret;
310 }
311 
compare_issuer_policy(const POLICY_MAPPING * const * a,const POLICY_MAPPING * const * b)312 static int compare_issuer_policy(const POLICY_MAPPING *const *a,
313                                  const POLICY_MAPPING *const *b) {
314   return OBJ_cmp((*a)->issuerDomainPolicy, (*b)->issuerDomainPolicy);
315 }
316 
compare_subject_policy(const POLICY_MAPPING * const * a,const POLICY_MAPPING * const * b)317 static int compare_subject_policy(const POLICY_MAPPING *const *a,
318                                   const POLICY_MAPPING *const *b) {
319   return OBJ_cmp((*a)->subjectDomainPolicy, (*b)->subjectDomainPolicy);
320 }
321 
delete_if_mapped(X509_POLICY_NODE * node,void * data)322 static int delete_if_mapped(X509_POLICY_NODE *node, void *data) {
323   const POLICY_MAPPINGS *mappings = data;
324   // |mappings| must have been sorted by |compare_issuer_policy|.
325   assert(sk_POLICY_MAPPING_is_sorted(mappings));
326   POLICY_MAPPING mapping;
327   mapping.issuerDomainPolicy = node->policy;
328   if (!sk_POLICY_MAPPING_find(mappings, /*out_index=*/NULL, &mapping)) {
329     return 0;
330   }
331   x509_policy_node_free(node);
332   return 1;
333 }
334 
335 // process_policy_mappings processes the policy mappings extension of |cert|,
336 // whose corresponding graph level is |level|. |mapping_allowed| specifies
337 // whether policy mapping is inhibited at this point. On success, it returns an
338 // |X509_POLICY_LEVEL| containing the "expected_policy_set" for |level|. On
339 // error, it returns NULL. This implements steps (a) and (b) of RFC 5280,
340 // section 6.1.4.
341 //
342 // We represent the "expected_policy_set" as an |X509_POLICY_LEVEL|.
343 // |has_any_policy| indicates whether there is an anyPolicy node with
344 // "expected_policy_set" of {anyPolicy}. If a node with policy oid P1 contains
345 // P2 in its "expected_policy_set", the level will contain a node of policy P2
346 // with P1 in |parent_policies|.
347 //
348 // This is equivalent to the |X509_POLICY_LEVEL| that would result if the next
349 // certificats contained anyPolicy. |process_certificate_policies| will filter
350 // this result down to compute the actual level.
process_policy_mappings(const X509 * cert,X509_POLICY_LEVEL * level,int mapping_allowed)351 static X509_POLICY_LEVEL *process_policy_mappings(const X509 *cert,
352                                                   X509_POLICY_LEVEL *level,
353                                                   int mapping_allowed) {
354   int ok = 0;
355   STACK_OF(X509_POLICY_NODE) *new_nodes = NULL;
356   X509_POLICY_LEVEL *next = NULL;
357   int critical;
358   POLICY_MAPPINGS *mappings =
359       X509_get_ext_d2i(cert, NID_policy_mappings, &critical, NULL);
360   if (mappings == NULL && critical != -1) {
361     // Syntax error in the policy mappings extension.
362     goto err;
363   }
364 
365   if (mappings != NULL) {
366     // PolicyMappings may not be empty. See RFC 5280, section 4.2.1.5.
367     // TODO(https://crbug.com/boringssl/443): Move this check into the parser.
368     if (sk_POLICY_MAPPING_num(mappings) == 0) {
369       OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION);
370       goto err;
371     }
372 
373     // RFC 5280, section 6.1.4, step (a).
374     for (size_t i = 0; i < sk_POLICY_MAPPING_num(mappings); i++) {
375       POLICY_MAPPING *mapping = sk_POLICY_MAPPING_value(mappings, i);
376       if (is_any_policy(mapping->issuerDomainPolicy) ||
377           is_any_policy(mapping->subjectDomainPolicy)) {
378         goto err;
379       }
380     }
381 
382     // Sort to group by issuerDomainPolicy.
383     sk_POLICY_MAPPING_set_cmp_func(mappings, compare_issuer_policy);
384     sk_POLICY_MAPPING_sort(mappings);
385 
386     if (mapping_allowed) {
387       // Mark nodes as mapped, and add any nodes to |level| which may be needed
388       // as part of RFC 5280, section 6.1.4, step (b.1).
389       new_nodes = sk_X509_POLICY_NODE_new_null();
390       if (new_nodes == NULL) {
391         goto err;
392       }
393       const ASN1_OBJECT *last_policy = NULL;
394       for (size_t i = 0; i < sk_POLICY_MAPPING_num(mappings); i++) {
395         const POLICY_MAPPING *mapping = sk_POLICY_MAPPING_value(mappings, i);
396         // There may be multiple mappings with the same |issuerDomainPolicy|.
397         if (last_policy != NULL &&
398             OBJ_cmp(mapping->issuerDomainPolicy, last_policy) == 0) {
399           continue;
400         }
401         last_policy = mapping->issuerDomainPolicy;
402 
403         X509_POLICY_NODE *node =
404             x509_policy_level_find(level, mapping->issuerDomainPolicy);
405         if (node == NULL) {
406           if (!level->has_any_policy) {
407             continue;
408           }
409           node = x509_policy_node_new(mapping->issuerDomainPolicy);
410           if (node == NULL ||  //
411               !sk_X509_POLICY_NODE_push(new_nodes, node)) {
412             x509_policy_node_free(node);
413             goto err;
414           }
415         }
416         node->mapped = 1;
417       }
418       if (!x509_policy_level_add_nodes(level, new_nodes)) {
419         goto err;
420       }
421     } else {
422       // RFC 5280, section 6.1.4, step (b.2). If mapping is inhibited, delete
423       // all mapped nodes.
424       sk_X509_POLICY_NODE_delete_if(level->nodes, delete_if_mapped, mappings);
425       sk_POLICY_MAPPING_pop_free(mappings, POLICY_MAPPING_free);
426       mappings = NULL;
427     }
428   }
429 
430   // If a node was not mapped, it retains the original "explicit_policy_set"
431   // value, itself. Add those to |mappings|.
432   if (mappings == NULL) {
433     mappings = sk_POLICY_MAPPING_new_null();
434     if (mappings == NULL) {
435       goto err;
436     }
437   }
438   for (size_t i = 0; i < sk_X509_POLICY_NODE_num(level->nodes); i++) {
439     X509_POLICY_NODE *node = sk_X509_POLICY_NODE_value(level->nodes, i);
440     if (!node->mapped) {
441       POLICY_MAPPING *mapping = POLICY_MAPPING_new();
442       if (mapping == NULL) {
443         goto err;
444       }
445       mapping->issuerDomainPolicy = OBJ_dup(node->policy);
446       mapping->subjectDomainPolicy = OBJ_dup(node->policy);
447       if (mapping->issuerDomainPolicy == NULL ||
448           mapping->subjectDomainPolicy == NULL ||
449           !sk_POLICY_MAPPING_push(mappings, mapping)) {
450         POLICY_MAPPING_free(mapping);
451         goto err;
452       }
453     }
454   }
455 
456   // Sort to group by subjectDomainPolicy.
457   sk_POLICY_MAPPING_set_cmp_func(mappings, compare_subject_policy);
458   sk_POLICY_MAPPING_sort(mappings);
459 
460   // Convert |mappings| to our "expected_policy_set" representation.
461   next = x509_policy_level_new();
462   if (next == NULL) {
463     goto err;
464   }
465   next->has_any_policy = level->has_any_policy;
466 
467   X509_POLICY_NODE *last_node = NULL;
468   for (size_t i = 0; i < sk_POLICY_MAPPING_num(mappings); i++) {
469     POLICY_MAPPING *mapping = sk_POLICY_MAPPING_value(mappings, i);
470     // Skip mappings where |issuerDomainPolicy| does not appear in the graph.
471     if (!level->has_any_policy &&
472         x509_policy_level_find(level, mapping->issuerDomainPolicy) == NULL) {
473       continue;
474     }
475 
476     if (last_node == NULL ||
477         OBJ_cmp(last_node->policy, mapping->subjectDomainPolicy) != 0) {
478       last_node = x509_policy_node_new(mapping->subjectDomainPolicy);
479       if (last_node == NULL ||
480           !sk_X509_POLICY_NODE_push(next->nodes, last_node)) {
481         x509_policy_node_free(last_node);
482         goto err;
483       }
484     }
485 
486     if (!sk_ASN1_OBJECT_push(last_node->parent_policies,
487                              mapping->issuerDomainPolicy)) {
488       goto err;
489     }
490     mapping->issuerDomainPolicy = NULL;
491   }
492 
493   sk_X509_POLICY_NODE_sort(next->nodes);
494   ok = 1;
495 
496 err:
497   if (!ok) {
498     x509_policy_level_free(next);
499     next = NULL;
500   }
501 
502   sk_POLICY_MAPPING_pop_free(mappings, POLICY_MAPPING_free);
503   sk_X509_POLICY_NODE_pop_free(new_nodes, x509_policy_node_free);
504   return next;
505 }
506 
507 // apply_skip_certs, if |skip_certs| is non-NULL, sets |*value| to the minimum
508 // of its current value and |skip_certs|. It returns one on success and zero if
509 // |skip_certs| is negative.
apply_skip_certs(const ASN1_INTEGER * skip_certs,size_t * value)510 static int apply_skip_certs(const ASN1_INTEGER *skip_certs, size_t *value) {
511   if (skip_certs == NULL) {
512     return 1;
513   }
514 
515   // TODO(https://crbug.com/boringssl/443): Move this check into the parser.
516   if (skip_certs->type & V_ASN1_NEG) {
517     OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION);
518     return 0;
519   }
520 
521   // If |skip_certs| does not fit in |uint64_t|, it must exceed |*value|.
522   uint64_t u64;
523   if (ASN1_INTEGER_get_uint64(&u64, skip_certs) && u64 < *value) {
524     *value = (size_t)u64;
525   }
526   ERR_clear_error();
527   return 1;
528 }
529 
530 // process_policy_constraints updates |*explicit_policy|, |*policy_mapping|, and
531 // |*inhibit_any_policy| according to |x509|'s policy constraints and inhibit
532 // anyPolicy extensions. It returns one on success and zero on error. This
533 // implements steps (i) and (j) of RFC 5280, section 6.1.4.
process_policy_constraints(const X509 * x509,size_t * explicit_policy,size_t * policy_mapping,size_t * inhibit_any_policy)534 static int process_policy_constraints(const X509 *x509, size_t *explicit_policy,
535                                       size_t *policy_mapping,
536                                       size_t *inhibit_any_policy) {
537   int critical;
538   POLICY_CONSTRAINTS *constraints =
539       X509_get_ext_d2i(x509, NID_policy_constraints, &critical, NULL);
540   if (constraints == NULL && critical != -1) {
541     return 0;
542   }
543   if (constraints != NULL) {
544     if (constraints->requireExplicitPolicy == NULL &&
545         constraints->inhibitPolicyMapping == NULL) {
546       // Per RFC 5280, section 4.2.1.11, at least one of the fields must be
547       // present.
548       OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION);
549       POLICY_CONSTRAINTS_free(constraints);
550       return 0;
551     }
552     int ok =
553         apply_skip_certs(constraints->requireExplicitPolicy, explicit_policy) &&
554         apply_skip_certs(constraints->inhibitPolicyMapping, policy_mapping);
555     POLICY_CONSTRAINTS_free(constraints);
556     if (!ok) {
557       return 0;
558     }
559   }
560 
561   ASN1_INTEGER *inhibit_any_policy_ext =
562       X509_get_ext_d2i(x509, NID_inhibit_any_policy, &critical, NULL);
563   if (inhibit_any_policy_ext == NULL && critical != -1) {
564     return 0;
565   }
566   int ok = apply_skip_certs(inhibit_any_policy_ext, inhibit_any_policy);
567   ASN1_INTEGER_free(inhibit_any_policy_ext);
568   return ok;
569 }
570 
571 // has_explicit_policy returns one if the set of authority-space policy OIDs
572 // |levels| has some non-empty intersection with |user_policies|, and zero
573 // otherwise. This mirrors the logic in RFC 5280, section 6.1.5, step (g). This
574 // function modifies |levels| and should only be called at the end of policy
575 // evaluation.
has_explicit_policy(STACK_OF (X509_POLICY_LEVEL)* levels,const STACK_OF (ASN1_OBJECT)* user_policies)576 static int has_explicit_policy(STACK_OF(X509_POLICY_LEVEL) *levels,
577                                const STACK_OF(ASN1_OBJECT) *user_policies) {
578   assert(user_policies == NULL || sk_ASN1_OBJECT_is_sorted(user_policies));
579 
580   // Step (g.i). If the policy graph is empty, the intersection is empty.
581   size_t num_levels = sk_X509_POLICY_LEVEL_num(levels);
582   X509_POLICY_LEVEL *level = sk_X509_POLICY_LEVEL_value(levels, num_levels - 1);
583   if (x509_policy_level_is_empty(level)) {
584     return 0;
585   }
586 
587   // If |user_policies| is empty, we interpret it as having a single anyPolicy
588   // value. The caller may also have supplied anyPolicy explicitly.
589   int user_has_any_policy = sk_ASN1_OBJECT_num(user_policies) == 0;
590   for (size_t i = 0; i < sk_ASN1_OBJECT_num(user_policies); i++) {
591     if (is_any_policy(sk_ASN1_OBJECT_value(user_policies, i))) {
592       user_has_any_policy = 1;
593       break;
594     }
595   }
596 
597   // Step (g.ii). If the policy graph is not empty and the user set contains
598   // anyPolicy, the intersection is the entire (non-empty) graph.
599   if (user_has_any_policy) {
600     return 1;
601   }
602 
603   // Step (g.iii) does not delete anyPolicy nodes, so if the graph has
604   // anyPolicy, some explicit policy will survive. The actual intersection may
605   // synthesize some nodes in step (g.iii.3), but we do not return the policy
606   // list itself, so we skip actually computing this.
607   if (level->has_any_policy) {
608     return 1;
609   }
610 
611   // We defer pruning the tree, so as we look for nodes with parent anyPolicy,
612   // step (g.iii.1), we must limit to nodes reachable from the bottommost level.
613   // Start by marking each of those nodes as reachable.
614   for (size_t i = 0; i < sk_X509_POLICY_NODE_num(level->nodes); i++) {
615     sk_X509_POLICY_NODE_value(level->nodes, i)->reachable = 1;
616   }
617 
618   for (size_t i = num_levels - 1; i < num_levels; i--) {
619     level = sk_X509_POLICY_LEVEL_value(levels, i);
620     for (size_t j = 0; j < sk_X509_POLICY_NODE_num(level->nodes); j++) {
621       X509_POLICY_NODE *node = sk_X509_POLICY_NODE_value(level->nodes, j);
622       if (!node->reachable) {
623         continue;
624       }
625       if (sk_ASN1_OBJECT_num(node->parent_policies) == 0) {
626         // |node|'s parent is anyPolicy and is part of "valid_policy_node_set".
627         // If it exists in |user_policies|, the intersection is non-empty and we
628         // can return immediately.
629         if (sk_ASN1_OBJECT_find(user_policies, /*out_index=*/NULL,
630                                 node->policy)) {
631           return 1;
632         }
633       } else if (i > 0) {
634         // |node|'s parents are concrete policies. Mark the parents reachable,
635         // to be inspected by the next loop iteration.
636         X509_POLICY_LEVEL *prev = sk_X509_POLICY_LEVEL_value(levels, i - 1);
637         for (size_t k = 0; k < sk_ASN1_OBJECT_num(node->parent_policies); k++) {
638           X509_POLICY_NODE *parent = x509_policy_level_find(
639               prev, sk_ASN1_OBJECT_value(node->parent_policies, k));
640           if (parent != NULL) {
641             parent->reachable = 1;
642           }
643         }
644       }
645     }
646   }
647 
648   return 0;
649 }
650 
asn1_object_cmp(const ASN1_OBJECT * const * a,const ASN1_OBJECT * const * b)651 static int asn1_object_cmp(const ASN1_OBJECT *const *a,
652                            const ASN1_OBJECT *const *b) {
653   return OBJ_cmp(*a, *b);
654 }
655 
X509_policy_check(const STACK_OF (X509)* certs,const STACK_OF (ASN1_OBJECT)* user_policies,unsigned long flags,X509 ** out_current_cert)656 int X509_policy_check(const STACK_OF(X509) *certs,
657                       const STACK_OF(ASN1_OBJECT) *user_policies,
658                       unsigned long flags, X509 **out_current_cert) {
659   *out_current_cert = NULL;
660   int ret = X509_V_ERR_OUT_OF_MEM;
661   X509_POLICY_LEVEL *level = NULL;
662   STACK_OF(X509_POLICY_LEVEL) *levels = NULL;
663   STACK_OF(ASN1_OBJECT) *user_policies_sorted = NULL;
664   size_t num_certs = sk_X509_num(certs);
665 
666   // Skip policy checking if the chain is just the trust anchor.
667   if (num_certs <= 1) {
668     return X509_V_OK;
669   }
670 
671   // See RFC 5280, section 6.1.2, steps (d) through (f).
672   size_t explicit_policy =
673       (flags & X509_V_FLAG_EXPLICIT_POLICY) ? 0 : num_certs + 1;
674   size_t inhibit_any_policy =
675       (flags & X509_V_FLAG_INHIBIT_ANY) ? 0 : num_certs + 1;
676   size_t policy_mapping =
677       (flags & X509_V_FLAG_INHIBIT_MAP) ? 0 : num_certs + 1;
678 
679   levels = sk_X509_POLICY_LEVEL_new_null();
680   if (levels == NULL) {
681     goto err;
682   }
683 
684   for (size_t i = num_certs - 2; i < num_certs; i--) {
685     X509 *cert = sk_X509_value(certs, i);
686     if (!x509v3_cache_extensions(cert)) {
687       goto err;
688     }
689     const int is_self_issued = (cert->ex_flags & EXFLAG_SI) != 0;
690 
691     if (level == NULL) {
692       assert(i == num_certs - 2);
693       level = x509_policy_level_new();
694       if (level == NULL) {
695         goto err;
696       }
697       level->has_any_policy = 1;
698     }
699 
700     // RFC 5280, section 6.1.3, steps (d) and (e). |any_policy_allowed| is
701     // computed as in step (d.2).
702     const int any_policy_allowed =
703         inhibit_any_policy > 0 || (i > 0 && is_self_issued);
704     if (!process_certificate_policies(cert, level, any_policy_allowed)) {
705       ret = X509_V_ERR_INVALID_POLICY_EXTENSION;
706       *out_current_cert = cert;
707       goto err;
708     }
709 
710     // RFC 5280, section 6.1.3, step (f).
711     if (explicit_policy == 0 && x509_policy_level_is_empty(level)) {
712       ret = X509_V_ERR_NO_EXPLICIT_POLICY;
713       goto err;
714     }
715 
716     // Insert into the list.
717     if (!sk_X509_POLICY_LEVEL_push(levels, level)) {
718       goto err;
719     }
720     X509_POLICY_LEVEL *current_level = level;
721     level = NULL;
722 
723     // If this is not the leaf certificate, we go to section 6.1.4. If it
724     // is the leaf certificate, we go to section 6.1.5 instead.
725     if (i != 0) {
726       // RFC 5280, section 6.1.4, steps (a) and (b).
727       level = process_policy_mappings(cert, current_level, policy_mapping > 0);
728       if (level == NULL) {
729         ret = X509_V_ERR_INVALID_POLICY_EXTENSION;
730         *out_current_cert = cert;
731         goto err;
732       }
733     }
734 
735     // RFC 5280, section 6.1.4, step (h-j) for non-leaves, and section 6.1.5,
736     // step (a-b) for leaves. In the leaf case, RFC 5280 says only to update
737     // |explicit_policy|, but |policy_mapping| and |inhibit_any_policy| are no
738     // longer read at this point, so we use the same process.
739     if (i == 0 || !is_self_issued) {
740       if (explicit_policy > 0) {
741         explicit_policy--;
742       }
743       if (policy_mapping > 0) {
744         policy_mapping--;
745       }
746       if (inhibit_any_policy > 0) {
747         inhibit_any_policy--;
748       }
749     }
750     if (!process_policy_constraints(cert, &explicit_policy, &policy_mapping,
751                                     &inhibit_any_policy)) {
752       ret = X509_V_ERR_INVALID_POLICY_EXTENSION;
753       *out_current_cert = cert;
754       goto err;
755     }
756   }
757 
758   // RFC 5280, section 6.1.5, step (g). We do not output the policy set, so it
759   // is only necessary to check if the user-constrained-policy-set is not empty.
760   if (explicit_policy == 0) {
761     // Build a sorted copy of |user_policies| for more efficient lookup.
762     if (user_policies != NULL) {
763       user_policies_sorted = sk_ASN1_OBJECT_dup(user_policies);
764       if (user_policies_sorted == NULL) {
765         goto err;
766       }
767       sk_ASN1_OBJECT_set_cmp_func(user_policies_sorted, asn1_object_cmp);
768       sk_ASN1_OBJECT_sort(user_policies_sorted);
769     }
770 
771     if (!has_explicit_policy(levels, user_policies_sorted)) {
772       ret = X509_V_ERR_NO_EXPLICIT_POLICY;
773       goto err;
774     }
775   }
776 
777   ret = X509_V_OK;
778 
779 err:
780   x509_policy_level_free(level);
781   // |user_policies_sorted|'s contents are owned by |user_policies|, so we do
782   // not use |sk_ASN1_OBJECT_pop_free|.
783   sk_ASN1_OBJECT_free(user_policies_sorted);
784   sk_X509_POLICY_LEVEL_pop_free(levels, x509_policy_level_free);
785   return ret;
786 }
787