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