1 /* $OpenBSD: pcy_tree.c,v 1.1 2020/06/04 15:19:31 jsing Exp $ */
2 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3  * project 2004.
4  */
5 /* ====================================================================
6  * Copyright (c) 2004 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58 
59 #include <openssl/x509.h>
60 #include <openssl/x509v3.h>
61 
62 #include "pcy_int.h"
63 
64 /* Enable this to print out the complete policy tree at various point during
65  * evaluation.
66  */
67 
68 /*#define OPENSSL_POLICY_DEBUG*/
69 
70 #ifdef OPENSSL_POLICY_DEBUG
71 
72 static void
73 expected_print(BIO *err, X509_POLICY_LEVEL *lev, X509_POLICY_NODE *node,
74     int indent)
75 {
76 	if ((lev->flags & X509_V_FLAG_INHIBIT_MAP) ||
77 	    !(node->data->flags & POLICY_DATA_FLAG_MAP_MASK))
78 		BIO_puts(err, "  Not Mapped\n");
79 	else {
80 		int i;
81 		STACK_OF(ASN1_OBJECT) *pset = node->data->expected_policy_set;
82 		ASN1_OBJECT *oid;
83 		BIO_puts(err, "  Expected: ");
84 		for (i = 0; i < sk_ASN1_OBJECT_num(pset); i++) {
85 			oid = sk_ASN1_OBJECT_value(pset, i);
86 			if (i)
87 				BIO_puts(err, ", ");
88 			i2a_ASN1_OBJECT(err, oid);
89 		}
90 		BIO_puts(err, "\n");
91 	}
92 }
93 
94 static void
95 tree_print(char *str, X509_POLICY_TREE *tree, X509_POLICY_LEVEL *curr)
96 {
97 	X509_POLICY_LEVEL *plev;
98 	X509_POLICY_NODE *node;
99 	int i;
100 	BIO *err;
101 
102 	if ((err = BIO_new_fp(stderr, BIO_NOCLOSE)) == NULL)
103 		return;
104 
105 	if (!curr)
106 		curr = tree->levels + tree->nlevel;
107 	else
108 		curr++;
109 	BIO_printf(err, "Level print after %s\n", str);
110 	BIO_printf(err, "Printing Up to Level %ld\n", curr - tree->levels);
111 	for (plev = tree->levels; plev != curr; plev++) {
112 		BIO_printf(err, "Level %ld, flags = %x\n",
113 		    plev - tree->levels, plev->flags);
114 		for (i = 0; i < sk_X509_POLICY_NODE_num(plev->nodes); i++) {
115 			node = sk_X509_POLICY_NODE_value(plev->nodes, i);
116 			X509_POLICY_NODE_print(err, node, 2);
117 			expected_print(err, plev, node, 2);
118 			BIO_printf(err, "  Flags: %x\n", node->data->flags);
119 		}
120 		if (plev->anyPolicy)
121 			X509_POLICY_NODE_print(err, plev->anyPolicy, 2);
122 	}
123 
124 	BIO_free(err);
125 }
126 #else
127 
128 #define tree_print(a,b,c) /* */
129 
130 #endif
131 
132 /* Initialize policy tree. Return values:
133  *  0 Some internal error occured.
134  * -1 Inconsistent or invalid extensions in certificates.
135  *  1 Tree initialized OK.
136  *  2 Policy tree is empty.
137  *  5 Tree OK and requireExplicitPolicy true.
138  *  6 Tree empty and requireExplicitPolicy true.
139  */
140 
141 static int
142 tree_init(X509_POLICY_TREE **ptree, STACK_OF(X509) *certs, unsigned int flags)
143 {
144 	X509_POLICY_TREE *tree;
145 	X509_POLICY_LEVEL *level;
146 	const X509_POLICY_CACHE *cache;
147 	X509_POLICY_DATA *data = NULL;
148 	X509 *x;
149 	int ret = 1;
150 	int i, n;
151 	int explicit_policy;
152 	int any_skip;
153 	int map_skip;
154 
155 	*ptree = NULL;
156 	n = sk_X509_num(certs);
157 
158 	if (flags & X509_V_FLAG_EXPLICIT_POLICY)
159 		explicit_policy = 0;
160 	else
161 		explicit_policy = n + 1;
162 
163 	if (flags & X509_V_FLAG_INHIBIT_ANY)
164 		any_skip = 0;
165 	else
166 		any_skip = n + 1;
167 
168 	if (flags & X509_V_FLAG_INHIBIT_MAP)
169 		map_skip = 0;
170 	else
171 		map_skip = n + 1;
172 
173 	/* Can't do anything with just a trust anchor */
174 	if (n == 1)
175 		return 1;
176 	/* First setup policy cache in all certificates apart from the
177 	 * trust anchor. Note any bad cache results on the way. Also can
178 	 * calculate explicit_policy value at this point.
179 	 */
180 	for (i = n - 2; i >= 0; i--) {
181 		x = sk_X509_value(certs, i);
182 		X509_check_purpose(x, -1, -1);
183 		cache = policy_cache_set(x);
184 		/* If cache NULL something bad happened: return immediately */
185 		if (cache == NULL)
186 			return 0;
187 		/* If inconsistent extensions keep a note of it but continue */
188 		if (x->ex_flags & EXFLAG_INVALID_POLICY)
189 			ret = -1;
190 		/* Otherwise if we have no data (hence no CertificatePolicies)
191 		 * and haven't already set an inconsistent code note it.
192 		 */
193 		else if ((ret == 1) && !cache->data)
194 			ret = 2;
195 		if (explicit_policy > 0) {
196 			if (!(x->ex_flags & EXFLAG_SI))
197 				explicit_policy--;
198 			if ((cache->explicit_skip != -1) &&
199 			    (cache->explicit_skip < explicit_policy))
200 				explicit_policy = cache->explicit_skip;
201 		}
202 	}
203 
204 	if (ret != 1) {
205 		if (ret == 2 && !explicit_policy)
206 			return 6;
207 		return ret;
208 	}
209 
210 
211 	/* If we get this far initialize the tree */
212 
213 	tree = malloc(sizeof(X509_POLICY_TREE));
214 
215 	if (!tree)
216 		return 0;
217 
218 	tree->flags = 0;
219 	tree->levels = calloc(n, sizeof(X509_POLICY_LEVEL));
220 	tree->nlevel = 0;
221 	tree->extra_data = NULL;
222 	tree->auth_policies = NULL;
223 	tree->user_policies = NULL;
224 
225 	if (!tree->levels) {
226 		free(tree);
227 		return 0;
228 	}
229 
230 	tree->nlevel = n;
231 
232 	level = tree->levels;
233 
234 	/* Root data: initialize to anyPolicy */
235 
236 	data = policy_data_new(NULL, OBJ_nid2obj(NID_any_policy), 0);
237 
238 	if (!data || !level_add_node(level, data, NULL, tree, NULL))
239 		goto bad_tree;
240 
241 	for (i = n - 2; i >= 0; i--) {
242 		level++;
243 		x = sk_X509_value(certs, i);
244 		cache = policy_cache_set(x);
245 		CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
246 		level->cert = x;
247 
248 		if (!cache->anyPolicy)
249 			level->flags |= X509_V_FLAG_INHIBIT_ANY;
250 
251 		/* Determine inhibit any and inhibit map flags */
252 		if (any_skip == 0) {
253 			/* Any matching allowed if certificate is self
254 			 * issued and not the last in the chain.
255 			 */
256 			if (!(x->ex_flags & EXFLAG_SI) || (i == 0))
257 				level->flags |= X509_V_FLAG_INHIBIT_ANY;
258 		} else {
259 			if (!(x->ex_flags & EXFLAG_SI))
260 				any_skip--;
261 			if ((cache->any_skip >= 0) &&
262 			    (cache->any_skip < any_skip))
263 				any_skip = cache->any_skip;
264 		}
265 
266 		if (map_skip == 0)
267 			level->flags |= X509_V_FLAG_INHIBIT_MAP;
268 		else {
269 			if (!(x->ex_flags & EXFLAG_SI))
270 				map_skip--;
271 			if ((cache->map_skip >= 0) &&
272 			    (cache->map_skip < map_skip))
273 				map_skip = cache->map_skip;
274 		}
275 
276 	}
277 
278 	*ptree = tree;
279 
280 	if (explicit_policy)
281 		return 1;
282 	else
283 		return 5;
284 
285 bad_tree:
286 	X509_policy_tree_free(tree);
287 
288 	return 0;
289 }
290 
291 static int
292 tree_link_matching_nodes(X509_POLICY_LEVEL *curr, const X509_POLICY_DATA *data)
293 {
294 	X509_POLICY_LEVEL *last = curr - 1;
295 	X509_POLICY_NODE *node;
296 	int i, matched = 0;
297 
298 	/* Iterate through all in nodes linking matches */
299 	for (i = 0; i < sk_X509_POLICY_NODE_num(last->nodes); i++) {
300 		node = sk_X509_POLICY_NODE_value(last->nodes, i);
301 		if (policy_node_match(last, node, data->valid_policy)) {
302 			if (!level_add_node(curr, data, node, NULL, NULL))
303 				return 0;
304 			matched = 1;
305 		}
306 	}
307 	if (!matched && last->anyPolicy) {
308 		if (!level_add_node(curr, data, last->anyPolicy, NULL, NULL))
309 			return 0;
310 	}
311 	return 1;
312 }
313 
314 /* This corresponds to RFC3280 6.1.3(d)(1):
315  * link any data from CertificatePolicies onto matching parent
316  * or anyPolicy if no match.
317  */
318 
319 static int
320 tree_link_nodes(X509_POLICY_LEVEL *curr, const X509_POLICY_CACHE *cache)
321 {
322 	int i;
323 	X509_POLICY_DATA *data;
324 
325 	for (i = 0; i < sk_X509_POLICY_DATA_num(cache->data); i++) {
326 		data = sk_X509_POLICY_DATA_value(cache->data, i);
327 		/* Look for matching nodes in previous level */
328 		if (!tree_link_matching_nodes(curr, data))
329 			return 0;
330 	}
331 	return 1;
332 }
333 
334 /* This corresponds to RFC3280 6.1.3(d)(2):
335  * Create new data for any unmatched policies in the parent and link
336  * to anyPolicy.
337  */
338 
339 static int
340 tree_add_unmatched(X509_POLICY_LEVEL *curr, const X509_POLICY_CACHE *cache,
341     const ASN1_OBJECT *id, X509_POLICY_NODE *node, X509_POLICY_TREE *tree)
342 {
343 	X509_POLICY_DATA *data;
344 
345 	if (id == NULL)
346 		id = node->data->valid_policy;
347 	/* Create a new node with qualifiers from anyPolicy and
348 	 * id from unmatched node.
349 	 */
350 	data = policy_data_new(NULL, id, node_critical(node));
351 
352 	if (data == NULL)
353 		return 0;
354 	/* Curr may not have anyPolicy */
355 	data->qualifier_set = cache->anyPolicy->qualifier_set;
356 	data->flags |= POLICY_DATA_FLAG_SHARED_QUALIFIERS;
357 	if (!level_add_node(curr, data, node, tree, NULL)) {
358 		policy_data_free(data);
359 		return 0;
360 	}
361 
362 	return 1;
363 }
364 
365 static int
366 tree_link_unmatched(X509_POLICY_LEVEL *curr, const X509_POLICY_CACHE *cache,
367     X509_POLICY_NODE *node, X509_POLICY_TREE *tree)
368 {
369 	const X509_POLICY_LEVEL *last = curr - 1;
370 	int i;
371 
372 	if ((last->flags & X509_V_FLAG_INHIBIT_MAP) ||
373 	    !(node->data->flags & POLICY_DATA_FLAG_MAPPED)) {
374 		/* If no policy mapping: matched if one child present */
375 		if (node->nchild)
376 			return 1;
377 		if (!tree_add_unmatched(curr, cache, NULL, node, tree))
378 			return 0;
379 		/* Add it */
380 	} else {
381 		/* If mapping: matched if one child per expected policy set */
382 		STACK_OF(ASN1_OBJECT) *expset = node->data->expected_policy_set;
383 		if (node->nchild == sk_ASN1_OBJECT_num(expset))
384 			return 1;
385 		/* Locate unmatched nodes */
386 		for (i = 0; i < sk_ASN1_OBJECT_num(expset); i++) {
387 			ASN1_OBJECT *oid = sk_ASN1_OBJECT_value(expset, i);
388 			if (level_find_node(curr, node, oid))
389 				continue;
390 			if (!tree_add_unmatched(curr, cache, oid, node, tree))
391 				return 0;
392 		}
393 	}
394 
395 	return 1;
396 }
397 
398 static int
399 tree_link_any(X509_POLICY_LEVEL *curr, const X509_POLICY_CACHE *cache,
400     X509_POLICY_TREE *tree)
401 {
402 	int i;
403 	X509_POLICY_NODE *node;
404 	X509_POLICY_LEVEL *last = curr - 1;
405 
406 	for (i = 0; i < sk_X509_POLICY_NODE_num(last->nodes); i++) {
407 		node = sk_X509_POLICY_NODE_value(last->nodes, i);
408 
409 		if (!tree_link_unmatched(curr, cache, node, tree))
410 			return 0;
411 	}
412 	/* Finally add link to anyPolicy */
413 	if (last->anyPolicy) {
414 		if (!level_add_node(curr, cache->anyPolicy,
415 		    last->anyPolicy, NULL, NULL))
416 			return 0;
417 	}
418 	return 1;
419 }
420 
421 /* Prune the tree: delete any child mapped child data on the current level
422  * then proceed up the tree deleting any data with no children. If we ever
423  * have no data on a level we can halt because the tree will be empty.
424  */
425 
426 static int
427 tree_prune(X509_POLICY_TREE *tree, X509_POLICY_LEVEL *curr)
428 {
429 	STACK_OF(X509_POLICY_NODE) *nodes;
430 	X509_POLICY_NODE *node;
431 	int i;
432 
433 	nodes = curr->nodes;
434 	if (curr->flags & X509_V_FLAG_INHIBIT_MAP) {
435 		for (i = sk_X509_POLICY_NODE_num(nodes) - 1; i >= 0; i--) {
436 			node = sk_X509_POLICY_NODE_value(nodes, i);
437 			/* Delete any mapped data: see RFC3280 XXXX */
438 			if (node->data->flags & POLICY_DATA_FLAG_MAP_MASK) {
439 				node->parent->nchild--;
440 				free(node);
441 				(void)sk_X509_POLICY_NODE_delete(nodes, i);
442 			}
443 		}
444 	}
445 
446 	for (;;) {
447 		--curr;
448 		nodes = curr->nodes;
449 		for (i = sk_X509_POLICY_NODE_num(nodes) - 1; i >= 0; i--) {
450 			node = sk_X509_POLICY_NODE_value(nodes, i);
451 			if (node->nchild == 0) {
452 				node->parent->nchild--;
453 				free(node);
454 				(void)sk_X509_POLICY_NODE_delete(nodes, i);
455 			}
456 		}
457 		if (curr->anyPolicy && !curr->anyPolicy->nchild) {
458 			if (curr->anyPolicy->parent)
459 				curr->anyPolicy->parent->nchild--;
460 			free(curr->anyPolicy);
461 			curr->anyPolicy = NULL;
462 		}
463 		if (curr == tree->levels) {
464 			/* If we zapped anyPolicy at top then tree is empty */
465 			if (!curr->anyPolicy)
466 				return 2;
467 			return 1;
468 		}
469 	}
470 
471 	return 1;
472 }
473 
474 static int
475 tree_add_auth_node(STACK_OF(X509_POLICY_NODE) **pnodes, X509_POLICY_NODE *pcy)
476 {
477 	if (!*pnodes) {
478 		*pnodes = policy_node_cmp_new();
479 		if (!*pnodes)
480 			return 0;
481 	} else if (sk_X509_POLICY_NODE_find(*pnodes, pcy) != -1)
482 		return 1;
483 
484 	if (!sk_X509_POLICY_NODE_push(*pnodes, pcy))
485 		return 0;
486 
487 	return 1;
488 }
489 
490 /* Calculate the authority set based on policy tree.
491  * The 'pnodes' parameter is used as a store for the set of policy nodes
492  * used to calculate the user set. If the authority set is not anyPolicy
493  * then pnodes will just point to the authority set. If however the authority
494  * set is anyPolicy then the set of valid policies (other than anyPolicy)
495  * is store in pnodes. The return value of '2' is used in this case to indicate
496  * that pnodes should be freed.
497  */
498 
499 static int
500 tree_calculate_authority_set(X509_POLICY_TREE *tree,
501     STACK_OF(X509_POLICY_NODE) **pnodes)
502 {
503 	X509_POLICY_LEVEL *curr;
504 	X509_POLICY_NODE *node, *anyptr;
505 	STACK_OF(X509_POLICY_NODE) **addnodes;
506 	int i, j;
507 
508 	curr = tree->levels + tree->nlevel - 1;
509 
510 	/* If last level contains anyPolicy set is anyPolicy */
511 	if (curr->anyPolicy) {
512 		if (!tree_add_auth_node(&tree->auth_policies, curr->anyPolicy))
513 			return 0;
514 		addnodes = pnodes;
515 	} else
516 		/* Add policies to authority set */
517 		addnodes = &tree->auth_policies;
518 
519 	curr = tree->levels;
520 	for (i = 1; i < tree->nlevel; i++) {
521 		/* If no anyPolicy node on this this level it can't
522 		 * appear on lower levels so end search.
523 		 */
524 		if (!(anyptr = curr->anyPolicy))
525 			break;
526 		curr++;
527 		for (j = 0; j < sk_X509_POLICY_NODE_num(curr->nodes); j++) {
528 			node = sk_X509_POLICY_NODE_value(curr->nodes, j);
529 			if ((node->parent == anyptr) &&
530 			    !tree_add_auth_node(addnodes, node))
531 				return 0;
532 		}
533 	}
534 
535 	if (addnodes == pnodes)
536 		return 2;
537 
538 	*pnodes = tree->auth_policies;
539 
540 	return 1;
541 }
542 
543 static int
544 tree_calculate_user_set(X509_POLICY_TREE *tree,
545     STACK_OF(ASN1_OBJECT) *policy_oids, STACK_OF(X509_POLICY_NODE) *auth_nodes)
546 {
547 	int i;
548 	X509_POLICY_NODE *node;
549 	ASN1_OBJECT *oid;
550 	X509_POLICY_NODE *anyPolicy;
551 	X509_POLICY_DATA *extra;
552 
553 	/* Check if anyPolicy present in authority constrained policy set:
554 	 * this will happen if it is a leaf node.
555 	 */
556 
557 	if (sk_ASN1_OBJECT_num(policy_oids) <= 0)
558 		return 1;
559 
560 	anyPolicy = tree->levels[tree->nlevel - 1].anyPolicy;
561 
562 	for (i = 0; i < sk_ASN1_OBJECT_num(policy_oids); i++) {
563 		oid = sk_ASN1_OBJECT_value(policy_oids, i);
564 		if (OBJ_obj2nid(oid) == NID_any_policy) {
565 			tree->flags |= POLICY_FLAG_ANY_POLICY;
566 			return 1;
567 		}
568 	}
569 
570 	for (i = 0; i < sk_ASN1_OBJECT_num(policy_oids); i++) {
571 		oid = sk_ASN1_OBJECT_value(policy_oids, i);
572 		node = tree_find_sk(auth_nodes, oid);
573 		if (!node) {
574 			if (!anyPolicy)
575 				continue;
576 			/* Create a new node with policy ID from user set
577 			 * and qualifiers from anyPolicy.
578 			 */
579 			extra = policy_data_new(NULL, oid,
580 			    node_critical(anyPolicy));
581 			if (!extra)
582 				return 0;
583 			extra->qualifier_set = anyPolicy->data->qualifier_set;
584 			extra->flags = POLICY_DATA_FLAG_SHARED_QUALIFIERS |
585 			    POLICY_DATA_FLAG_EXTRA_NODE;
586 			(void) level_add_node(NULL, extra, anyPolicy->parent,
587 			    tree, &node);
588 		}
589 		if (!tree->user_policies) {
590 			tree->user_policies = sk_X509_POLICY_NODE_new_null();
591 			if (!tree->user_policies)
592 				return 1;
593 		}
594 		if (!sk_X509_POLICY_NODE_push(tree->user_policies, node))
595 			return 0;
596 	}
597 	return 1;
598 }
599 
600 static int
601 tree_evaluate(X509_POLICY_TREE *tree)
602 {
603 	int ret, i;
604 	X509_POLICY_LEVEL *curr = tree->levels + 1;
605 	const X509_POLICY_CACHE *cache;
606 
607 	for (i = 1; i < tree->nlevel; i++, curr++) {
608 		cache = policy_cache_set(curr->cert);
609 		if (!tree_link_nodes(curr, cache))
610 			return 0;
611 
612 		if (!(curr->flags & X509_V_FLAG_INHIBIT_ANY) &&
613 		    !tree_link_any(curr, cache, tree))
614 			return 0;
615 		tree_print("before tree_prune()", tree, curr);
616 		ret = tree_prune(tree, curr);
617 		if (ret != 1)
618 			return ret;
619 	}
620 
621 	return 1;
622 }
623 
624 static void
625 exnode_free(X509_POLICY_NODE *node)
626 {
627 	if (node->data && (node->data->flags & POLICY_DATA_FLAG_EXTRA_NODE))
628 		free(node);
629 }
630 
631 void
632 X509_policy_tree_free(X509_POLICY_TREE *tree)
633 {
634 	X509_POLICY_LEVEL *curr;
635 	int i;
636 
637 	if (!tree)
638 		return;
639 
640 	sk_X509_POLICY_NODE_free(tree->auth_policies);
641 	sk_X509_POLICY_NODE_pop_free(tree->user_policies, exnode_free);
642 
643 	for (i = 0, curr = tree->levels; i < tree->nlevel; i++, curr++) {
644 		X509_free(curr->cert);
645 		if (curr->nodes)
646 			sk_X509_POLICY_NODE_pop_free(curr->nodes,
647 		    policy_node_free);
648 		if (curr->anyPolicy)
649 			policy_node_free(curr->anyPolicy);
650 	}
651 
652 	if (tree->extra_data)
653 		sk_X509_POLICY_DATA_pop_free(tree->extra_data,
654 		    policy_data_free);
655 
656 	free(tree->levels);
657 	free(tree);
658 }
659 
660 /* Application policy checking function.
661  * Return codes:
662  *  0 	Internal Error.
663  *  1   Successful.
664  * -1   One or more certificates contain invalid or inconsistent extensions
665  * -2	User constrained policy set empty and requireExplicit true.
666  */
667 
668 int
669 X509_policy_check(X509_POLICY_TREE **ptree, int *pexplicit_policy,
670     STACK_OF(X509) *certs, STACK_OF(ASN1_OBJECT) *policy_oids,
671     unsigned int flags)
672 {
673 	int ret, ret2;
674 	X509_POLICY_TREE *tree = NULL;
675 	STACK_OF(X509_POLICY_NODE) *nodes, *auth_nodes = NULL;
676 
677 	*ptree = NULL;
678 	*pexplicit_policy = 0;
679 	ret = tree_init(&tree, certs, flags);
680 
681 	switch (ret) {
682 
683 		/* Tree empty requireExplicit False: OK */
684 	case 2:
685 		return 1;
686 
687 		/* Some internal error */
688 	case -1:
689 		return -1;
690 
691 		/* Some internal error */
692 	case 0:
693 		return 0;
694 
695 		/* Tree empty requireExplicit True: Error */
696 
697 	case 6:
698 		*pexplicit_policy = 1;
699 		return -2;
700 
701 		/* Tree OK requireExplicit True: OK and continue */
702 	case 5:
703 		*pexplicit_policy = 1;
704 		break;
705 
706 		/* Tree OK: continue */
707 
708 	case 1:
709 		if (!tree)
710 			/*
711 			 * tree_init() returns success and a null tree
712 			 * if it's just looking at a trust anchor.
713 			 * I'm not sure that returning success here is
714 			 * correct, but I'm sure that reporting this
715 			 * as an internal error which our caller
716 			 * interprets as a malloc failure is wrong.
717 			 */
718 			return 1;
719 		break;
720 	}
721 
722 	if (!tree)
723 		goto error;
724 	ret = tree_evaluate(tree);
725 
726 	tree_print("tree_evaluate()", tree, NULL);
727 
728 	if (ret <= 0)
729 		goto error;
730 
731 	/* Return value 2 means tree empty */
732 	if (ret == 2) {
733 		X509_policy_tree_free(tree);
734 		if (*pexplicit_policy)
735 			return -2;
736 		else
737 			return 1;
738 	}
739 
740 	/* Tree is not empty: continue */
741 
742 	ret = tree_calculate_authority_set(tree, &auth_nodes);
743 	if (ret == 0)
744 		goto error;
745 
746 	ret2 = tree_calculate_user_set(tree, policy_oids, auth_nodes);
747 
748 	/* Return value 2 means auth_nodes needs to be freed */
749 	if (ret == 2)
750 		sk_X509_POLICY_NODE_free(auth_nodes);
751 
752 	if (ret2 == 0)
753 		goto error;
754 
755 	if (tree)
756 		*ptree = tree;
757 
758 	if (*pexplicit_policy) {
759 		nodes = X509_policy_tree_get0_user_policies(tree);
760 		if (sk_X509_POLICY_NODE_num(nodes) <= 0)
761 			return -2;
762 	}
763 
764 	return 1;
765 
766 error:
767 	X509_policy_tree_free(tree);
768 
769 	return 0;
770 }
771