xref: /linux/security/selinux/ss/policydb.c (revision b73b967b0fc44707f39faa4f298f1f9d9b7bfac5)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Implementation of the policy database.
4  *
5  * Author : Stephen Smalley, <stephen.smalley.work@gmail.com>
6  */
7 
8 /*
9  * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>
10  *          Support for enhanced MLS infrastructure.
11  *          Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
12  *
13  * Updated: Frank Mayer <mayerf@tresys.com> and
14  *          Karl MacMillan <kmacmillan@tresys.com>
15  *          Added conditional policy language extensions
16  *          Copyright (C) 2003-2004 Tresys Technology, LLC
17  *
18  * Updated: Hewlett-Packard <paul@paul-moore.com>
19  *          Added support for the policy capability bitmap
20  *          Copyright (C) 2007 Hewlett-Packard Development Company, L.P.
21  *
22  * Update: Mellanox Techonologies
23  *         Added Infiniband support
24  *         Copyright (C) 2016 Mellanox Techonologies
25  */
26 
27 #include <linux/kernel.h>
28 #include <linux/sched.h>
29 #include <linux/slab.h>
30 #include <linux/string.h>
31 #include <linux/errno.h>
32 #include <linux/audit.h>
33 #include <linux/sort.h>
34 #include "security.h"
35 
36 #include "policydb.h"
37 #include "conditional.h"
38 #include "mls.h"
39 #include "services.h"
40 
41 #ifdef CONFIG_SECURITY_SELINUX_DEBUG
42 /* clang-format off */
43 static const char *const symtab_name[SYM_NUM] = {
44 	"common prefixes",
45 	"classes",
46 	"roles",
47 	"types",
48 	"users",
49 	"bools",
50 	"levels",
51 	"categories",
52 };
53 /* clang-format off */
54 #endif
55 
56 struct policydb_compat_info {
57 	unsigned int version;
58 	unsigned int sym_num;
59 	unsigned int ocon_num;
60 };
61 
62 /* These need to be updated if SYM_NUM or OCON_NUM changes */
63 static const struct policydb_compat_info policydb_compat[] = {
64 	{
65 		.version = POLICYDB_VERSION_BASE,
66 		.sym_num = SYM_NUM - 3,
67 		.ocon_num = OCON_NUM - 3,
68 	},
69 	{
70 		.version = POLICYDB_VERSION_BOOL,
71 		.sym_num = SYM_NUM - 2,
72 		.ocon_num = OCON_NUM - 3,
73 	},
74 	{
75 		.version = POLICYDB_VERSION_IPV6,
76 		.sym_num = SYM_NUM - 2,
77 		.ocon_num = OCON_NUM - 2,
78 	},
79 	{
80 		.version = POLICYDB_VERSION_NLCLASS,
81 		.sym_num = SYM_NUM - 2,
82 		.ocon_num = OCON_NUM - 2,
83 	},
84 	{
85 		.version = POLICYDB_VERSION_MLS,
86 		.sym_num = SYM_NUM,
87 		.ocon_num = OCON_NUM - 2,
88 	},
89 	{
90 		.version = POLICYDB_VERSION_AVTAB,
91 		.sym_num = SYM_NUM,
92 		.ocon_num = OCON_NUM - 2,
93 	},
94 	{
95 		.version = POLICYDB_VERSION_RANGETRANS,
96 		.sym_num = SYM_NUM,
97 		.ocon_num = OCON_NUM - 2,
98 	},
99 	{
100 		.version = POLICYDB_VERSION_POLCAP,
101 		.sym_num = SYM_NUM,
102 		.ocon_num = OCON_NUM - 2,
103 	},
104 	{
105 		.version = POLICYDB_VERSION_PERMISSIVE,
106 		.sym_num = SYM_NUM,
107 		.ocon_num = OCON_NUM - 2,
108 	},
109 	{
110 		.version = POLICYDB_VERSION_BOUNDARY,
111 		.sym_num = SYM_NUM,
112 		.ocon_num = OCON_NUM - 2,
113 	},
114 	{
115 		.version = POLICYDB_VERSION_FILENAME_TRANS,
116 		.sym_num = SYM_NUM,
117 		.ocon_num = OCON_NUM - 2,
118 	},
119 	{
120 		.version = POLICYDB_VERSION_ROLETRANS,
121 		.sym_num = SYM_NUM,
122 		.ocon_num = OCON_NUM - 2,
123 	},
124 	{
125 		.version = POLICYDB_VERSION_NEW_OBJECT_DEFAULTS,
126 		.sym_num = SYM_NUM,
127 		.ocon_num = OCON_NUM - 2,
128 	},
129 	{
130 		.version = POLICYDB_VERSION_DEFAULT_TYPE,
131 		.sym_num = SYM_NUM,
132 		.ocon_num = OCON_NUM - 2,
133 	},
134 	{
135 		.version = POLICYDB_VERSION_CONSTRAINT_NAMES,
136 		.sym_num = SYM_NUM,
137 		.ocon_num = OCON_NUM - 2,
138 	},
139 	{
140 		.version = POLICYDB_VERSION_XPERMS_IOCTL,
141 		.sym_num = SYM_NUM,
142 		.ocon_num = OCON_NUM - 2,
143 	},
144 	{
145 		.version = POLICYDB_VERSION_INFINIBAND,
146 		.sym_num = SYM_NUM,
147 		.ocon_num = OCON_NUM,
148 	},
149 	{
150 		.version = POLICYDB_VERSION_GLBLUB,
151 		.sym_num = SYM_NUM,
152 		.ocon_num = OCON_NUM,
153 	},
154 	{
155 		.version = POLICYDB_VERSION_COMP_FTRANS,
156 		.sym_num = SYM_NUM,
157 		.ocon_num = OCON_NUM,
158 	},
159 	{
160 		.version = POLICYDB_VERSION_COND_XPERMS,
161 		.sym_num = SYM_NUM,
162 		.ocon_num = OCON_NUM,
163 	},
164 	{
165 		.version = POLICYDB_VERSION_NEVERAUDIT,
166 		.sym_num = SYM_NUM,
167 		.ocon_num = OCON_NUM,
168 	},
169 };
170 
171 static const struct policydb_compat_info *
172 policydb_lookup_compat(unsigned int version)
173 {
174 	unsigned int i;
175 
176 	for (i = 0; i < ARRAY_SIZE(policydb_compat); i++) {
177 		if (policydb_compat[i].version == version)
178 			return &policydb_compat[i];
179 	}
180 
181 	return NULL;
182 }
183 
184 /*
185  * The following *_destroy functions are used to
186  * free any memory allocated for each kind of
187  * symbol data in the policy database.
188  */
189 
190 static int perm_destroy(void *key, void *datum, void *p)
191 {
192 	kfree(key);
193 	kfree(datum);
194 	return 0;
195 }
196 
197 static int common_destroy(void *key, void *datum, void *p)
198 {
199 	struct common_datum *comdatum;
200 
201 	kfree(key);
202 	if (datum) {
203 		comdatum = datum;
204 		hashtab_map(&comdatum->permissions.table, perm_destroy, NULL);
205 		hashtab_destroy(&comdatum->permissions.table);
206 	}
207 	kfree(datum);
208 	return 0;
209 }
210 
211 static void constraint_expr_destroy(struct constraint_expr *expr)
212 {
213 	if (expr) {
214 		ebitmap_destroy(&expr->names);
215 		if (expr->type_names) {
216 			ebitmap_destroy(&expr->type_names->types);
217 			ebitmap_destroy(&expr->type_names->negset);
218 			kfree(expr->type_names);
219 		}
220 		kfree(expr);
221 	}
222 }
223 
224 static int cls_destroy(void *key, void *datum, void *p)
225 {
226 	struct class_datum *cladatum;
227 	struct constraint_node *constraint, *ctemp;
228 	struct constraint_expr *e, *etmp;
229 
230 	kfree(key);
231 	if (datum) {
232 		cladatum = datum;
233 		hashtab_map(&cladatum->permissions.table, perm_destroy, NULL);
234 		hashtab_destroy(&cladatum->permissions.table);
235 		constraint = cladatum->constraints;
236 		while (constraint) {
237 			e = constraint->expr;
238 			while (e) {
239 				etmp = e;
240 				e = e->next;
241 				constraint_expr_destroy(etmp);
242 			}
243 			ctemp = constraint;
244 			constraint = constraint->next;
245 			kfree(ctemp);
246 		}
247 
248 		constraint = cladatum->validatetrans;
249 		while (constraint) {
250 			e = constraint->expr;
251 			while (e) {
252 				etmp = e;
253 				e = e->next;
254 				constraint_expr_destroy(etmp);
255 			}
256 			ctemp = constraint;
257 			constraint = constraint->next;
258 			kfree(ctemp);
259 		}
260 		kfree(cladatum->comkey);
261 	}
262 	kfree(datum);
263 	return 0;
264 }
265 
266 static int role_destroy(void *key, void *datum, void *p)
267 {
268 	struct role_datum *role;
269 
270 	kfree(key);
271 	if (datum) {
272 		role = datum;
273 		ebitmap_destroy(&role->dominates);
274 		ebitmap_destroy(&role->types);
275 	}
276 	kfree(datum);
277 	return 0;
278 }
279 
280 static int type_destroy(void *key, void *datum, void *p)
281 {
282 	kfree(key);
283 	kfree(datum);
284 	return 0;
285 }
286 
287 static int user_destroy(void *key, void *datum, void *p)
288 {
289 	struct user_datum *usrdatum;
290 
291 	kfree(key);
292 	if (datum) {
293 		usrdatum = datum;
294 		ebitmap_destroy(&usrdatum->roles);
295 		ebitmap_destroy(&usrdatum->range.level[0].cat);
296 		ebitmap_destroy(&usrdatum->range.level[1].cat);
297 		ebitmap_destroy(&usrdatum->dfltlevel.cat);
298 	}
299 	kfree(datum);
300 	return 0;
301 }
302 
303 static int sens_destroy(void *key, void *datum, void *p)
304 {
305 	struct level_datum *levdatum;
306 
307 	kfree(key);
308 	if (datum) {
309 		levdatum = datum;
310 		ebitmap_destroy(&levdatum->level.cat);
311 	}
312 	kfree(datum);
313 	return 0;
314 }
315 
316 static int cat_destroy(void *key, void *datum, void *p)
317 {
318 	kfree(key);
319 	kfree(datum);
320 	return 0;
321 }
322 
323 /* clang-format off */
324 static int (*const destroy_f[SYM_NUM])(void *key, void *datum, void *datap) = {
325 	common_destroy,
326 	cls_destroy,
327 	role_destroy,
328 	type_destroy,
329 	user_destroy,
330 	cond_destroy_bool,
331 	sens_destroy,
332 	cat_destroy,
333 };
334 /* clang-format on */
335 
336 static int filenametr_destroy(void *key, void *datum, void *p)
337 {
338 	struct filename_trans_key *ft = key;
339 	struct filename_trans_datum *next, *d = datum;
340 
341 	kfree(ft->name);
342 	kfree(key);
343 	do {
344 		ebitmap_destroy(&d->stypes);
345 		next = d->next;
346 		kfree(d);
347 		d = next;
348 	} while (unlikely(d));
349 	cond_resched();
350 	return 0;
351 }
352 
353 static int range_tr_destroy(void *key, void *datum, void *p)
354 {
355 	struct mls_range *rt = datum;
356 
357 	kfree(key);
358 	ebitmap_destroy(&rt->level[0].cat);
359 	ebitmap_destroy(&rt->level[1].cat);
360 	kfree(datum);
361 	cond_resched();
362 	return 0;
363 }
364 
365 static int role_tr_destroy(void *key, void *datum, void *p)
366 {
367 	kfree(key);
368 	kfree(datum);
369 	return 0;
370 }
371 
372 static void ocontext_destroy(struct ocontext *c, unsigned int i)
373 {
374 	if (!c)
375 		return;
376 
377 	context_destroy(&c->context[0]);
378 	context_destroy(&c->context[1]);
379 	if (i == OCON_ISID || i == OCON_FS || i == OCON_NETIF ||
380 	    i == OCON_FSUSE)
381 		kfree(c->u.name);
382 	kfree(c);
383 }
384 
385 /*
386  * Initialize the role table.
387  */
388 static int roles_init(struct policydb *p)
389 {
390 	char *key = NULL;
391 	int rc;
392 	struct role_datum *role;
393 
394 	role = kzalloc_obj(*role);
395 	if (!role)
396 		return -ENOMEM;
397 
398 	rc = -EINVAL;
399 	role->value = ++p->p_roles.nprim;
400 	if (role->value != OBJECT_R_VAL)
401 		goto out;
402 
403 	rc = -ENOMEM;
404 	key = kstrdup(OBJECT_R, GFP_KERNEL);
405 	if (!key)
406 		goto out;
407 
408 	rc = symtab_insert(&p->p_roles, key, role);
409 	if (rc)
410 		goto out;
411 
412 	return 0;
413 out:
414 	kfree(key);
415 	kfree(role);
416 	return rc;
417 }
418 
419 static u32 filenametr_hash(const void *k)
420 {
421 	const struct filename_trans_key *ft = k;
422 	unsigned long salt = ft->ttype ^ ft->tclass;
423 
424 	return full_name_hash((void *)salt, ft->name, strlen(ft->name));
425 }
426 
427 static int filenametr_cmp(const void *k1, const void *k2)
428 {
429 	const struct filename_trans_key *ft1 = k1;
430 	const struct filename_trans_key *ft2 = k2;
431 	int v;
432 
433 	v = cmp_int(ft1->ttype, ft2->ttype);
434 	if (v)
435 		return v;
436 
437 	v = cmp_int(ft1->tclass, ft2->tclass);
438 	if (v)
439 		return v;
440 
441 	return strcmp(ft1->name, ft2->name);
442 }
443 
444 static const struct hashtab_key_params filenametr_key_params = {
445 	.hash = filenametr_hash,
446 	.cmp = filenametr_cmp,
447 };
448 
449 struct filename_trans_datum *
450 policydb_filenametr_search(struct policydb *p, struct filename_trans_key *key)
451 {
452 	return hashtab_search(&p->filename_trans, key, filenametr_key_params);
453 }
454 
455 static u32 rangetr_hash(const void *k)
456 {
457 	const struct range_trans *key = k;
458 
459 	return key->source_type + (key->target_type << 3) +
460 	       (key->target_class << 5);
461 }
462 
463 static int rangetr_cmp(const void *k1, const void *k2)
464 {
465 	const struct range_trans *key1 = k1, *key2 = k2;
466 	int v;
467 
468 	v = cmp_int(key1->source_type, key2->source_type);
469 	if (v)
470 		return v;
471 
472 	v = cmp_int(key1->target_type, key2->target_type);
473 	if (v)
474 		return v;
475 
476 	v = cmp_int(key1->target_class, key2->target_class);
477 
478 	return v;
479 }
480 
481 static const struct hashtab_key_params rangetr_key_params = {
482 	.hash = rangetr_hash,
483 	.cmp = rangetr_cmp,
484 };
485 
486 struct mls_range *policydb_rangetr_search(struct policydb *p,
487 					  struct range_trans *key)
488 {
489 	return hashtab_search(&p->range_tr, key, rangetr_key_params);
490 }
491 
492 static u32 role_trans_hash(const void *k)
493 {
494 	const struct role_trans_key *key = k;
495 
496 	return jhash_3words(key->role, key->type,
497 			    (u32)key->tclass << 16 | key->tclass, 0);
498 }
499 
500 static int role_trans_cmp(const void *k1, const void *k2)
501 {
502 	const struct role_trans_key *key1 = k1, *key2 = k2;
503 	int v;
504 
505 	v = cmp_int(key1->role, key2->role);
506 	if (v)
507 		return v;
508 
509 	v = cmp_int(key1->type, key2->type);
510 	if (v)
511 		return v;
512 
513 	return cmp_int(key1->tclass, key2->tclass);
514 }
515 
516 static const struct hashtab_key_params roletr_key_params = {
517 	.hash = role_trans_hash,
518 	.cmp = role_trans_cmp,
519 };
520 
521 struct role_trans_datum *policydb_roletr_search(struct policydb *p,
522 						struct role_trans_key *key)
523 {
524 	return hashtab_search(&p->role_tr, key, roletr_key_params);
525 }
526 
527 /*
528  * Initialize a policy database structure.
529  */
530 static void policydb_init(struct policydb *p)
531 {
532 	memset(p, 0, sizeof(*p));
533 
534 	avtab_init(&p->te_avtab);
535 	cond_policydb_init(p);
536 
537 	ebitmap_init(&p->filename_trans_ttypes);
538 	ebitmap_init(&p->policycaps);
539 	ebitmap_init(&p->permissive_map);
540 	ebitmap_init(&p->neveraudit_map);
541 }
542 
543 /*
544  * The following *_index functions are used to
545  * define the val_to_name and val_to_struct arrays
546  * in a policy database structure.  The val_to_name
547  * arrays are used when converting security context
548  * structures into string representations.  The
549  * val_to_struct arrays are used when the attributes
550  * of a class, role, or user are needed.
551  */
552 
553 static int common_index(void *key, void *datum, void *datap)
554 {
555 	struct policydb *p;
556 	struct common_datum *comdatum;
557 
558 	comdatum = datum;
559 	p = datap;
560 	if (!comdatum->value || comdatum->value > p->p_commons.nprim)
561 		return -EINVAL;
562 
563 	if (p->sym_val_to_name[SYM_COMMONS][comdatum->value - 1])
564 		return -EINVAL;
565 
566 	p->sym_val_to_name[SYM_COMMONS][comdatum->value - 1] = key;
567 
568 	return 0;
569 }
570 
571 static int class_index(void *key, void *datum, void *datap)
572 {
573 	struct policydb *p;
574 	struct class_datum *cladatum;
575 
576 	cladatum = datum;
577 	p = datap;
578 	if (!cladatum->value || cladatum->value > p->p_classes.nprim)
579 		return -EINVAL;
580 
581 	if (p->class_val_to_struct[cladatum->value - 1])
582 		return -EINVAL;
583 
584 	p->sym_val_to_name[SYM_CLASSES][cladatum->value - 1] = key;
585 	p->class_val_to_struct[cladatum->value - 1] = cladatum;
586 	return 0;
587 }
588 
589 static int role_index(void *key, void *datum, void *datap)
590 {
591 	struct policydb *p;
592 	struct role_datum *role;
593 
594 	role = datum;
595 	p = datap;
596 	if (!role->value || role->value > p->p_roles.nprim ||
597 	    role->bounds > p->p_roles.nprim)
598 		return -EINVAL;
599 
600 	if (p->role_val_to_struct[role->value - 1])
601 		return -EINVAL;
602 
603 	p->sym_val_to_name[SYM_ROLES][role->value - 1] = key;
604 	p->role_val_to_struct[role->value - 1] = role;
605 	return 0;
606 }
607 
608 static int type_index(void *key, void *datum, void *datap)
609 {
610 	struct policydb *p;
611 	struct type_datum *typdatum;
612 
613 	typdatum = datum;
614 	p = datap;
615 
616 	if (!typdatum->value || typdatum->value > p->p_types.nprim ||
617 		typdatum->bounds > p->p_types.nprim) {
618 		pr_err("SELinux: type %s had value %u bounds %u nprim %u\n",
619 			(char *)key, typdatum->value, typdatum->bounds,
620 			p->p_types.nprim);
621 		return -EINVAL;
622 	}
623 
624 	if (typdatum->primary) {
625 		if (p->type_val_to_struct[typdatum->value - 1])
626 			return -EINVAL;
627 		p->sym_val_to_name[SYM_TYPES][typdatum->value - 1] = key;
628 		p->type_val_to_struct[typdatum->value - 1] = typdatum;
629 	}
630 
631 	return 0;
632 }
633 
634 static int user_index(void *key, void *datum, void *datap)
635 {
636 	struct policydb *p;
637 	struct user_datum *usrdatum;
638 
639 	usrdatum = datum;
640 	p = datap;
641 	if (!usrdatum->value || usrdatum->value > p->p_users.nprim ||
642 	    usrdatum->bounds > p->p_users.nprim)
643 		return -EINVAL;
644 
645 	if (p->user_val_to_struct[usrdatum->value - 1])
646 		return -EINVAL;
647 
648 	p->sym_val_to_name[SYM_USERS][usrdatum->value - 1] = key;
649 	p->user_val_to_struct[usrdatum->value - 1] = usrdatum;
650 	return 0;
651 }
652 
653 static int sens_index(void *key, void *datum, void *datap)
654 {
655 	struct policydb *p;
656 	struct level_datum *levdatum;
657 
658 	levdatum = datum;
659 	p = datap;
660 
661 	if (!levdatum->level.sens || levdatum->level.sens > p->p_levels.nprim)
662 		return -EINVAL;
663 
664 	if (!levdatum->isalias) {
665 		if (p->sym_val_to_name[SYM_LEVELS][levdatum->level.sens - 1])
666 			return -EINVAL;
667 		p->sym_val_to_name[SYM_LEVELS][levdatum->level.sens - 1] = key;
668 	}
669 
670 	return 0;
671 }
672 
673 static int cat_index(void *key, void *datum, void *datap)
674 {
675 	struct policydb *p;
676 	struct cat_datum *catdatum;
677 
678 	catdatum = datum;
679 	p = datap;
680 
681 	if (!catdatum->value || catdatum->value > p->p_cats.nprim)
682 		return -EINVAL;
683 
684 	if (!catdatum->isalias) {
685 		if (p->sym_val_to_name[SYM_CATS][catdatum->value - 1])
686 			return -EINVAL;
687 		p->sym_val_to_name[SYM_CATS][catdatum->value - 1] = key;
688 	}
689 
690 	return 0;
691 }
692 
693 static int sens_cat_index_check(void *key, void *datum, void *datap)
694 {
695 	struct policydb *p = datap;
696 	struct level_datum *levdatum = datum;
697 	struct ebitmap_node *node;
698 	u32 bit;
699 
700 	ebitmap_for_each_positive_bit(&levdatum->level.cat, node, bit) {
701 		if (bit >= p->p_cats.nprim || !sym_name(p, SYM_CATS, bit)) {
702 			pr_err("SELinux: sensitivity %s allows undefined category %u\n",
703 				(const char *)key, bit + 1);
704 			return -EINVAL;
705 		}
706 	}
707 	return 0;
708 }
709 
710 static int role_index_check(void *key, void *datum, void *datap)
711 {
712 	const struct policydb *p = datap;
713 	const struct role_datum *role = datum;
714 	struct ebitmap_node *node;
715 	u32 bit;
716 
717 	ebitmap_for_each_positive_bit(&role->dominates, node, bit) {
718 		if (!policydb_role_isvalid(p, bit + 1)) {
719 			pr_err("SELinux:  role %s declares dominance on undefined role %u\n",
720 			       (const char *)key, bit + 1);
721 			return -EINVAL;
722 		}
723 	}
724 
725 	ebitmap_for_each_positive_bit(&role->types, node, bit) {
726 		if (!policydb_type_isvalid(p, bit + 1)) {
727 			pr_err("SELinux:  role %s authorizes undefined type %u\n",
728 			       (const char *)key, bit + 1);
729 			return -EINVAL;
730 		}
731 	}
732 
733 	return 0;
734 }
735 
736 static int user_index_check(void *key, void *datum, void *datap)
737 {
738 	const struct policydb *p = datap;
739 	const struct user_datum *usr = datum;
740 	struct ebitmap_node *node;
741 	u32 bit;
742 
743 	ebitmap_for_each_positive_bit(&usr->roles, node, bit) {
744 		if (!policydb_role_isvalid(p, bit + 1)) {
745 			pr_err("SELinux:  user %s authorizes undefined role %u\n",
746 			       (const char *)key, bit + 1);
747 			return -EINVAL;
748 		}
749 	}
750 
751 	if (p->mls_enabled) {
752 		if (!mls_range_isvalid(p, &usr->range)) {
753 			pr_err("SELinux:  user %s has an invalid MLS range\n",
754 			       (const char *)key);
755 			return -EINVAL;
756 		}
757 
758 		if (!mls_level_isvalid(p, &usr->dfltlevel)) {
759 			pr_err("SELinux:  user %s has an invalid MLS default level\n",
760 			       (const char *)key);
761 			return -EINVAL;
762 		}
763 	}
764 
765 	return 0;
766 }
767 
768 /* clang-format off */
769 static int (*const index_f[SYM_NUM])(void *key, void *datum, void *datap) = {
770 	common_index,
771 	class_index,
772 	role_index,
773 	type_index,
774 	user_index,
775 	cond_index_bool,
776 	sens_index,
777 	cat_index,
778 };
779 /* clang-format on */
780 
781 #ifdef CONFIG_SECURITY_SELINUX_DEBUG
782 static void hash_eval(struct hashtab *h, const char *hash_name,
783 		      const char *hash_details)
784 {
785 	struct hashtab_info info;
786 
787 	hashtab_stat(h, &info);
788 	pr_debug(
789 		"SELinux: %s%s%s:  %d entries and %d/%d buckets used, longest chain length %d, sum of chain length^2 %llu\n",
790 		hash_name, hash_details ? "@" : "", hash_details ?: "", h->nel,
791 		info.slots_used, h->size, info.max_chain_len,
792 		info.chain2_len_sum);
793 }
794 
795 static void symtab_hash_eval(struct symtab *s)
796 {
797 	int i;
798 
799 	for (i = 0; i < SYM_NUM; i++)
800 		hash_eval(&s[i].table, symtab_name[i], NULL);
801 }
802 
803 #else
804 static inline void hash_eval(struct hashtab *h, const char *hash_name,
805 			     const char *hash_details)
806 {
807 }
808 static inline void symtab_hash_eval(struct symtab *s)
809 {
810 }
811 #endif /* CONFIG_SECURITY_SELINUX_DEBUG */
812 
813 /*
814  * Define the other val_to_name and val_to_struct arrays
815  * in a policy database structure.
816  *
817  * Caller must clean up on failure.
818  */
819 static int policydb_index(struct policydb *p)
820 {
821 	struct ebitmap_node *node;
822 	int i, rc;
823 	u32 bit, v;
824 
825 	if (p->mls_enabled)
826 		pr_debug(
827 			"SELinux:  %d users, %d roles, %d types, %d bools, %d sens, %d cats\n",
828 			p->p_users.nprim, p->p_roles.nprim, p->p_types.nprim,
829 			p->p_bools.nprim, p->p_levels.nprim, p->p_cats.nprim);
830 	else
831 		pr_debug("SELinux:  %d users, %d roles, %d types, %d bools\n",
832 			 p->p_users.nprim, p->p_roles.nprim, p->p_types.nprim,
833 			 p->p_bools.nprim);
834 
835 	pr_debug("SELinux:  %d classes, %d rules\n", p->p_classes.nprim,
836 		 p->te_avtab.nel);
837 
838 	symtab_hash_eval(p->symtab);
839 
840 	p->class_val_to_struct = kzalloc_objs(*p->class_val_to_struct,
841 					      p->p_classes.nprim);
842 	if (!p->class_val_to_struct)
843 		return -ENOMEM;
844 
845 	p->role_val_to_struct = kzalloc_objs(*p->role_val_to_struct,
846 					     p->p_roles.nprim);
847 	if (!p->role_val_to_struct)
848 		return -ENOMEM;
849 
850 	p->user_val_to_struct = kzalloc_objs(*p->user_val_to_struct,
851 					     p->p_users.nprim);
852 	if (!p->user_val_to_struct)
853 		return -ENOMEM;
854 
855 	p->type_val_to_struct = kvzalloc_objs(*p->type_val_to_struct,
856 					      p->p_types.nprim);
857 	if (!p->type_val_to_struct)
858 		return -ENOMEM;
859 
860 	rc = cond_init_bool_indexes(p);
861 	if (rc)
862 		goto out;
863 
864 	for (i = 0; i < SYM_NUM; i++) {
865 		p->sym_val_to_name[i] = kvcalloc(p->symtab[i].nprim,
866 						 sizeof(char *), GFP_KERNEL);
867 		if (!p->sym_val_to_name[i])
868 			return -ENOMEM;
869 
870 		rc = hashtab_map(&p->symtab[i].table, index_f[i], p);
871 		if (rc)
872 			goto out;
873 	}
874 
875 	/*
876 	 * A sparse class value is absorbed by policydb_class_isvalid() and
877 	 * its siblings, but no such predicate exists for booleans: every
878 	 * user of bool_val_to_struct[] walks it by index and dereferences
879 	 * each entry -- cond_evaluate_expr(), the two getters and
880 	 * security_set_bools() -- so an unclaimed one has no consumer that
881 	 * can tolerate it.
882 	 */
883 	for (v = 0; v < p->p_bools.nprim; v++) {
884 		if (!p->bool_val_to_struct[v]) {
885 			pr_err("SELinux:  boolean %u is declared but not defined\n",
886 			       v + 1);
887 			rc = -EINVAL;
888 			goto out;
889 		}
890 	}
891 
892 	if (p->mls_enabled) {
893 		rc = hashtab_map(&p->p_levels.table, sens_cat_index_check, p);
894 		if (rc)
895 			goto out;
896 	}
897 
898 	rc = hashtab_map(&p->p_roles.table, role_index_check, p);
899 	if (rc)
900 		goto out;
901 
902 	rc = hashtab_map(&p->p_users.table, user_index_check, p);
903 	if (rc)
904 		goto out;
905 
906 	ebitmap_for_each_positive_bit(&p->permissive_map, node, bit) {
907 		if (!policydb_simpletype_isvalid(p, bit)) {
908 			pr_err("SELinux:  permissive map refers to invalid type %u\n",
909 			       bit);
910 			rc = -EINVAL;
911 			goto out;
912 		}
913 	}
914 	ebitmap_for_each_positive_bit(&p->neveraudit_map, node, bit) {
915 		if (!policydb_simpletype_isvalid(p, bit)) {
916 			pr_err("SELinux:  neveraudit map refers to invalid type %u\n",
917 			       bit);
918 			rc = -EINVAL;
919 			goto out;
920 		}
921 	}
922 
923 	rc = 0;
924 out:
925 	return rc;
926 }
927 
928 /*
929  * Free any memory allocated by a policy database structure.
930  */
931 void policydb_destroy(struct policydb *p)
932 {
933 	struct ocontext *c, *ctmp;
934 	struct genfs *g, *gtmp;
935 	u32 i;
936 	struct role_allow *ra, *lra = NULL;
937 
938 	for (i = 0; i < SYM_NUM; i++) {
939 		cond_resched();
940 		hashtab_map(&p->symtab[i].table, destroy_f[i], NULL);
941 		hashtab_destroy(&p->symtab[i].table);
942 	}
943 
944 	for (i = 0; i < SYM_NUM; i++)
945 		kvfree(p->sym_val_to_name[i]);
946 
947 	kfree(p->class_val_to_struct);
948 	kfree(p->role_val_to_struct);
949 	kfree(p->user_val_to_struct);
950 	kvfree(p->type_val_to_struct);
951 
952 	avtab_destroy(&p->te_avtab);
953 
954 	for (i = 0; i < OCON_NUM; i++) {
955 		cond_resched();
956 		c = p->ocontexts[i];
957 		while (c) {
958 			ctmp = c;
959 			c = c->next;
960 			ocontext_destroy(ctmp, i);
961 		}
962 		p->ocontexts[i] = NULL;
963 	}
964 
965 	g = p->genfs;
966 	while (g) {
967 		cond_resched();
968 		kfree(g->fstype);
969 		c = g->head;
970 		while (c) {
971 			ctmp = c;
972 			c = c->next;
973 			ocontext_destroy(ctmp, OCON_FSUSE);
974 		}
975 		gtmp = g;
976 		g = g->next;
977 		kfree(gtmp);
978 	}
979 	p->genfs = NULL;
980 
981 	cond_policydb_destroy(p);
982 
983 	hashtab_map(&p->role_tr, role_tr_destroy, NULL);
984 	hashtab_destroy(&p->role_tr);
985 
986 	for (ra = p->role_allow; ra; ra = ra->next) {
987 		cond_resched();
988 		kfree(lra);
989 		lra = ra;
990 	}
991 	kfree(lra);
992 
993 	hashtab_map(&p->filename_trans, filenametr_destroy, NULL);
994 	hashtab_destroy(&p->filename_trans);
995 
996 	hashtab_map(&p->range_tr, range_tr_destroy, NULL);
997 	hashtab_destroy(&p->range_tr);
998 
999 	if (p->type_attr_map_array) {
1000 		for (i = 0; i < p->p_types.nprim; i++)
1001 			ebitmap_destroy(&p->type_attr_map_array[i]);
1002 		kvfree(p->type_attr_map_array);
1003 	}
1004 
1005 	ebitmap_destroy(&p->filename_trans_ttypes);
1006 	ebitmap_destroy(&p->policycaps);
1007 	ebitmap_destroy(&p->permissive_map);
1008 	ebitmap_destroy(&p->neveraudit_map);
1009 }
1010 
1011 /*
1012  * Load the initial SIDs specified in a policy database
1013  * structure into a SID table.
1014  */
1015 int policydb_load_isids(struct policydb *p, struct sidtab *s)
1016 {
1017 	struct ocontext *head, *c;
1018 	bool isid_init;
1019 	int rc;
1020 
1021 	rc = sidtab_init(s);
1022 	if (rc) {
1023 		pr_err("SELinux:  out of memory on SID table init\n");
1024 		return rc;
1025 	}
1026 
1027 	isid_init = ebitmap_get_bit(&p->policycaps,
1028 				    POLICYDB_CAP_USERSPACE_INITIAL_CONTEXT);
1029 
1030 	head = p->ocontexts[OCON_ISID];
1031 	for (c = head; c; c = c->next) {
1032 		u32 sid = c->sid[0];
1033 		const char *name = security_get_initial_sid_context(sid);
1034 
1035 		if (sid == SECSID_NULL) {
1036 			pr_err("SELinux:  SID 0 was assigned a context.\n");
1037 			sidtab_destroy(s);
1038 			return -EINVAL;
1039 		}
1040 
1041 		/* Ignore initial SIDs unused by this kernel. */
1042 		if (!name)
1043 			continue;
1044 
1045 		/*
1046 		 * Also ignore SECINITSID_INIT if the policy doesn't declare
1047 		 * support for it
1048 		 */
1049 		if (sid == SECINITSID_INIT && !isid_init)
1050 			continue;
1051 
1052 		rc = sidtab_set_initial(s, sid, &c->context[0]);
1053 		if (rc) {
1054 			pr_err("SELinux:  unable to load initial SID %s.\n",
1055 			       name);
1056 			sidtab_destroy(s);
1057 			return rc;
1058 		}
1059 
1060 		/*
1061 		 * If the policy doesn't support the "userspace_initial_context"
1062 		 * capability, set SECINITSID_INIT to the same context as
1063 		 * SECINITSID_KERNEL. This ensures the same behavior as before
1064 		 * the reintroduction of SECINITSID_INIT, where all tasks
1065 		 * started before policy load would initially get the context
1066 		 * corresponding to SECINITSID_KERNEL.
1067 		 */
1068 		if (sid == SECINITSID_KERNEL && !isid_init) {
1069 			rc = sidtab_set_initial(s, SECINITSID_INIT,
1070 						&c->context[0]);
1071 			if (rc) {
1072 				pr_err("SELinux:  unable to load initial SID %s.\n",
1073 				       name);
1074 				sidtab_destroy(s);
1075 				return rc;
1076 			}
1077 		}
1078 	}
1079 	return 0;
1080 }
1081 
1082 bool policydb_class_isvalid(const struct policydb *p, u16 class)
1083 {
1084 	if (!class || class > p->p_classes.nprim)
1085 		return false;
1086 	if (!p->sym_val_to_name[SYM_CLASSES][class - 1])
1087 		return false;
1088 	return true;
1089 }
1090 
1091 bool policydb_user_isvalid(const struct policydb *p, u32 user)
1092 {
1093 	if (!user || user > p->p_users.nprim)
1094 		return false;
1095 	if (!p->sym_val_to_name[SYM_USERS][user - 1])
1096 		return false;
1097 	return true;
1098 }
1099 
1100 bool policydb_role_isvalid(const struct policydb *p, u32 role)
1101 {
1102 	if (!role || role > p->p_roles.nprim)
1103 		return false;
1104 	if (!p->sym_val_to_name[SYM_ROLES][role - 1])
1105 		return false;
1106 	return true;
1107 }
1108 
1109 bool policydb_type_isvalid(const struct policydb *p, u32 type)
1110 {
1111 	if (!type || type > p->p_types.nprim)
1112 		return false;
1113 	if (!p->sym_val_to_name[SYM_TYPES][type - 1])
1114 		return false;
1115 	return true;
1116 }
1117 
1118 bool policydb_simpletype_isvalid(const struct policydb *p, u32 type)
1119 {
1120 	const struct type_datum *datum;
1121 
1122 	if (!type || type > p->p_types.nprim)
1123 		return false;
1124 
1125 	datum = p->type_val_to_struct[type - 1];
1126 	if (!datum)
1127 		return false;
1128 
1129 	if (datum->attribute)
1130 		return false;
1131 
1132 	return true;
1133 }
1134 
1135 /*
1136  * Return true if the fields in the security context
1137  * structure `c' are valid.  Return 0 otherwise.
1138  */
1139 bool policydb_context_isvalid(const struct policydb *p, const struct context *c)
1140 {
1141 	const struct role_datum *role;
1142 	const struct user_datum *usrdatum;
1143 
1144 	if (!policydb_role_isvalid(p, c->role))
1145 		return false;
1146 
1147 	if (!policydb_user_isvalid(p, c->user))
1148 		return false;
1149 
1150 	if (!policydb_simpletype_isvalid(p, c->type))
1151 		return false;
1152 
1153 	if (c->role != OBJECT_R_VAL) {
1154 		/*
1155 		 * Role must be authorized for the type.
1156 		 */
1157 		role = p->role_val_to_struct[c->role - 1];
1158 		if (!ebitmap_get_bit(&role->types, c->type - 1))
1159 			/* role may not be associated with type */
1160 			return false;
1161 
1162 		/*
1163 		 * User must be authorized for the role.
1164 		 */
1165 		usrdatum = p->user_val_to_struct[c->user - 1];
1166 		if (!ebitmap_get_bit(&usrdatum->roles, c->role - 1))
1167 			/* user may not be associated with role */
1168 			return false;
1169 	}
1170 
1171 	if (!mls_context_isvalid(p, c))
1172 		return false;
1173 
1174 	return true;
1175 }
1176 
1177 /*
1178  * Read a MLS range structure from a policydb binary
1179  * representation file.
1180  */
1181 static int mls_read_range_helper(struct mls_range *r, struct policy_file *fp)
1182 {
1183 	__le32 buf[2];
1184 	u32 items;
1185 	int rc;
1186 
1187 	rc = next_entry(buf, fp, sizeof(u32));
1188 	if (rc)
1189 		goto out;
1190 
1191 	rc = -EINVAL;
1192 	items = le32_to_cpu(buf[0]);
1193 	if (items > ARRAY_SIZE(buf)) {
1194 		pr_err("SELinux: mls:  range overflow\n");
1195 		goto out;
1196 	}
1197 
1198 	rc = next_entry(buf, fp, sizeof(u32) * items);
1199 	if (rc) {
1200 		pr_err("SELinux: mls:  truncated range\n");
1201 		goto out;
1202 	}
1203 
1204 	r->level[0].sens = le32_to_cpu(buf[0]);
1205 	if (items > 1)
1206 		r->level[1].sens = le32_to_cpu(buf[1]);
1207 	else
1208 		r->level[1].sens = r->level[0].sens;
1209 
1210 	rc = ebitmap_read(&r->level[0].cat, fp);
1211 	if (rc) {
1212 		pr_err("SELinux: mls:  error reading low categories\n");
1213 		goto out;
1214 	}
1215 	if (items > 1) {
1216 		rc = ebitmap_read(&r->level[1].cat, fp);
1217 		if (rc) {
1218 			pr_err("SELinux: mls:  error reading high categories\n");
1219 			goto bad_high;
1220 		}
1221 	} else {
1222 		rc = ebitmap_cpy(&r->level[1].cat, &r->level[0].cat);
1223 		if (rc) {
1224 			pr_err("SELinux: mls:  out of memory\n");
1225 			goto bad_high;
1226 		}
1227 	}
1228 
1229 	return 0;
1230 bad_high:
1231 	ebitmap_destroy(&r->level[0].cat);
1232 out:
1233 	return rc;
1234 }
1235 
1236 /*
1237  * Read and validate a security context structure
1238  * from a policydb binary representation file.
1239  */
1240 static int context_read_and_validate(struct context *c, struct policydb *p,
1241 				     struct policy_file *fp)
1242 {
1243 	__le32 buf[3];
1244 	int rc;
1245 
1246 	rc = next_entry(buf, fp, sizeof buf);
1247 	if (rc) {
1248 		pr_err("SELinux: context truncated\n");
1249 		goto out;
1250 	}
1251 	c->user = le32_to_cpu(buf[0]);
1252 	c->role = le32_to_cpu(buf[1]);
1253 	c->type = le32_to_cpu(buf[2]);
1254 	if (p->policyvers >= POLICYDB_VERSION_MLS) {
1255 		rc = mls_read_range_helper(&c->range, fp);
1256 		if (rc) {
1257 			pr_err("SELinux: error reading MLS range of context\n");
1258 			goto out;
1259 		}
1260 	}
1261 
1262 	rc = -EINVAL;
1263 	if (!policydb_context_isvalid(p, c)) {
1264 		pr_err("SELinux:  invalid security context\n");
1265 		context_destroy(c);
1266 		goto out;
1267 	}
1268 	rc = 0;
1269 out:
1270 	return rc;
1271 }
1272 
1273 /*
1274  * The following *_read functions are used to
1275  * read the symbol data from a policy database
1276  * binary representation file.
1277  */
1278 
1279 int str_read(char **strp, gfp_t flags, struct policy_file *fp, u32 len)
1280 {
1281 	int rc;
1282 	char *str;
1283 
1284 	if ((len == 0) || (len == (u32)-1))
1285 		return -EINVAL;
1286 
1287 	if (size_check(sizeof(char), len, fp))
1288 		return -EINVAL;
1289 
1290 	str = kmalloc(len + 1, flags | __GFP_NOWARN);
1291 	if (!str)
1292 		return -ENOMEM;
1293 
1294 	rc = next_entry(str, fp, len);
1295 	if (rc) {
1296 		kfree(str);
1297 		return rc;
1298 	}
1299 
1300 	str[len] = '\0';
1301 	*strp = str;
1302 	return 0;
1303 }
1304 
1305 /*
1306  * Bitmap of the permission values a symtab has claimed.  Values are 1-based
1307  * and bounded by SEL_VEC_MAX, the width of an access vector, so the whole set
1308  * fits in a u32 and the callers reject an nprim past that width.
1309  */
1310 static u32 perm_claimed_mask(u32 nprim)
1311 {
1312 	return nprim ? U32_MAX >> (SEL_VEC_MAX - nprim) : 0;
1313 }
1314 
1315 static int perm_read(struct policydb *p, struct symtab *s,
1316 		     struct policy_file *fp, u32 *claimed)
1317 {
1318 	char *key = NULL;
1319 	struct perm_datum *perdatum;
1320 	int rc;
1321 	__le32 buf[2];
1322 	u32 len;
1323 
1324 	perdatum = kzalloc_obj(*perdatum);
1325 	if (!perdatum)
1326 		return -ENOMEM;
1327 
1328 	rc = next_entry(buf, fp, sizeof buf);
1329 	if (rc)
1330 		goto bad;
1331 
1332 	len = le32_to_cpu(buf[0]);
1333 	perdatum->value = le32_to_cpu(buf[1]);
1334 	rc = -EINVAL;
1335 	if (perdatum->value < 1 || perdatum->value > SEL_VEC_MAX)
1336 		goto bad;
1337 	/* indexes an nprim-sized array in security_get_permissions() */
1338 	if (perdatum->value > s->nprim)
1339 		goto bad;
1340 	/* two permissions cannot share one slot of that array */
1341 	if (*claimed & (1U << (perdatum->value - 1)))
1342 		goto bad;
1343 	*claimed |= 1U << (perdatum->value - 1);
1344 
1345 	rc = str_read(&key, GFP_KERNEL, fp, len);
1346 	if (rc)
1347 		goto bad;
1348 
1349 	rc = symtab_insert(s, key, perdatum);
1350 	if (rc)
1351 		goto bad;
1352 
1353 	return 0;
1354 bad:
1355 	perm_destroy(key, perdatum, NULL);
1356 	return rc;
1357 }
1358 
1359 static int common_read(struct policydb *p, struct symtab *s, struct policy_file *fp)
1360 {
1361 	char *key = NULL;
1362 	struct common_datum *comdatum;
1363 	__le32 buf[4];
1364 	u32 i, len, nel, claimed = 0;
1365 	int rc;
1366 
1367 	comdatum = kzalloc_obj(*comdatum);
1368 	if (!comdatum)
1369 		return -ENOMEM;
1370 
1371 	rc = next_entry(buf, fp, sizeof buf);
1372 	if (rc)
1373 		goto bad;
1374 
1375 	len = le32_to_cpu(buf[0]);
1376 	comdatum->value = le32_to_cpu(buf[1]);
1377 	nel = le32_to_cpu(buf[3]);
1378 	rc = -EINVAL;
1379 	if (nel > SEL_VEC_MAX)
1380 		goto bad;
1381 
1382 	/* perm_read() reads at least 64 bytes for any valid permission */
1383 	rc = size_check(2 * sizeof(u32), nel, fp);
1384 	if (rc)
1385 		goto bad;
1386 
1387 	rc = symtab_init(&comdatum->permissions, nel);
1388 	if (rc)
1389 		goto bad;
1390 	comdatum->permissions.nprim = le32_to_cpu(buf[2]);
1391 	/* no permission value can reach a slot past SEL_VEC_MAX */
1392 	rc = -EINVAL;
1393 	if (comdatum->permissions.nprim > SEL_VEC_MAX)
1394 		goto bad;
1395 
1396 	rc = str_read(&key, GFP_KERNEL, fp, len);
1397 	if (rc)
1398 		goto bad;
1399 
1400 	for (i = 0; i < nel; i++) {
1401 		rc = perm_read(p, &comdatum->permissions, fp, &claimed);
1402 		if (rc)
1403 			goto bad;
1404 	}
1405 
1406 	rc = -EINVAL;
1407 	if (claimed != perm_claimed_mask(comdatum->permissions.nprim)) {
1408 		pr_err("SELinux:  common %s does not define every permission it declares\n",
1409 		       key);
1410 		goto bad;
1411 	}
1412 
1413 	hash_eval(&comdatum->permissions.table, "common_permissions", key);
1414 
1415 	rc = symtab_insert(s, key, comdatum);
1416 	if (rc)
1417 		goto bad;
1418 	return 0;
1419 bad:
1420 	common_destroy(key, comdatum, NULL);
1421 	return rc;
1422 }
1423 
1424 static void type_set_init(struct type_set *t)
1425 {
1426 	ebitmap_init(&t->types);
1427 	ebitmap_init(&t->negset);
1428 }
1429 
1430 static int type_set_read(struct type_set *t, struct policy_file *fp)
1431 {
1432 	__le32 buf[1];
1433 	int rc;
1434 
1435 	if (ebitmap_read(&t->types, fp))
1436 		return -EINVAL;
1437 	if (ebitmap_read(&t->negset, fp))
1438 		return -EINVAL;
1439 
1440 	rc = next_entry(buf, fp, sizeof(u32));
1441 	if (rc < 0)
1442 		return -EINVAL;
1443 	t->flags = le32_to_cpu(buf[0]);
1444 
1445 	return 0;
1446 }
1447 
1448 static int read_cons_helper(struct policydb *p, struct constraint_node **nodep,
1449 			    u32 ncons, int allowxtarget, struct policy_file *fp)
1450 {
1451 	struct constraint_node *c, *lc;
1452 	struct constraint_expr *e, *le;
1453 	__le32 buf[3];
1454 	u32 i, j, nexpr;
1455 	int rc, depth;
1456 
1457 	lc = NULL;
1458 	for (i = 0; i < ncons; i++) {
1459 		c = kzalloc_obj(*c);
1460 		if (!c)
1461 			return -ENOMEM;
1462 
1463 		if (lc)
1464 			lc->next = c;
1465 		else
1466 			*nodep = c;
1467 
1468 		rc = next_entry(buf, fp, (sizeof(u32) * 2));
1469 		if (rc)
1470 			return rc;
1471 		c->permissions = le32_to_cpu(buf[0]);
1472 		nexpr = le32_to_cpu(buf[1]);
1473 		le = NULL;
1474 		depth = -1;
1475 		for (j = 0; j < nexpr; j++) {
1476 			e = kzalloc_obj(*e);
1477 			if (!e)
1478 				return -ENOMEM;
1479 
1480 			if (le)
1481 				le->next = e;
1482 			else
1483 				c->expr = e;
1484 
1485 			rc = next_entry(buf, fp, (sizeof(u32) * 3));
1486 			if (rc)
1487 				return rc;
1488 			e->expr_type = le32_to_cpu(buf[0]);
1489 			e->attr = le32_to_cpu(buf[1]);
1490 			e->op = le32_to_cpu(buf[2]);
1491 
1492 			switch (e->expr_type) {
1493 			case CEXPR_NOT:
1494 				if (depth < 0)
1495 					return -EINVAL;
1496 				break;
1497 			case CEXPR_AND:
1498 			case CEXPR_OR:
1499 				if (depth < 1)
1500 					return -EINVAL;
1501 				depth--;
1502 				break;
1503 			case CEXPR_ATTR:
1504 				if (depth == (CEXPR_MAXDEPTH - 1))
1505 					return -EINVAL;
1506 				depth++;
1507 				switch (e->attr) {
1508 				case CEXPR_USER:
1509 				case CEXPR_TYPE:
1510 					if (e->op != CEXPR_EQ &&
1511 					    e->op != CEXPR_NEQ)
1512 						return -EINVAL;
1513 					break;
1514 				case CEXPR_ROLE:
1515 				case CEXPR_L1L2:
1516 				case CEXPR_L1H2:
1517 				case CEXPR_H1L2:
1518 				case CEXPR_H1H2:
1519 				case CEXPR_L1H1:
1520 				case CEXPR_L2H2:
1521 					if (e->op < CEXPR_EQ ||
1522 					    e->op > CEXPR_INCOMP)
1523 						return -EINVAL;
1524 					break;
1525 				default:
1526 					return -EINVAL;
1527 				}
1528 				break;
1529 			case CEXPR_NAMES:
1530 				if (!allowxtarget && (e->attr & CEXPR_XTARGET))
1531 					return -EINVAL;
1532 				if (depth == (CEXPR_MAXDEPTH - 1))
1533 					return -EINVAL;
1534 				depth++;
1535 				switch (e->attr &
1536 					~(CEXPR_TARGET|CEXPR_XTARGET)) {
1537 				case CEXPR_USER:
1538 				case CEXPR_ROLE:
1539 				case CEXPR_TYPE:
1540 					break;
1541 				default:
1542 					return -EINVAL;
1543 				}
1544 				if ((e->attr & (CEXPR_TARGET|CEXPR_XTARGET)) ==
1545 					(CEXPR_TARGET|CEXPR_XTARGET))
1546 					return -EINVAL;
1547 				if (e->op != CEXPR_EQ && e->op != CEXPR_NEQ)
1548 					return -EINVAL;
1549 				rc = ebitmap_read(&e->names, fp);
1550 				if (rc)
1551 					return rc;
1552 				if (p->policyvers >=
1553 				    POLICYDB_VERSION_CONSTRAINT_NAMES) {
1554 					e->type_names = kzalloc_obj(*e->type_names);
1555 					if (!e->type_names)
1556 						return -ENOMEM;
1557 					type_set_init(e->type_names);
1558 					rc = type_set_read(e->type_names, fp);
1559 					if (rc)
1560 						return rc;
1561 				}
1562 				break;
1563 			default:
1564 				return -EINVAL;
1565 			}
1566 			le = e;
1567 		}
1568 		if (depth != 0)
1569 			return -EINVAL;
1570 		lc = c;
1571 	}
1572 
1573 	return 0;
1574 }
1575 
1576 static int class_read(struct policydb *p, struct symtab *s, struct policy_file *fp)
1577 {
1578 	char *key = NULL;
1579 	struct class_datum *cladatum;
1580 	__le32 buf[6];
1581 	u32 i, len, len2, ncons, nel, val, claimed = 0, inherited = 0;
1582 	int rc;
1583 
1584 	cladatum = kzalloc_obj(*cladatum);
1585 	if (!cladatum)
1586 		return -ENOMEM;
1587 
1588 	rc = next_entry(buf, fp, sizeof(u32) * 6);
1589 	if (rc)
1590 		goto bad;
1591 
1592 	len = le32_to_cpu(buf[0]);
1593 	len2 = le32_to_cpu(buf[1]);
1594 	nel = le32_to_cpu(buf[4]);
1595 	rc = -EINVAL;
1596 	if (nel > SEL_VEC_MAX)
1597 		goto bad;
1598 
1599 	val = le32_to_cpu(buf[2]);
1600 	rc = -EINVAL;
1601 	if (val > U16_MAX)
1602 		goto bad;
1603 	cladatum->value = val;
1604 
1605 	/* perm_read() reads at least 64 bytes for any valid permission */
1606 	rc = size_check(2 * sizeof(u32), nel, fp);
1607 	if (rc)
1608 		goto bad;
1609 
1610 	rc = symtab_init(&cladatum->permissions, nel);
1611 	if (rc)
1612 		goto bad;
1613 	cladatum->permissions.nprim = le32_to_cpu(buf[3]);
1614 	/* no permission value can reach a slot past SEL_VEC_MAX */
1615 	rc = -EINVAL;
1616 	if (cladatum->permissions.nprim > SEL_VEC_MAX)
1617 		goto bad;
1618 
1619 	ncons = le32_to_cpu(buf[5]);
1620 
1621 	rc = str_read(&key, GFP_KERNEL, fp, len);
1622 	if (rc)
1623 		goto bad;
1624 
1625 	if (len2) {
1626 		rc = str_read(&cladatum->comkey, GFP_KERNEL, fp, len2);
1627 		if (rc)
1628 			goto bad;
1629 
1630 		rc = -EINVAL;
1631 		cladatum->comdatum =
1632 			symtab_search(&p->p_commons, cladatum->comkey);
1633 		if (!cladatum->comdatum) {
1634 			pr_err("SELinux:  unknown common %s\n",
1635 			       cladatum->comkey);
1636 			goto bad;
1637 		}
1638 
1639 		/*
1640 		 * security_get_permissions() maps the common's permissions
1641 		 * into an array sized by this class's nprim, so a class must
1642 		 * declare at least as many as the common it inherits.
1643 		 */
1644 		if (cladatum->permissions.nprim <
1645 		    cladatum->comdatum->permissions.nprim) {
1646 			pr_err("SELinux:  class %s has fewer permissions than common %s\n",
1647 			       key, cladatum->comkey);
1648 			goto bad;
1649 		}
1650 	}
1651 	for (i = 0; i < nel; i++) {
1652 		rc = perm_read(p, &cladatum->permissions, fp, &claimed);
1653 		if (rc)
1654 			goto bad;
1655 	}
1656 
1657 	/* the class's own permissions must claim the slots the common leaves */
1658 	if (cladatum->comdatum)
1659 		inherited = cladatum->comdatum->permissions.nprim;
1660 	rc = -EINVAL;
1661 	if (claimed != (perm_claimed_mask(cladatum->permissions.nprim) &
1662 			~perm_claimed_mask(inherited))) {
1663 		pr_err("SELinux:  class %s does not define every permission it declares\n",
1664 		       key);
1665 		goto bad;
1666 	}
1667 
1668 	hash_eval(&cladatum->permissions.table, "class_permissions", key);
1669 
1670 	rc = read_cons_helper(p, &cladatum->constraints, ncons, 0, fp);
1671 	if (rc)
1672 		goto bad;
1673 
1674 	if (p->policyvers >= POLICYDB_VERSION_VALIDATETRANS) {
1675 		/* grab the validatetrans rules */
1676 		rc = next_entry(buf, fp, sizeof(u32));
1677 		if (rc)
1678 			goto bad;
1679 		ncons = le32_to_cpu(buf[0]);
1680 		rc = read_cons_helper(p, &cladatum->validatetrans, ncons, 1,
1681 				      fp);
1682 		if (rc)
1683 			goto bad;
1684 	}
1685 
1686 	if (p->policyvers >= POLICYDB_VERSION_NEW_OBJECT_DEFAULTS) {
1687 		rc = next_entry(buf, fp, sizeof(u32) * 3);
1688 		if (rc)
1689 			goto bad;
1690 
1691 		rc = -EINVAL;
1692 		val = le32_to_cpu(buf[0]);
1693 		switch (val) {
1694 		case 0:
1695 		case DEFAULT_SOURCE:
1696 		case DEFAULT_TARGET:
1697 			cladatum->default_user = val;
1698 			break;
1699 		default:
1700 			goto bad;
1701 		}
1702 		val = le32_to_cpu(buf[1]);
1703 		switch (val) {
1704 		case 0:
1705 		case DEFAULT_SOURCE:
1706 		case DEFAULT_TARGET:
1707 			cladatum->default_role = val;
1708 			break;
1709 		default:
1710 			goto bad;
1711 		}
1712 		val = le32_to_cpu(buf[2]);
1713 		switch (val) {
1714 		case 0:
1715 		case DEFAULT_SOURCE_LOW:
1716 		case DEFAULT_SOURCE_HIGH:
1717 		case DEFAULT_SOURCE_LOW_HIGH:
1718 		case DEFAULT_TARGET_LOW:
1719 		case DEFAULT_TARGET_HIGH:
1720 		case DEFAULT_TARGET_LOW_HIGH:
1721 		case DEFAULT_GLBLUB:
1722 			cladatum->default_range = val;
1723 			break;
1724 		default:
1725 			goto bad;
1726 		}
1727 	}
1728 
1729 	if (p->policyvers >= POLICYDB_VERSION_DEFAULT_TYPE) {
1730 		rc = next_entry(buf, fp, sizeof(u32) * 1);
1731 		if (rc)
1732 			goto bad;
1733 		rc = -EINVAL;
1734 		val = le32_to_cpu(buf[0]);
1735 		switch (val) {
1736 		case 0:
1737 		case DEFAULT_TARGET:
1738 		case DEFAULT_SOURCE:
1739 			cladatum->default_type = val;
1740 			break;
1741 		default:
1742 			goto bad;
1743 		}
1744 	}
1745 
1746 	rc = symtab_insert(s, key, cladatum);
1747 	if (rc)
1748 		goto bad;
1749 
1750 	return 0;
1751 bad:
1752 	cls_destroy(key, cladatum, NULL);
1753 	if (rc)
1754 		pr_err("SELinux:  invalid class\n");
1755 	return rc;
1756 }
1757 
1758 static int role_read(struct policydb *p, struct symtab *s, struct policy_file *fp)
1759 {
1760 	char *key = NULL;
1761 	struct role_datum *role;
1762 	int rc;
1763 	unsigned int to_read = 2;
1764 	__le32 buf[3];
1765 	u32 len;
1766 
1767 	role = kzalloc_obj(*role);
1768 	if (!role)
1769 		return -ENOMEM;
1770 
1771 	if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
1772 		to_read = 3;
1773 
1774 	rc = next_entry(buf, fp, sizeof(buf[0]) * to_read);
1775 	if (rc)
1776 		goto bad;
1777 
1778 	len = le32_to_cpu(buf[0]);
1779 	role->value = le32_to_cpu(buf[1]);
1780 	if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
1781 		role->bounds = le32_to_cpu(buf[2]);
1782 
1783 	rc = str_read(&key, GFP_KERNEL, fp, len);
1784 	if (rc)
1785 		goto bad;
1786 
1787 	rc = ebitmap_read(&role->dominates, fp);
1788 	if (rc)
1789 		goto bad;
1790 
1791 	rc = ebitmap_read(&role->types, fp);
1792 	if (rc)
1793 		goto bad;
1794 
1795 	if (strcmp(key, OBJECT_R) == 0) {
1796 		rc = -EINVAL;
1797 		if (role->value != OBJECT_R_VAL) {
1798 			pr_err("SELinux: Role %s has wrong value %d\n",
1799 			       OBJECT_R, role->value);
1800 			goto bad;
1801 		}
1802 		rc = 0;
1803 		goto bad;
1804 	}
1805 
1806 	rc = symtab_insert(s, key, role);
1807 	if (rc)
1808 		goto bad;
1809 	return 0;
1810 bad:
1811 	role_destroy(key, role, NULL);
1812 	return rc;
1813 }
1814 
1815 static int type_read(struct policydb *p, struct symtab *s, struct policy_file *fp)
1816 {
1817 	char *key = NULL;
1818 	struct type_datum *typdatum;
1819 	int rc;
1820 	unsigned int to_read = 3;
1821 	__le32 buf[4];
1822 	u32 len;
1823 
1824 	typdatum = kzalloc_obj(*typdatum);
1825 	if (!typdatum)
1826 		return -ENOMEM;
1827 
1828 	if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
1829 		to_read = 4;
1830 
1831 	rc = next_entry(buf, fp, sizeof(buf[0]) * to_read);
1832 	if (rc)
1833 		goto bad;
1834 
1835 	len = le32_to_cpu(buf[0]);
1836 	typdatum->value = le32_to_cpu(buf[1]);
1837 	if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) {
1838 		u32 prop = le32_to_cpu(buf[2]);
1839 
1840 		if (prop & TYPEDATUM_PROPERTY_PRIMARY)
1841 			typdatum->primary = 1;
1842 		if (prop & TYPEDATUM_PROPERTY_ATTRIBUTE)
1843 			typdatum->attribute = 1;
1844 
1845 		typdatum->bounds = le32_to_cpu(buf[3]);
1846 	} else {
1847 		typdatum->primary = le32_to_cpu(buf[2]);
1848 	}
1849 
1850 	rc = str_read(&key, GFP_KERNEL, fp, len);
1851 	if (rc)
1852 		goto bad;
1853 
1854 	rc = symtab_insert(s, key, typdatum);
1855 	if (rc)
1856 		goto bad;
1857 	return 0;
1858 bad:
1859 	type_destroy(key, typdatum, NULL);
1860 	return rc;
1861 }
1862 
1863 /*
1864  * Read a MLS level structure from a policydb binary
1865  * representation file.
1866  */
1867 static int mls_read_level(struct mls_level *lp, struct policy_file *fp)
1868 {
1869 	__le32 buf[1];
1870 	int rc;
1871 
1872 	memset(lp, 0, sizeof(*lp));
1873 
1874 	rc = next_entry(buf, fp, sizeof buf);
1875 	if (rc) {
1876 		pr_err("SELinux: mls: truncated level\n");
1877 		return rc;
1878 	}
1879 	lp->sens = le32_to_cpu(buf[0]);
1880 
1881 	rc = ebitmap_read(&lp->cat, fp);
1882 	if (rc) {
1883 		pr_err("SELinux: mls:  error reading level categories\n");
1884 		return rc;
1885 	}
1886 	return 0;
1887 }
1888 
1889 static int user_read(struct policydb *p, struct symtab *s, struct policy_file *fp)
1890 {
1891 	char *key = NULL;
1892 	struct user_datum *usrdatum;
1893 	int rc;
1894 	unsigned int to_read = 2;
1895 	__le32 buf[3];
1896 	u32 len;
1897 
1898 	usrdatum = kzalloc_obj(*usrdatum);
1899 	if (!usrdatum)
1900 		return -ENOMEM;
1901 
1902 	if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
1903 		to_read = 3;
1904 
1905 	rc = next_entry(buf, fp, sizeof(buf[0]) * to_read);
1906 	if (rc)
1907 		goto bad;
1908 
1909 	len = le32_to_cpu(buf[0]);
1910 	usrdatum->value = le32_to_cpu(buf[1]);
1911 	if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
1912 		usrdatum->bounds = le32_to_cpu(buf[2]);
1913 
1914 	rc = str_read(&key, GFP_KERNEL, fp, len);
1915 	if (rc)
1916 		goto bad;
1917 
1918 	rc = ebitmap_read(&usrdatum->roles, fp);
1919 	if (rc)
1920 		goto bad;
1921 
1922 	if (p->policyvers >= POLICYDB_VERSION_MLS) {
1923 		rc = mls_read_range_helper(&usrdatum->range, fp);
1924 		if (rc)
1925 			goto bad;
1926 		rc = mls_read_level(&usrdatum->dfltlevel, fp);
1927 		if (rc)
1928 			goto bad;
1929 	}
1930 
1931 	rc = symtab_insert(s, key, usrdatum);
1932 	if (rc)
1933 		goto bad;
1934 	return 0;
1935 bad:
1936 	user_destroy(key, usrdatum, NULL);
1937 	return rc;
1938 }
1939 
1940 static int sens_read(struct policydb *p, struct symtab *s, struct policy_file *fp)
1941 {
1942 	char *key = NULL;
1943 	struct level_datum *levdatum;
1944 	int rc;
1945 	__le32 buf[2];
1946 	u32 len, val;
1947 
1948 	levdatum = kzalloc_obj(*levdatum);
1949 	if (!levdatum)
1950 		return -ENOMEM;
1951 
1952 	rc = next_entry(buf, fp, sizeof buf);
1953 	if (rc)
1954 		goto bad;
1955 
1956 	len = le32_to_cpu(buf[0]);
1957 	val = le32_to_cpu(buf[1]);
1958 	rc = -EINVAL;
1959 	if (!val_is_boolean(val))
1960 		goto bad;
1961 	levdatum->isalias = val;
1962 
1963 	rc = str_read(&key, GFP_KERNEL, fp, len);
1964 	if (rc)
1965 		goto bad;
1966 
1967 	rc = mls_read_level(&levdatum->level, fp);
1968 	if (rc)
1969 		goto bad;
1970 
1971 	rc = symtab_insert(s, key, levdatum);
1972 	if (rc)
1973 		goto bad;
1974 	return 0;
1975 bad:
1976 	sens_destroy(key, levdatum, NULL);
1977 	if (rc)
1978 		pr_err("SELinux:  invalid sensitivity\n");
1979 	return rc;
1980 }
1981 
1982 static int cat_read(struct policydb *p, struct symtab *s, struct policy_file *fp)
1983 {
1984 	char *key = NULL;
1985 	struct cat_datum *catdatum;
1986 	int rc;
1987 	__le32 buf[3];
1988 	u32 len, val;
1989 
1990 	catdatum = kzalloc_obj(*catdatum);
1991 	if (!catdatum)
1992 		return -ENOMEM;
1993 
1994 	rc = next_entry(buf, fp, sizeof buf);
1995 	if (rc)
1996 		goto bad;
1997 
1998 	len = le32_to_cpu(buf[0]);
1999 	catdatum->value = le32_to_cpu(buf[1]);
2000 	val = le32_to_cpu(buf[2]);
2001 	rc = -EINVAL;
2002 	if (!val_is_boolean(val))
2003 		goto bad;
2004 	catdatum->isalias = val;
2005 
2006 	rc = str_read(&key, GFP_KERNEL, fp, len);
2007 	if (rc)
2008 		goto bad;
2009 
2010 	rc = symtab_insert(s, key, catdatum);
2011 	if (rc)
2012 		goto bad;
2013 	return 0;
2014 bad:
2015 	cat_destroy(key, catdatum, NULL);
2016 	if (rc)
2017 		pr_err("SELinux:  invalid category\n");
2018 	return rc;
2019 }
2020 
2021 /* clang-format off */
2022 static int (*const read_f[SYM_NUM])(struct policydb *p, struct symtab *s,
2023 				    struct policy_file *fp) = {
2024 	common_read,
2025 	class_read,
2026 	role_read,
2027 	type_read,
2028 	user_read,
2029 	cond_read_bool,
2030 	sens_read,
2031 	cat_read,
2032 };
2033 /* clang-format on */
2034 
2035 static int user_bounds_sanity_check(void *key, void *datum, void *datap)
2036 {
2037 	struct user_datum *upper, *user;
2038 	struct policydb *p = datap;
2039 	int depth = 0;
2040 
2041 	upper = user = datum;
2042 	while (upper->bounds) {
2043 		struct ebitmap_node *node;
2044 		u32 bit;
2045 
2046 		if (++depth == POLICYDB_BOUNDS_MAXDEPTH) {
2047 			pr_err("SELinux: user %s: "
2048 			       "too deep or looped boundary\n",
2049 			       (char *)key);
2050 			return -EINVAL;
2051 		}
2052 
2053 		if (!policydb_user_isvalid(p, upper->bounds)) {
2054 			pr_err("SELinux: user %s: invalid boundary id %d\n",
2055 			       (char *) key, upper->bounds);
2056 			return -EINVAL;
2057 		}
2058 
2059 		upper = p->user_val_to_struct[upper->bounds - 1];
2060 		ebitmap_for_each_positive_bit(&user->roles, node, bit)
2061 		{
2062 			if (ebitmap_get_bit(&upper->roles, bit))
2063 				continue;
2064 
2065 			pr_err("SELinux: boundary violated policy: "
2066 			       "user=%s role=%s bounds=%s\n",
2067 			       sym_name(p, SYM_USERS, user->value - 1),
2068 			       sym_name(p, SYM_ROLES, bit),
2069 			       sym_name(p, SYM_USERS, upper->value - 1));
2070 
2071 			return -EINVAL;
2072 		}
2073 	}
2074 
2075 	return 0;
2076 }
2077 
2078 static int role_bounds_sanity_check(void *key, void *datum, void *datap)
2079 {
2080 	struct role_datum *upper, *role;
2081 	struct policydb *p = datap;
2082 	int depth = 0;
2083 
2084 	upper = role = datum;
2085 	while (upper->bounds) {
2086 		struct ebitmap_node *node;
2087 		u32 bit;
2088 
2089 		if (++depth == POLICYDB_BOUNDS_MAXDEPTH) {
2090 			pr_err("SELinux: role %s: "
2091 			       "too deep or looped bounds\n",
2092 			       (char *)key);
2093 			return -EINVAL;
2094 		}
2095 
2096 		if (!policydb_role_isvalid(p, upper->bounds)) {
2097 			pr_err("SELinux: role %s: invalid boundary id %d\n",
2098 			       (char *) key, upper->bounds);
2099 			return -EINVAL;
2100 		}
2101 
2102 		upper = p->role_val_to_struct[upper->bounds - 1];
2103 		ebitmap_for_each_positive_bit(&role->types, node, bit)
2104 		{
2105 			if (ebitmap_get_bit(&upper->types, bit))
2106 				continue;
2107 
2108 			pr_err("SELinux: boundary violated policy: "
2109 			       "role=%s type=%s bounds=%s\n",
2110 			       sym_name(p, SYM_ROLES, role->value - 1),
2111 			       sym_name(p, SYM_TYPES, bit),
2112 			       sym_name(p, SYM_ROLES, upper->value - 1));
2113 
2114 			return -EINVAL;
2115 		}
2116 	}
2117 
2118 	return 0;
2119 }
2120 
2121 static int type_bounds_sanity_check(void *key, void *datum, void *datap)
2122 {
2123 	struct type_datum *upper;
2124 	struct policydb *p = datap;
2125 	int depth = 0;
2126 
2127 	upper = datum;
2128 	while (upper->bounds) {
2129 		if (++depth == POLICYDB_BOUNDS_MAXDEPTH) {
2130 			pr_err("SELinux: type %s: "
2131 			       "too deep or looped boundary\n",
2132 			       (char *)key);
2133 			return -EINVAL;
2134 		}
2135 
2136 		if (!policydb_type_isvalid(p, upper->bounds)) {
2137 			pr_err("SELinux: type %s: invalid boundary id %d\n",
2138 			       (char *) key, upper->bounds);
2139 			return -EINVAL;
2140 		}
2141 
2142 		upper = p->type_val_to_struct[upper->bounds - 1];
2143 		if (upper->attribute) {
2144 			pr_err("SELinux: type %s: "
2145 			       "bounded by attribute %s\n",
2146 			       (char *)key,
2147 			       sym_name(p, SYM_TYPES, upper->value - 1));
2148 			return -EINVAL;
2149 		}
2150 	}
2151 
2152 	return 0;
2153 }
2154 
2155 static int policydb_bounds_sanity_check(struct policydb *p)
2156 {
2157 	int rc;
2158 
2159 	if (p->policyvers < POLICYDB_VERSION_BOUNDARY)
2160 		return 0;
2161 
2162 	rc = hashtab_map(&p->p_users.table, user_bounds_sanity_check, p);
2163 	if (rc)
2164 		return rc;
2165 
2166 	rc = hashtab_map(&p->p_roles.table, role_bounds_sanity_check, p);
2167 	if (rc)
2168 		return rc;
2169 
2170 	rc = hashtab_map(&p->p_types.table, type_bounds_sanity_check, p);
2171 	if (rc)
2172 		return rc;
2173 
2174 	return 0;
2175 }
2176 
2177 u16 string_to_security_class(struct policydb *p, const char *name)
2178 {
2179 	struct class_datum *cladatum;
2180 
2181 	cladatum = symtab_search(&p->p_classes, name);
2182 	if (!cladatum)
2183 		return 0;
2184 
2185 	return cladatum->value;
2186 }
2187 
2188 u32 string_to_av_perm(struct policydb *p, u16 tclass, const char *name)
2189 {
2190 	struct class_datum *cladatum;
2191 	struct perm_datum *perdatum = NULL;
2192 	struct common_datum *comdatum;
2193 
2194 	if (!tclass || tclass > p->p_classes.nprim)
2195 		return 0;
2196 
2197 	cladatum = p->class_val_to_struct[tclass - 1];
2198 	comdatum = cladatum->comdatum;
2199 	if (comdatum)
2200 		perdatum = symtab_search(&comdatum->permissions, name);
2201 	if (!perdatum)
2202 		perdatum = symtab_search(&cladatum->permissions, name);
2203 	if (!perdatum)
2204 		return 0;
2205 
2206 	return 1U << (perdatum->value - 1);
2207 }
2208 
2209 static int range_read(struct policydb *p, struct policy_file *fp)
2210 {
2211 	struct range_trans *rt = NULL;
2212 	struct mls_range *r = NULL;
2213 	int rc;
2214 	__le32 buf[2];
2215 	u32 i, nel, val;
2216 
2217 	if (p->policyvers < POLICYDB_VERSION_MLS)
2218 		return 0;
2219 
2220 	rc = next_entry(buf, fp, sizeof(u32));
2221 	if (rc)
2222 		return rc;
2223 
2224 	nel = le32_to_cpu(buf[0]);
2225 
2226 	/* we read at least 64 bytes and mls_read_range_helper() 32 bytes
2227 	 * for any valid range-transition
2228 	 */
2229 	rc = size_check(3 * sizeof(u32), nel, fp);
2230 	if (rc)
2231 		return rc;
2232 
2233 	rc = hashtab_init(&p->range_tr, nel);
2234 	if (rc)
2235 		return rc;
2236 
2237 	for (i = 0; i < nel; i++) {
2238 		rc = -ENOMEM;
2239 		rt = kzalloc_obj(*rt);
2240 		if (!rt)
2241 			goto out;
2242 
2243 		rc = next_entry(buf, fp, (sizeof(u32) * 2));
2244 		if (rc)
2245 			goto out;
2246 
2247 		rt->source_type = le32_to_cpu(buf[0]);
2248 		rt->target_type = le32_to_cpu(buf[1]);
2249 		if (p->policyvers >= POLICYDB_VERSION_RANGETRANS) {
2250 			rc = next_entry(buf, fp, sizeof(u32));
2251 			if (rc)
2252 				goto out;
2253 			rc = -EINVAL;
2254 			val = le32_to_cpu(buf[0]);
2255 			if (val > U16_MAX)
2256 				goto out;
2257 			rt->target_class = val;
2258 		} else
2259 			rt->target_class = p->process_class;
2260 
2261 		rc = -EINVAL;
2262 		if (!policydb_type_isvalid(p, rt->source_type) ||
2263 		    !policydb_type_isvalid(p, rt->target_type) ||
2264 		    !policydb_class_isvalid(p, rt->target_class))
2265 			goto out;
2266 
2267 		rc = -ENOMEM;
2268 		r = kzalloc_obj(*r);
2269 		if (!r)
2270 			goto out;
2271 
2272 		rc = mls_read_range_helper(r, fp);
2273 		if (rc)
2274 			goto out;
2275 
2276 		rc = -EINVAL;
2277 		if (!mls_range_isvalid(p, r)) {
2278 			pr_warn("SELinux:  rangetrans:  invalid range\n");
2279 			goto out;
2280 		}
2281 
2282 		rc = hashtab_insert(&p->range_tr, rt, r, rangetr_key_params);
2283 		if (rc)
2284 			goto out;
2285 
2286 		rt = NULL;
2287 		r = NULL;
2288 	}
2289 	hash_eval(&p->range_tr, "rangetr", NULL);
2290 	rc = 0;
2291 out:
2292 	kfree(rt);
2293 	kfree(r);
2294 	if (rc)
2295 		pr_err("SELinux:  invalid range\n");
2296 	return rc;
2297 }
2298 
2299 static int filename_trans_read_helper_compat(struct policydb *p, struct policy_file *fp)
2300 {
2301 	struct filename_trans_key key, *ft = NULL;
2302 	struct filename_trans_datum *last, *datum = NULL;
2303 	char *name = NULL;
2304 	u32 len, stype, otype, val;
2305 	__le32 buf[4];
2306 	int rc;
2307 
2308 	/* length of the path component string */
2309 	rc = next_entry(buf, fp, sizeof(u32));
2310 	if (rc)
2311 		return rc;
2312 	len = le32_to_cpu(buf[0]);
2313 
2314 	/* path component string */
2315 	rc = str_read(&name, GFP_KERNEL, fp, len);
2316 	if (rc)
2317 		return rc;
2318 
2319 	rc = next_entry(buf, fp, sizeof(u32) * 4);
2320 	if (rc)
2321 		goto out;
2322 
2323 	rc = -EINVAL;
2324 	stype = le32_to_cpu(buf[0]);
2325 	if (!policydb_type_isvalid(p, stype))
2326 		goto out;
2327 	key.ttype = le32_to_cpu(buf[1]);
2328 	if (!policydb_type_isvalid(p, key.ttype))
2329 		goto out;
2330 	val = le32_to_cpu(buf[2]);
2331 	if (val > U16_MAX || !policydb_class_isvalid(p, val))
2332 		goto out;
2333 	key.tclass = val;
2334 	key.name = name;
2335 
2336 	otype = le32_to_cpu(buf[3]);
2337 	if (!policydb_simpletype_isvalid(p, otype))
2338 		goto out;
2339 
2340 	last = NULL;
2341 	datum = policydb_filenametr_search(p, &key);
2342 	while (datum) {
2343 		if (unlikely(ebitmap_get_bit(&datum->stypes, stype - 1))) {
2344 			/* conflicting/duplicate rules are ignored */
2345 			datum = NULL;
2346 			rc = 0;
2347 			goto out;
2348 		}
2349 		if (likely(datum->otype == otype))
2350 			break;
2351 		last = datum;
2352 		datum = datum->next;
2353 	}
2354 	if (!datum) {
2355 		rc = -ENOMEM;
2356 		datum = kmalloc_obj(*datum);
2357 		if (!datum)
2358 			goto out;
2359 
2360 		ebitmap_init(&datum->stypes);
2361 		datum->otype = otype;
2362 		datum->next = NULL;
2363 
2364 		if (unlikely(last)) {
2365 			last->next = datum;
2366 		} else {
2367 			rc = -ENOMEM;
2368 			ft = kmemdup(&key, sizeof(key), GFP_KERNEL);
2369 			if (!ft)
2370 				goto out;
2371 
2372 			rc = hashtab_insert(&p->filename_trans, ft, datum,
2373 					    filenametr_key_params);
2374 			if (rc)
2375 				goto out;
2376 			name = NULL;
2377 
2378 			rc = ebitmap_set_bit(&p->filename_trans_ttypes,
2379 					     key.ttype, 1);
2380 			if (rc)
2381 				return rc;
2382 		}
2383 	}
2384 	kfree(name);
2385 	return ebitmap_set_bit(&datum->stypes, stype - 1, 1);
2386 
2387 out:
2388 	kfree(ft);
2389 	kfree(name);
2390 	kfree(datum);
2391 
2392 	if (rc)
2393 		pr_err("SELinux:  invalid compat filename transition\n");
2394 	return rc;
2395 }
2396 
2397 static int filename_trans_read_helper(struct policydb *p, struct policy_file *fp)
2398 {
2399 	struct filename_trans_key *ft = NULL;
2400 	struct filename_trans_datum **dst, *datum, *first = NULL;
2401 	char *name = NULL;
2402 	u32 len, ttype, ndatum, i, val;
2403 	u16 tclass;
2404 	__le32 buf[3];
2405 	int rc;
2406 
2407 	/* length of the path component string */
2408 	rc = next_entry(buf, fp, sizeof(u32));
2409 	if (rc)
2410 		return rc;
2411 	len = le32_to_cpu(buf[0]);
2412 
2413 	/* path component string */
2414 	rc = str_read(&name, GFP_KERNEL, fp, len);
2415 	if (rc)
2416 		return rc;
2417 
2418 	rc = next_entry(buf, fp, sizeof(u32) * 3);
2419 	if (rc)
2420 		goto out;
2421 
2422 	rc = -EINVAL;
2423 	ttype = le32_to_cpu(buf[0]);
2424 	if (!policydb_type_isvalid(p, ttype))
2425 		goto out;
2426 	val = le32_to_cpu(buf[1]);
2427 	rc = -EINVAL;
2428 	if (val > U16_MAX || !policydb_class_isvalid(p, val))
2429 		goto out;
2430 	tclass = val;
2431 
2432 	ndatum = le32_to_cpu(buf[2]);
2433 	if (ndatum == 0) {
2434 		pr_err("SELinux:  Filename transition key with no datum\n");
2435 		rc = -ENOENT;
2436 		goto out;
2437 	}
2438 
2439 	dst = &first;
2440 	for (i = 0; i < ndatum; i++) {
2441 		rc = -ENOMEM;
2442 		datum = kmalloc_obj(*datum);
2443 		if (!datum)
2444 			goto out;
2445 
2446 		datum->next = NULL;
2447 		*dst = datum;
2448 
2449 		/* ebitmap_read() will at least init the bitmap */
2450 		rc = ebitmap_read(&datum->stypes, fp);
2451 		if (rc)
2452 			goto out;
2453 
2454 		rc = -EINVAL;
2455 		if (ebitmap_get_highest_set_bit(&datum->stypes) >= p->p_types.nprim)
2456 			goto out;
2457 
2458 		rc = next_entry(buf, fp, sizeof(u32));
2459 		if (rc)
2460 			goto out;
2461 
2462 		datum->otype = le32_to_cpu(buf[0]);
2463 
2464 		rc = -EINVAL;
2465 		if (!policydb_simpletype_isvalid(p, datum->otype))
2466 			goto out;
2467 
2468 		dst = &datum->next;
2469 	}
2470 
2471 	rc = -ENOMEM;
2472 	ft = kmalloc_obj(*ft);
2473 	if (!ft)
2474 		goto out;
2475 
2476 	ft->ttype = ttype;
2477 	ft->tclass = tclass;
2478 	ft->name = name;
2479 
2480 	rc = hashtab_insert(&p->filename_trans, ft, first,
2481 			    filenametr_key_params);
2482 	if (rc == -EEXIST)
2483 		pr_err("SELinux:  Duplicate filename transition key\n");
2484 	if (rc)
2485 		goto out;
2486 
2487 	return ebitmap_set_bit(&p->filename_trans_ttypes, ttype, 1);
2488 
2489 out:
2490 	kfree(ft);
2491 	kfree(name);
2492 	while (first) {
2493 		datum = first;
2494 		first = first->next;
2495 
2496 		ebitmap_destroy(&datum->stypes);
2497 		kfree(datum);
2498 	}
2499 
2500 	if (rc)
2501 		pr_err("SELinux:  invalid filename transition\n");
2502 	return rc;
2503 }
2504 
2505 static int filename_trans_read(struct policydb *p, struct policy_file *fp)
2506 {
2507 	u32 nel, i;
2508 	__le32 buf[1];
2509 	int rc;
2510 
2511 	if (p->policyvers < POLICYDB_VERSION_FILENAME_TRANS)
2512 		return 0;
2513 
2514 	rc = next_entry(buf, fp, sizeof(u32));
2515 	if (rc)
2516 		return rc;
2517 	nel = le32_to_cpu(buf[0]);
2518 
2519 	if (p->policyvers < POLICYDB_VERSION_COMP_FTRANS) {
2520 		p->compat_filename_trans_count = nel;
2521 
2522 		rc = hashtab_init(&p->filename_trans, (1 << 11));
2523 		if (rc)
2524 			return rc;
2525 
2526 		for (i = 0; i < nel; i++) {
2527 			rc = filename_trans_read_helper_compat(p, fp);
2528 			if (rc)
2529 				return rc;
2530 		}
2531 	} else {
2532 		rc = hashtab_init(&p->filename_trans, nel);
2533 		if (rc)
2534 			return rc;
2535 
2536 		for (i = 0; i < nel; i++) {
2537 			rc = filename_trans_read_helper(p, fp);
2538 			if (rc)
2539 				return rc;
2540 		}
2541 	}
2542 	hash_eval(&p->filename_trans, "filenametr", NULL);
2543 	return 0;
2544 }
2545 
2546 static int genfs_read(struct policydb *p, struct policy_file *fp)
2547 {
2548 	int rc;
2549 	u32 i, j, nel, nel2, len, len2, val;
2550 	__le32 buf[1];
2551 	struct ocontext *l, *c;
2552 	struct ocontext *newc = NULL;
2553 	struct genfs *genfs_p, *genfs;
2554 	struct genfs *newgenfs = NULL;
2555 
2556 	rc = next_entry(buf, fp, sizeof(u32));
2557 	if (rc)
2558 		return rc;
2559 	nel = le32_to_cpu(buf[0]);
2560 
2561 	for (i = 0; i < nel; i++) {
2562 		rc = next_entry(buf, fp, sizeof(u32));
2563 		if (rc)
2564 			goto out;
2565 		len = le32_to_cpu(buf[0]);
2566 
2567 		rc = -ENOMEM;
2568 		newgenfs = kzalloc_obj(*newgenfs);
2569 		if (!newgenfs)
2570 			goto out;
2571 
2572 		rc = str_read(&newgenfs->fstype, GFP_KERNEL, fp, len);
2573 		if (rc)
2574 			goto out;
2575 
2576 		for (genfs_p = NULL, genfs = p->genfs; genfs;
2577 		     genfs_p = genfs, genfs = genfs->next) {
2578 			rc = -EINVAL;
2579 			if (strcmp(newgenfs->fstype, genfs->fstype) == 0) {
2580 				pr_err("SELinux:  dup genfs fstype %s\n",
2581 				       newgenfs->fstype);
2582 				goto out;
2583 			}
2584 			if (strcmp(newgenfs->fstype, genfs->fstype) < 0)
2585 				break;
2586 		}
2587 		newgenfs->next = genfs;
2588 		if (genfs_p)
2589 			genfs_p->next = newgenfs;
2590 		else
2591 			p->genfs = newgenfs;
2592 		genfs = newgenfs;
2593 		newgenfs = NULL;
2594 
2595 		rc = next_entry(buf, fp, sizeof(u32));
2596 		if (rc)
2597 			goto out;
2598 
2599 		nel2 = le32_to_cpu(buf[0]);
2600 		for (j = 0; j < nel2; j++) {
2601 			rc = next_entry(buf, fp, sizeof(u32));
2602 			if (rc)
2603 				goto out;
2604 			len = le32_to_cpu(buf[0]);
2605 
2606 			rc = -ENOMEM;
2607 			newc = kzalloc_obj(*newc);
2608 			if (!newc)
2609 				goto out;
2610 
2611 			rc = str_read(&newc->u.name, GFP_KERNEL, fp, len);
2612 			if (rc)
2613 				goto out;
2614 
2615 			rc = next_entry(buf, fp, sizeof(u32));
2616 			if (rc)
2617 				goto out;
2618 
2619 			rc = -EINVAL;
2620 			val = le32_to_cpu(buf[0]);
2621 			if (val > U16_MAX || (val != 0 && !policydb_class_isvalid(p, val)))
2622 				goto out;
2623 			newc->v.sclass = val;
2624 			rc = context_read_and_validate(&newc->context[0], p,
2625 						       fp);
2626 			if (rc)
2627 				goto out;
2628 
2629 			for (l = NULL, c = genfs->head; c; l = c, c = c->next) {
2630 				rc = -EINVAL;
2631 				if (!strcmp(newc->u.name, c->u.name) &&
2632 				    (!c->v.sclass || !newc->v.sclass ||
2633 				     newc->v.sclass == c->v.sclass)) {
2634 					pr_err("SELinux:  dup genfs entry (%s,%s)\n",
2635 					       genfs->fstype, c->u.name);
2636 					goto out;
2637 				}
2638 				len = strlen(newc->u.name);
2639 				len2 = strlen(c->u.name);
2640 				if (len > len2)
2641 					break;
2642 			}
2643 
2644 			newc->next = c;
2645 			if (l)
2646 				l->next = newc;
2647 			else
2648 				genfs->head = newc;
2649 			newc = NULL;
2650 		}
2651 	}
2652 	rc = 0;
2653 out:
2654 	if (newgenfs) {
2655 		kfree(newgenfs->fstype);
2656 		kfree(newgenfs);
2657 	}
2658 	ocontext_destroy(newc, OCON_FSUSE);
2659 
2660 	if (rc)
2661 		pr_err("SELinux:  invalid genfs\n");
2662 
2663 	return rc;
2664 }
2665 
2666 static int ocontext_read(struct policydb *p,
2667 			 const struct policydb_compat_info *info, struct policy_file *fp)
2668 {
2669 	int rc;
2670 	unsigned int i;
2671 	u32 j, nel, len, val;
2672 	__be64 prefixbuf[1];
2673 	__le32 buf[3];
2674 	struct ocontext *l, *c;
2675 	u32 nodebuf[8];
2676 
2677 	for (i = 0; i < info->ocon_num; i++) {
2678 		rc = next_entry(buf, fp, sizeof(u32));
2679 		if (rc)
2680 			goto out;
2681 		nel = le32_to_cpu(buf[0]);
2682 
2683 		l = NULL;
2684 		for (j = 0; j < nel; j++) {
2685 			rc = -ENOMEM;
2686 			c = kzalloc_obj(*c);
2687 			if (!c)
2688 				goto out;
2689 			if (l)
2690 				l->next = c;
2691 			else
2692 				p->ocontexts[i] = c;
2693 			l = c;
2694 
2695 			switch (i) {
2696 			case OCON_ISID:
2697 				rc = next_entry(buf, fp, sizeof(u32));
2698 				if (rc)
2699 					goto out;
2700 
2701 				c->sid[0] = le32_to_cpu(buf[0]);
2702 				rc = context_read_and_validate(&c->context[0],
2703 							       p, fp);
2704 				if (rc)
2705 					goto out;
2706 				break;
2707 			case OCON_FS:
2708 			case OCON_NETIF:
2709 				rc = next_entry(buf, fp, sizeof(u32));
2710 				if (rc)
2711 					goto out;
2712 				len = le32_to_cpu(buf[0]);
2713 
2714 				rc = str_read(&c->u.name, GFP_KERNEL, fp, len);
2715 				if (rc)
2716 					goto out;
2717 
2718 				if (i == OCON_FS)
2719 					pr_warn("SELinux:  void and deprecated fs ocon %s\n",
2720 						c->u.name);
2721 
2722 				rc = context_read_and_validate(&c->context[0],
2723 							       p, fp);
2724 				if (rc)
2725 					goto out;
2726 				rc = context_read_and_validate(&c->context[1],
2727 							       p, fp);
2728 				if (rc)
2729 					goto out;
2730 				break;
2731 			case OCON_PORT:
2732 				rc = next_entry(buf, fp, sizeof(u32) * 3);
2733 				if (rc)
2734 					goto out;
2735 
2736 				rc = -EINVAL;
2737 				val = le32_to_cpu(buf[0]);
2738 				if (val > U8_MAX)
2739 					goto out;
2740 				c->u.port.protocol = val;
2741 				val = le32_to_cpu(buf[1]);
2742 				if (val > U16_MAX)
2743 					goto out;
2744 				c->u.port.low_port = val;
2745 				val = le32_to_cpu(buf[2]);
2746 				if (val > U16_MAX)
2747 					goto out;
2748 				c->u.port.high_port = val;
2749 				if (c->u.port.low_port == 0 ||
2750 				    c->u.port.low_port > c->u.port.high_port)
2751 					goto out;
2752 
2753 				rc = context_read_and_validate(&c->context[0], p, fp);
2754 				if (rc)
2755 					goto out;
2756 				break;
2757 			case OCON_NODE:
2758 				rc = next_entry(nodebuf, fp, sizeof(u32) * 2);
2759 				if (rc)
2760 					goto out;
2761 				c->u.node.addr = nodebuf[0]; /* network order */
2762 				c->u.node.mask = nodebuf[1]; /* network order */
2763 				rc = context_read_and_validate(&c->context[0],
2764 							       p, fp);
2765 				if (rc)
2766 					goto out;
2767 				break;
2768 			case OCON_FSUSE:
2769 				rc = next_entry(buf, fp, sizeof(u32) * 2);
2770 				if (rc)
2771 					goto out;
2772 
2773 				rc = -EINVAL;
2774 				c->v.behavior = le32_to_cpu(buf[0]);
2775 				/* Determined at runtime, not in policy DB. */
2776 				if (c->v.behavior == SECURITY_FS_USE_MNTPOINT)
2777 					goto out;
2778 				if (c->v.behavior > SECURITY_FS_USE_MAX)
2779 					goto out;
2780 
2781 				len = le32_to_cpu(buf[1]);
2782 				rc = str_read(&c->u.name, GFP_KERNEL, fp, len);
2783 				if (rc)
2784 					goto out;
2785 
2786 				rc = context_read_and_validate(&c->context[0],
2787 							       p, fp);
2788 				if (rc)
2789 					goto out;
2790 				break;
2791 			case OCON_NODE6: {
2792 				int k;
2793 
2794 				rc = next_entry(nodebuf, fp, sizeof(u32) * 8);
2795 				if (rc)
2796 					goto out;
2797 				for (k = 0; k < 4; k++)
2798 					c->u.node6.addr[k] = nodebuf[k];
2799 				for (k = 0; k < 4; k++)
2800 					c->u.node6.mask[k] = nodebuf[k + 4];
2801 				rc = context_read_and_validate(&c->context[0],
2802 							       p, fp);
2803 				if (rc)
2804 					goto out;
2805 				break;
2806 			}
2807 			case OCON_IBPKEY: {
2808 				u32 pkey_lo, pkey_hi;
2809 
2810 				rc = next_entry(prefixbuf, fp, sizeof(u64));
2811 				if (rc)
2812 					goto out;
2813 
2814 				/* we need to have subnet_prefix in CPU order */
2815 				c->u.ibpkey.subnet_prefix =
2816 					be64_to_cpu(prefixbuf[0]);
2817 
2818 				rc = next_entry(buf, fp, sizeof(u32) * 2);
2819 				if (rc)
2820 					goto out;
2821 
2822 				pkey_lo = le32_to_cpu(buf[0]);
2823 				pkey_hi = le32_to_cpu(buf[1]);
2824 
2825 				if (pkey_lo > U16_MAX || pkey_hi > U16_MAX) {
2826 					rc = -EINVAL;
2827 					goto out;
2828 				}
2829 
2830 				c->u.ibpkey.low_pkey = pkey_lo;
2831 				c->u.ibpkey.high_pkey = pkey_hi;
2832 
2833 				rc = context_read_and_validate(&c->context[0],
2834 							       p, fp);
2835 				if (rc)
2836 					goto out;
2837 				break;
2838 			}
2839 			case OCON_IBENDPORT: {
2840 				u32 port;
2841 
2842 				rc = next_entry(buf, fp, sizeof(u32) * 2);
2843 				if (rc)
2844 					goto out;
2845 				len = le32_to_cpu(buf[0]);
2846 
2847 				rc = str_read(&c->u.ibendport.dev_name,
2848 					      GFP_KERNEL, fp, len);
2849 				if (rc)
2850 					goto out;
2851 
2852 				port = le32_to_cpu(buf[1]);
2853 				if (port > U8_MAX || port == 0) {
2854 					rc = -EINVAL;
2855 					goto out;
2856 				}
2857 
2858 				c->u.ibendport.port = port;
2859 
2860 				rc = context_read_and_validate(&c->context[0],
2861 							       p, fp);
2862 				if (rc)
2863 					goto out;
2864 				break;
2865 			} /* end case */
2866 			} /* end switch */
2867 		}
2868 	}
2869 	rc = 0;
2870 out:
2871 	if (rc)
2872 		pr_err("SELinux:  invalid ocon\n");
2873 	return rc;
2874 }
2875 
2876 /*
2877  * Read the configuration data from a policy database binary
2878  * representation file into a policy database structure.
2879  */
2880 int policydb_read(struct policydb *p, struct policy_file *fp)
2881 {
2882 	struct role_allow *ra, *lra;
2883 	struct role_trans_key *rtk = NULL;
2884 	struct role_trans_datum *rtd = NULL;
2885 	int rc;
2886 	__le32 buf[4];
2887 	u32 i, j, len, nprim, nel, perm, val;
2888 
2889 	char *policydb_str;
2890 	const struct policydb_compat_info *info;
2891 
2892 	policydb_init(p);
2893 
2894 	/* Read the magic number and string length. */
2895 	rc = next_entry(buf, fp, sizeof(u32) * 2);
2896 	if (rc)
2897 		goto bad;
2898 
2899 	rc = -EINVAL;
2900 	if (le32_to_cpu(buf[0]) != POLICYDB_MAGIC) {
2901 		pr_err("SELinux:  policydb magic number 0x%x does "
2902 		       "not match expected magic number 0x%x\n",
2903 		       le32_to_cpu(buf[0]), POLICYDB_MAGIC);
2904 		goto bad;
2905 	}
2906 
2907 	rc = -EINVAL;
2908 	len = le32_to_cpu(buf[1]);
2909 	if (len != strlen(POLICYDB_STRING)) {
2910 		pr_err("SELinux:  policydb string length %d does not "
2911 		       "match expected length %zu\n",
2912 		       len, strlen(POLICYDB_STRING));
2913 		goto bad;
2914 	}
2915 
2916 	rc = str_read(&policydb_str, GFP_KERNEL, fp, len);
2917 	if (rc) {
2918 		if (rc == -ENOMEM) {
2919 			pr_err("SELinux:  unable to allocate memory for policydb string of length %d\n",
2920 			       len);
2921 		} else {
2922 			pr_err("SELinux:  truncated policydb string identifier\n");
2923 		}
2924 		goto bad;
2925 	}
2926 
2927 	rc = -EINVAL;
2928 	if (strcmp(policydb_str, POLICYDB_STRING)) {
2929 		pr_err("SELinux:  policydb string %s does not match "
2930 		       "my string %s\n",
2931 		       policydb_str, POLICYDB_STRING);
2932 		kfree(policydb_str);
2933 		goto bad;
2934 	}
2935 	/* Done with policydb_str. */
2936 	kfree(policydb_str);
2937 	policydb_str = NULL;
2938 
2939 	/* Read the version and table sizes. */
2940 	rc = next_entry(buf, fp, sizeof(u32) * 4);
2941 	if (rc)
2942 		goto bad;
2943 
2944 	rc = -EINVAL;
2945 	p->policyvers = le32_to_cpu(buf[0]);
2946 	if (p->policyvers < POLICYDB_VERSION_MIN ||
2947 	    p->policyvers > POLICYDB_VERSION_MAX) {
2948 		pr_err("SELinux:  policydb version %d does not match "
2949 		       "my version range %d-%d\n",
2950 		       le32_to_cpu(buf[0]), POLICYDB_VERSION_MIN,
2951 		       POLICYDB_VERSION_MAX);
2952 		goto bad;
2953 	}
2954 
2955 	val = le32_to_cpu(buf[1]);
2956 	if (val & POLICYDB_CONFIG_MLS) {
2957 		p->mls_enabled = 1;
2958 
2959 		rc = -EINVAL;
2960 		if (p->policyvers < POLICYDB_VERSION_MLS) {
2961 			pr_err("SELinux: security policydb version %d "
2962 			       "(MLS) not backwards compatible\n",
2963 			       p->policyvers);
2964 			goto bad;
2965 		}
2966 	}
2967 	rc = -EINVAL;
2968 	if ((val & (REJECT_UNKNOWN | ALLOW_UNKNOWN)) == (REJECT_UNKNOWN | ALLOW_UNKNOWN)) {
2969 		pr_err("SELinux:  policydb configuration both rejects and allows unknown classes and permissions\n");
2970 		goto bad;
2971 	}
2972 	p->reject_unknown = !!(val & REJECT_UNKNOWN);
2973 	p->allow_unknown = !!(val & ALLOW_UNKNOWN);
2974 
2975 	if (p->policyvers >= POLICYDB_VERSION_POLCAP) {
2976 		rc = ebitmap_read(&p->policycaps, fp);
2977 		if (rc)
2978 			goto bad;
2979 	}
2980 
2981 	if (p->policyvers >= POLICYDB_VERSION_PERMISSIVE) {
2982 		rc = ebitmap_read(&p->permissive_map, fp);
2983 		if (rc)
2984 			goto bad;
2985 	}
2986 
2987 	if (p->policyvers >= POLICYDB_VERSION_NEVERAUDIT) {
2988 		rc = ebitmap_read(&p->neveraudit_map, fp);
2989 		if (rc)
2990 			goto bad;
2991 	}
2992 
2993 	rc = -EINVAL;
2994 	info = policydb_lookup_compat(p->policyvers);
2995 	if (!info) {
2996 		pr_err("SELinux:  unable to find policy compat info "
2997 		       "for version %d\n",
2998 		       p->policyvers);
2999 		goto bad;
3000 	}
3001 
3002 	rc = -EINVAL;
3003 	if (le32_to_cpu(buf[2]) != info->sym_num ||
3004 	    le32_to_cpu(buf[3]) != info->ocon_num) {
3005 		pr_err("SELinux:  policydb table sizes (%d,%d) do "
3006 		       "not match mine (%d,%d)\n",
3007 		       le32_to_cpu(buf[2]), le32_to_cpu(buf[3]), info->sym_num,
3008 		       info->ocon_num);
3009 		goto bad;
3010 	}
3011 
3012 	for (i = 0; i < info->sym_num; i++) {
3013 		rc = next_entry(buf, fp, sizeof(u32) * 2);
3014 		if (rc)
3015 			goto bad;
3016 		nprim = le32_to_cpu(buf[0]);
3017 		nel = le32_to_cpu(buf[1]);
3018 
3019 		/* every read_f() implementation reads at least 128 bytes
3020 		 * for any valid entry
3021 		 */
3022 		rc = size_check(4 * sizeof(u32), nel, fp);
3023 		if (rc)
3024 			goto out;
3025 
3026 		rc = symtab_init(&p->symtab[i], nel);
3027 		if (rc)
3028 			goto out;
3029 
3030 		if (i == SYM_ROLES) {
3031 			rc = roles_init(p);
3032 			if (rc)
3033 				goto out;
3034 		}
3035 
3036 		for (j = 0; j < nel; j++) {
3037 			rc = read_f[i](p, &p->symtab[i], fp);
3038 			if (rc)
3039 				goto bad;
3040 		}
3041 
3042 		p->symtab[i].nprim = nprim;
3043 	}
3044 
3045 	rc = policydb_index(p);
3046 	if (rc)
3047 		goto bad;
3048 
3049 	rc = -EINVAL;
3050 	p->process_class = string_to_security_class(p, "process");
3051 	if (!p->process_class) {
3052 		pr_err("SELinux: process class is required, not defined in policy\n");
3053 		goto bad;
3054 	}
3055 
3056 	rc = avtab_read(&p->te_avtab, fp, p);
3057 	if (rc)
3058 		goto bad;
3059 
3060 	avtab_hash_eval(&p->te_avtab, "rules");
3061 
3062 	if (p->policyvers >= POLICYDB_VERSION_BOOL) {
3063 		rc = cond_read_list(p, fp);
3064 		if (rc)
3065 			goto bad;
3066 	}
3067 
3068 	rc = next_entry(buf, fp, sizeof(u32));
3069 	if (rc)
3070 		goto bad;
3071 	nel = le32_to_cpu(buf[0]);
3072 
3073 	/* we read at least 96 bytes for any valid role-transition */
3074 	rc = size_check(3 * sizeof(u32), nel, fp);
3075 	if (rc)
3076 		goto bad;
3077 
3078 	rc = hashtab_init(&p->role_tr, nel);
3079 	if (rc)
3080 		goto bad;
3081 	for (i = 0; i < nel; i++) {
3082 		rc = -ENOMEM;
3083 		rtk = kmalloc_obj(*rtk);
3084 		if (!rtk)
3085 			goto bad;
3086 
3087 		rc = -ENOMEM;
3088 		rtd = kmalloc_obj(*rtd);
3089 		if (!rtd)
3090 			goto bad;
3091 
3092 		rc = next_entry(buf, fp, sizeof(u32) * 3);
3093 		if (rc)
3094 			goto bad;
3095 
3096 		rtk->role = le32_to_cpu(buf[0]);
3097 		rtk->type = le32_to_cpu(buf[1]);
3098 		rtd->new_role = le32_to_cpu(buf[2]);
3099 		if (p->policyvers >= POLICYDB_VERSION_ROLETRANS) {
3100 			rc = next_entry(buf, fp, sizeof(u32));
3101 			if (rc)
3102 				goto bad;
3103 			rc = -EINVAL;
3104 			val = le32_to_cpu(buf[0]);
3105 			if (val > U16_MAX)
3106 				goto bad;
3107 			rtk->tclass = val;
3108 		} else
3109 			rtk->tclass = p->process_class;
3110 
3111 		rc = -EINVAL;
3112 		if (!policydb_role_isvalid(p, rtk->role) ||
3113 		    !policydb_type_isvalid(p, rtk->type) ||
3114 		    !policydb_class_isvalid(p, rtk->tclass) ||
3115 		    !policydb_role_isvalid(p, rtd->new_role))
3116 			goto bad;
3117 
3118 		rc = hashtab_insert(&p->role_tr, rtk, rtd, roletr_key_params);
3119 		if (rc)
3120 			goto bad;
3121 
3122 		rtk = NULL;
3123 		rtd = NULL;
3124 	}
3125 
3126 	hash_eval(&p->role_tr, "roletr", NULL);
3127 
3128 	rc = next_entry(buf, fp, sizeof(u32));
3129 	if (rc)
3130 		goto bad;
3131 	nel = le32_to_cpu(buf[0]);
3132 	lra = NULL;
3133 	for (i = 0; i < nel; i++) {
3134 		rc = -ENOMEM;
3135 		ra = kzalloc_obj(*ra);
3136 		if (!ra)
3137 			goto bad;
3138 		if (lra)
3139 			lra->next = ra;
3140 		else
3141 			p->role_allow = ra;
3142 		rc = next_entry(buf, fp, sizeof(u32) * 2);
3143 		if (rc)
3144 			goto bad;
3145 
3146 		rc = -EINVAL;
3147 		ra->role = le32_to_cpu(buf[0]);
3148 		ra->new_role = le32_to_cpu(buf[1]);
3149 		if (!policydb_role_isvalid(p, ra->role) ||
3150 		    !policydb_role_isvalid(p, ra->new_role))
3151 			goto bad;
3152 		lra = ra;
3153 	}
3154 
3155 	rc = filename_trans_read(p, fp);
3156 	if (rc)
3157 		goto bad;
3158 
3159 	rc = -EINVAL;
3160 	perm = string_to_av_perm(p, p->process_class, "transition");
3161 	if (!perm) {
3162 		pr_err("SELinux: process transition permission is required, not defined in policy\n");
3163 		goto bad;
3164 	}
3165 	p->process_trans_perms = perm;
3166 	perm = string_to_av_perm(p, p->process_class, "dyntransition");
3167 	if (!perm) {
3168 		pr_err("SELinux: process dyntransition permission is required, not defined in policy\n");
3169 		goto bad;
3170 	}
3171 	p->process_trans_perms |= perm;
3172 
3173 	rc = ocontext_read(p, info, fp);
3174 	if (rc)
3175 		goto bad;
3176 
3177 	rc = genfs_read(p, fp);
3178 	if (rc)
3179 		goto bad;
3180 
3181 	rc = range_read(p, fp);
3182 	if (rc)
3183 		goto bad;
3184 
3185 	rc = -ENOMEM;
3186 	p->type_attr_map_array = kvzalloc_objs(*p->type_attr_map_array,
3187 					       p->p_types.nprim);
3188 	if (!p->type_attr_map_array)
3189 		goto bad;
3190 
3191 	/* just in case ebitmap_init() becomes more than just a memset(0): */
3192 	for (i = 0; i < p->p_types.nprim; i++)
3193 		ebitmap_init(&p->type_attr_map_array[i]);
3194 
3195 	for (i = 0; i < p->p_types.nprim; i++) {
3196 		struct ebitmap *e = &p->type_attr_map_array[i];
3197 
3198 		if (p->policyvers >= POLICYDB_VERSION_AVTAB) {
3199 			rc = ebitmap_read(e, fp);
3200 			if (rc)
3201 				goto bad;
3202 		}
3203 
3204 		rc = -EINVAL;
3205 		if (ebitmap_get_highest_set_bit(e) >= p->p_types.nprim)
3206 			goto bad;
3207 
3208 		/* add the type itself as the degenerate case */
3209 		rc = ebitmap_set_bit(e, i, 1);
3210 		if (rc)
3211 			goto bad;
3212 	}
3213 
3214 	rc = policydb_bounds_sanity_check(p);
3215 	if (rc)
3216 		goto bad;
3217 
3218 	rc = 0;
3219 out:
3220 	return rc;
3221 bad:
3222 	kfree(rtk);
3223 	kfree(rtd);
3224 	policydb_destroy(p);
3225 	goto out;
3226 }
3227 
3228 /*
3229  * Write a MLS level structure to a policydb binary
3230  * representation file.
3231  */
3232 static int mls_write_level(struct mls_level *l, struct policy_file *fp)
3233 {
3234 	__le32 buf[1];
3235 	int rc;
3236 
3237 	buf[0] = cpu_to_le32(l->sens);
3238 	rc = put_entry(buf, sizeof(u32), 1, fp);
3239 	if (rc)
3240 		return rc;
3241 
3242 	rc = ebitmap_write(&l->cat, fp);
3243 	if (rc)
3244 		return rc;
3245 
3246 	return 0;
3247 }
3248 
3249 /*
3250  * Write a MLS range structure to a policydb binary
3251  * representation file.
3252  */
3253 static int mls_write_range_helper(struct mls_range *r, struct policy_file *fp)
3254 {
3255 	__le32 buf[3];
3256 	size_t items;
3257 	int rc, eq;
3258 
3259 	eq = mls_level_eq(&r->level[1], &r->level[0]);
3260 
3261 	if (eq)
3262 		items = 2;
3263 	else
3264 		items = 3;
3265 	buf[0] = cpu_to_le32(items - 1);
3266 	buf[1] = cpu_to_le32(r->level[0].sens);
3267 	if (!eq)
3268 		buf[2] = cpu_to_le32(r->level[1].sens);
3269 
3270 	BUG_ON(items > ARRAY_SIZE(buf));
3271 
3272 	rc = put_entry(buf, sizeof(u32), items, fp);
3273 	if (rc)
3274 		return rc;
3275 
3276 	rc = ebitmap_write(&r->level[0].cat, fp);
3277 	if (rc)
3278 		return rc;
3279 	if (!eq) {
3280 		rc = ebitmap_write(&r->level[1].cat, fp);
3281 		if (rc)
3282 			return rc;
3283 	}
3284 
3285 	return 0;
3286 }
3287 
3288 static int sens_write(void *vkey, void *datum, void *ptr)
3289 {
3290 	char *key = vkey;
3291 	struct level_datum *levdatum = datum;
3292 	struct policy_data *pd = ptr;
3293 	struct policy_file *fp = pd->fp;
3294 	__le32 buf[2];
3295 	size_t len;
3296 	int rc;
3297 
3298 	len = strlen(key);
3299 	buf[0] = cpu_to_le32(len);
3300 	buf[1] = cpu_to_le32(levdatum->isalias);
3301 	rc = put_entry(buf, sizeof(u32), 2, fp);
3302 	if (rc)
3303 		return rc;
3304 
3305 	rc = put_entry(key, 1, len, fp);
3306 	if (rc)
3307 		return rc;
3308 
3309 	rc = mls_write_level(&levdatum->level, fp);
3310 	if (rc)
3311 		return rc;
3312 
3313 	return 0;
3314 }
3315 
3316 static int cat_write(void *vkey, void *datum, void *ptr)
3317 {
3318 	char *key = vkey;
3319 	struct cat_datum *catdatum = datum;
3320 	struct policy_data *pd = ptr;
3321 	struct policy_file *fp = pd->fp;
3322 	__le32 buf[3];
3323 	size_t len;
3324 	int rc;
3325 
3326 	len = strlen(key);
3327 	buf[0] = cpu_to_le32(len);
3328 	buf[1] = cpu_to_le32(catdatum->value);
3329 	buf[2] = cpu_to_le32(catdatum->isalias);
3330 	rc = put_entry(buf, sizeof(u32), 3, fp);
3331 	if (rc)
3332 		return rc;
3333 
3334 	rc = put_entry(key, 1, len, fp);
3335 	if (rc)
3336 		return rc;
3337 
3338 	return 0;
3339 }
3340 
3341 static int role_trans_write_one(void *key, void *datum, void *ptr)
3342 {
3343 	struct role_trans_key *rtk = key;
3344 	struct role_trans_datum *rtd = datum;
3345 	struct policy_data *pd = ptr;
3346 	struct policy_file *fp = pd->fp;
3347 	struct policydb *p = pd->p;
3348 	__le32 buf[3];
3349 	int rc;
3350 
3351 	buf[0] = cpu_to_le32(rtk->role);
3352 	buf[1] = cpu_to_le32(rtk->type);
3353 	buf[2] = cpu_to_le32(rtd->new_role);
3354 	rc = put_entry(buf, sizeof(u32), 3, fp);
3355 	if (rc)
3356 		return rc;
3357 	if (p->policyvers >= POLICYDB_VERSION_ROLETRANS) {
3358 		buf[0] = cpu_to_le32(rtk->tclass);
3359 		rc = put_entry(buf, sizeof(u32), 1, fp);
3360 		if (rc)
3361 			return rc;
3362 	}
3363 	return 0;
3364 }
3365 
3366 static int role_trans_write(struct policydb *p, struct policy_file *fp)
3367 {
3368 	struct policy_data pd = { .p = p, .fp = fp };
3369 	__le32 buf[1];
3370 	int rc;
3371 
3372 	buf[0] = cpu_to_le32(p->role_tr.nel);
3373 	rc = put_entry(buf, sizeof(u32), 1, fp);
3374 	if (rc)
3375 		return rc;
3376 
3377 	return hashtab_map(&p->role_tr, role_trans_write_one, &pd);
3378 }
3379 
3380 static int role_allow_write(struct role_allow *r, struct policy_file *fp)
3381 {
3382 	struct role_allow *ra;
3383 	__le32 buf[2];
3384 	size_t nel;
3385 	int rc;
3386 
3387 	nel = 0;
3388 	for (ra = r; ra; ra = ra->next)
3389 		nel++;
3390 	buf[0] = cpu_to_le32(nel);
3391 	rc = put_entry(buf, sizeof(u32), 1, fp);
3392 	if (rc)
3393 		return rc;
3394 	for (ra = r; ra; ra = ra->next) {
3395 		buf[0] = cpu_to_le32(ra->role);
3396 		buf[1] = cpu_to_le32(ra->new_role);
3397 		rc = put_entry(buf, sizeof(u32), 2, fp);
3398 		if (rc)
3399 			return rc;
3400 	}
3401 	return 0;
3402 }
3403 
3404 /*
3405  * Write a security context structure
3406  * to a policydb binary representation file.
3407  */
3408 static int context_write(struct policydb *p, struct context *c, struct policy_file *fp)
3409 {
3410 	int rc;
3411 	__le32 buf[3];
3412 
3413 	buf[0] = cpu_to_le32(c->user);
3414 	buf[1] = cpu_to_le32(c->role);
3415 	buf[2] = cpu_to_le32(c->type);
3416 
3417 	rc = put_entry(buf, sizeof(u32), 3, fp);
3418 	if (rc)
3419 		return rc;
3420 
3421 	rc = mls_write_range_helper(&c->range, fp);
3422 	if (rc)
3423 		return rc;
3424 
3425 	return 0;
3426 }
3427 
3428 /*
3429  * The following *_write functions are used to
3430  * write the symbol data to a policy database
3431  * binary representation file.
3432  */
3433 
3434 static int perm_write(void *vkey, void *datum, void *fp)
3435 {
3436 	char *key = vkey;
3437 	struct perm_datum *perdatum = datum;
3438 	__le32 buf[2];
3439 	size_t len;
3440 	int rc;
3441 
3442 	len = strlen(key);
3443 	buf[0] = cpu_to_le32(len);
3444 	buf[1] = cpu_to_le32(perdatum->value);
3445 	rc = put_entry(buf, sizeof(u32), 2, fp);
3446 	if (rc)
3447 		return rc;
3448 
3449 	rc = put_entry(key, 1, len, fp);
3450 	if (rc)
3451 		return rc;
3452 
3453 	return 0;
3454 }
3455 
3456 static int common_write(void *vkey, void *datum, void *ptr)
3457 {
3458 	char *key = vkey;
3459 	struct common_datum *comdatum = datum;
3460 	struct policy_data *pd = ptr;
3461 	struct policy_file *fp = pd->fp;
3462 	__le32 buf[4];
3463 	size_t len;
3464 	int rc;
3465 
3466 	len = strlen(key);
3467 	buf[0] = cpu_to_le32(len);
3468 	buf[1] = cpu_to_le32(comdatum->value);
3469 	buf[2] = cpu_to_le32(comdatum->permissions.nprim);
3470 	buf[3] = cpu_to_le32(comdatum->permissions.table.nel);
3471 	rc = put_entry(buf, sizeof(u32), 4, fp);
3472 	if (rc)
3473 		return rc;
3474 
3475 	rc = put_entry(key, 1, len, fp);
3476 	if (rc)
3477 		return rc;
3478 
3479 	rc = hashtab_map(&comdatum->permissions.table, perm_write, fp);
3480 	if (rc)
3481 		return rc;
3482 
3483 	return 0;
3484 }
3485 
3486 static int type_set_write(struct type_set *t, struct policy_file *fp)
3487 {
3488 	int rc;
3489 	__le32 buf[1];
3490 
3491 	if (ebitmap_write(&t->types, fp))
3492 		return -EINVAL;
3493 	if (ebitmap_write(&t->negset, fp))
3494 		return -EINVAL;
3495 
3496 	buf[0] = cpu_to_le32(t->flags);
3497 	rc = put_entry(buf, sizeof(u32), 1, fp);
3498 	if (rc)
3499 		return -EINVAL;
3500 
3501 	return 0;
3502 }
3503 
3504 static int write_cons_helper(struct policydb *p, struct constraint_node *node,
3505 			     struct policy_file *fp)
3506 {
3507 	struct constraint_node *c;
3508 	struct constraint_expr *e;
3509 	__le32 buf[3];
3510 	u32 nel;
3511 	int rc;
3512 
3513 	for (c = node; c; c = c->next) {
3514 		nel = 0;
3515 		for (e = c->expr; e; e = e->next)
3516 			nel++;
3517 		buf[0] = cpu_to_le32(c->permissions);
3518 		buf[1] = cpu_to_le32(nel);
3519 		rc = put_entry(buf, sizeof(u32), 2, fp);
3520 		if (rc)
3521 			return rc;
3522 		for (e = c->expr; e; e = e->next) {
3523 			buf[0] = cpu_to_le32(e->expr_type);
3524 			buf[1] = cpu_to_le32(e->attr);
3525 			buf[2] = cpu_to_le32(e->op);
3526 			rc = put_entry(buf, sizeof(u32), 3, fp);
3527 			if (rc)
3528 				return rc;
3529 
3530 			switch (e->expr_type) {
3531 			case CEXPR_NAMES:
3532 				rc = ebitmap_write(&e->names, fp);
3533 				if (rc)
3534 					return rc;
3535 				if (p->policyvers >=
3536 				    POLICYDB_VERSION_CONSTRAINT_NAMES) {
3537 					rc = type_set_write(e->type_names, fp);
3538 					if (rc)
3539 						return rc;
3540 				}
3541 				break;
3542 			default:
3543 				break;
3544 			}
3545 		}
3546 	}
3547 
3548 	return 0;
3549 }
3550 
3551 static int class_write(void *vkey, void *datum, void *ptr)
3552 {
3553 	char *key = vkey;
3554 	struct class_datum *cladatum = datum;
3555 	struct policy_data *pd = ptr;
3556 	struct policy_file *fp = pd->fp;
3557 	struct policydb *p = pd->p;
3558 	struct constraint_node *c;
3559 	__le32 buf[6];
3560 	u32 ncons;
3561 	size_t len, len2;
3562 	int rc;
3563 
3564 	len = strlen(key);
3565 	if (cladatum->comkey)
3566 		len2 = strlen(cladatum->comkey);
3567 	else
3568 		len2 = 0;
3569 
3570 	ncons = 0;
3571 	for (c = cladatum->constraints; c; c = c->next)
3572 		ncons++;
3573 
3574 	buf[0] = cpu_to_le32(len);
3575 	buf[1] = cpu_to_le32(len2);
3576 	buf[2] = cpu_to_le32(cladatum->value);
3577 	buf[3] = cpu_to_le32(cladatum->permissions.nprim);
3578 	buf[4] = cpu_to_le32(cladatum->permissions.table.nel);
3579 	buf[5] = cpu_to_le32(ncons);
3580 	rc = put_entry(buf, sizeof(u32), 6, fp);
3581 	if (rc)
3582 		return rc;
3583 
3584 	rc = put_entry(key, 1, len, fp);
3585 	if (rc)
3586 		return rc;
3587 
3588 	if (cladatum->comkey) {
3589 		rc = put_entry(cladatum->comkey, 1, len2, fp);
3590 		if (rc)
3591 			return rc;
3592 	}
3593 
3594 	rc = hashtab_map(&cladatum->permissions.table, perm_write, fp);
3595 	if (rc)
3596 		return rc;
3597 
3598 	rc = write_cons_helper(p, cladatum->constraints, fp);
3599 	if (rc)
3600 		return rc;
3601 
3602 	/* write out the validatetrans rule */
3603 	ncons = 0;
3604 	for (c = cladatum->validatetrans; c; c = c->next)
3605 		ncons++;
3606 
3607 	buf[0] = cpu_to_le32(ncons);
3608 	rc = put_entry(buf, sizeof(u32), 1, fp);
3609 	if (rc)
3610 		return rc;
3611 
3612 	rc = write_cons_helper(p, cladatum->validatetrans, fp);
3613 	if (rc)
3614 		return rc;
3615 
3616 	if (p->policyvers >= POLICYDB_VERSION_NEW_OBJECT_DEFAULTS) {
3617 		buf[0] = cpu_to_le32(cladatum->default_user);
3618 		buf[1] = cpu_to_le32(cladatum->default_role);
3619 		buf[2] = cpu_to_le32(cladatum->default_range);
3620 
3621 		rc = put_entry(buf, sizeof(uint32_t), 3, fp);
3622 		if (rc)
3623 			return rc;
3624 	}
3625 
3626 	if (p->policyvers >= POLICYDB_VERSION_DEFAULT_TYPE) {
3627 		buf[0] = cpu_to_le32(cladatum->default_type);
3628 		rc = put_entry(buf, sizeof(uint32_t), 1, fp);
3629 		if (rc)
3630 			return rc;
3631 	}
3632 
3633 	return 0;
3634 }
3635 
3636 static int role_write(void *vkey, void *datum, void *ptr)
3637 {
3638 	char *key = vkey;
3639 	struct role_datum *role = datum;
3640 	struct policy_data *pd = ptr;
3641 	struct policy_file *fp = pd->fp;
3642 	struct policydb *p = pd->p;
3643 	__le32 buf[3];
3644 	size_t items, len;
3645 	int rc;
3646 
3647 	len = strlen(key);
3648 	items = 0;
3649 	buf[items++] = cpu_to_le32(len);
3650 	buf[items++] = cpu_to_le32(role->value);
3651 	if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
3652 		buf[items++] = cpu_to_le32(role->bounds);
3653 
3654 	BUG_ON(items > ARRAY_SIZE(buf));
3655 
3656 	rc = put_entry(buf, sizeof(u32), items, fp);
3657 	if (rc)
3658 		return rc;
3659 
3660 	rc = put_entry(key, 1, len, fp);
3661 	if (rc)
3662 		return rc;
3663 
3664 	rc = ebitmap_write(&role->dominates, fp);
3665 	if (rc)
3666 		return rc;
3667 
3668 	rc = ebitmap_write(&role->types, fp);
3669 	if (rc)
3670 		return rc;
3671 
3672 	return 0;
3673 }
3674 
3675 static int type_write(void *vkey, void *datum, void *ptr)
3676 {
3677 	char *key = vkey;
3678 	struct type_datum *typdatum = datum;
3679 	struct policy_data *pd = ptr;
3680 	struct policydb *p = pd->p;
3681 	struct policy_file *fp = pd->fp;
3682 	__le32 buf[4];
3683 	int rc;
3684 	size_t items, len;
3685 
3686 	len = strlen(key);
3687 	items = 0;
3688 	buf[items++] = cpu_to_le32(len);
3689 	buf[items++] = cpu_to_le32(typdatum->value);
3690 	if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) {
3691 		u32 properties = 0;
3692 
3693 		if (typdatum->primary)
3694 			properties |= TYPEDATUM_PROPERTY_PRIMARY;
3695 
3696 		if (typdatum->attribute)
3697 			properties |= TYPEDATUM_PROPERTY_ATTRIBUTE;
3698 
3699 		buf[items++] = cpu_to_le32(properties);
3700 		buf[items++] = cpu_to_le32(typdatum->bounds);
3701 	} else {
3702 		buf[items++] = cpu_to_le32(typdatum->primary);
3703 	}
3704 	BUG_ON(items > ARRAY_SIZE(buf));
3705 	rc = put_entry(buf, sizeof(u32), items, fp);
3706 	if (rc)
3707 		return rc;
3708 
3709 	rc = put_entry(key, 1, len, fp);
3710 	if (rc)
3711 		return rc;
3712 
3713 	return 0;
3714 }
3715 
3716 static int user_write(void *vkey, void *datum, void *ptr)
3717 {
3718 	char *key = vkey;
3719 	struct user_datum *usrdatum = datum;
3720 	struct policy_data *pd = ptr;
3721 	struct policydb *p = pd->p;
3722 	struct policy_file *fp = pd->fp;
3723 	__le32 buf[3];
3724 	size_t items, len;
3725 	int rc;
3726 
3727 	len = strlen(key);
3728 	items = 0;
3729 	buf[items++] = cpu_to_le32(len);
3730 	buf[items++] = cpu_to_le32(usrdatum->value);
3731 	if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
3732 		buf[items++] = cpu_to_le32(usrdatum->bounds);
3733 	BUG_ON(items > ARRAY_SIZE(buf));
3734 	rc = put_entry(buf, sizeof(u32), items, fp);
3735 	if (rc)
3736 		return rc;
3737 
3738 	rc = put_entry(key, 1, len, fp);
3739 	if (rc)
3740 		return rc;
3741 
3742 	rc = ebitmap_write(&usrdatum->roles, fp);
3743 	if (rc)
3744 		return rc;
3745 
3746 	rc = mls_write_range_helper(&usrdatum->range, fp);
3747 	if (rc)
3748 		return rc;
3749 
3750 	rc = mls_write_level(&usrdatum->dfltlevel, fp);
3751 	if (rc)
3752 		return rc;
3753 
3754 	return 0;
3755 }
3756 
3757 /* clang-format off */
3758 static int (*const write_f[SYM_NUM])(void *key, void *datum, void *datap) = {
3759 	common_write,
3760 	class_write,
3761 	role_write,
3762 	type_write,
3763 	user_write,
3764 	cond_write_bool,
3765 	sens_write,
3766 	cat_write,
3767 };
3768 /* clang-format on */
3769 
3770 static int ocontext_write(struct policydb *p,
3771 			  const struct policydb_compat_info *info,
3772 			  struct policy_file *fp)
3773 {
3774 	unsigned int i, j;
3775 	int rc;
3776 	size_t nel, len;
3777 	__be64 prefixbuf[1];
3778 	__le32 buf[3];
3779 	u32 nodebuf[8];
3780 	struct ocontext *c;
3781 	for (i = 0; i < info->ocon_num; i++) {
3782 		nel = 0;
3783 		for (c = p->ocontexts[i]; c; c = c->next)
3784 			nel++;
3785 		buf[0] = cpu_to_le32(nel);
3786 		rc = put_entry(buf, sizeof(u32), 1, fp);
3787 		if (rc)
3788 			return rc;
3789 		for (c = p->ocontexts[i]; c; c = c->next) {
3790 			switch (i) {
3791 			case OCON_ISID:
3792 				buf[0] = cpu_to_le32(c->sid[0]);
3793 				rc = put_entry(buf, sizeof(u32), 1, fp);
3794 				if (rc)
3795 					return rc;
3796 				rc = context_write(p, &c->context[0], fp);
3797 				if (rc)
3798 					return rc;
3799 				break;
3800 			case OCON_FS:
3801 			case OCON_NETIF:
3802 				len = strlen(c->u.name);
3803 				buf[0] = cpu_to_le32(len);
3804 				rc = put_entry(buf, sizeof(u32), 1, fp);
3805 				if (rc)
3806 					return rc;
3807 				rc = put_entry(c->u.name, 1, len, fp);
3808 				if (rc)
3809 					return rc;
3810 				rc = context_write(p, &c->context[0], fp);
3811 				if (rc)
3812 					return rc;
3813 				rc = context_write(p, &c->context[1], fp);
3814 				if (rc)
3815 					return rc;
3816 				break;
3817 			case OCON_PORT:
3818 				buf[0] = cpu_to_le32(c->u.port.protocol);
3819 				buf[1] = cpu_to_le32(c->u.port.low_port);
3820 				buf[2] = cpu_to_le32(c->u.port.high_port);
3821 				rc = put_entry(buf, sizeof(u32), 3, fp);
3822 				if (rc)
3823 					return rc;
3824 				rc = context_write(p, &c->context[0], fp);
3825 				if (rc)
3826 					return rc;
3827 				break;
3828 			case OCON_NODE:
3829 				nodebuf[0] = c->u.node.addr; /* network order */
3830 				nodebuf[1] = c->u.node.mask; /* network order */
3831 				rc = put_entry(nodebuf, sizeof(u32), 2, fp);
3832 				if (rc)
3833 					return rc;
3834 				rc = context_write(p, &c->context[0], fp);
3835 				if (rc)
3836 					return rc;
3837 				break;
3838 			case OCON_FSUSE:
3839 				buf[0] = cpu_to_le32(c->v.behavior);
3840 				len = strlen(c->u.name);
3841 				buf[1] = cpu_to_le32(len);
3842 				rc = put_entry(buf, sizeof(u32), 2, fp);
3843 				if (rc)
3844 					return rc;
3845 				rc = put_entry(c->u.name, 1, len, fp);
3846 				if (rc)
3847 					return rc;
3848 				rc = context_write(p, &c->context[0], fp);
3849 				if (rc)
3850 					return rc;
3851 				break;
3852 			case OCON_NODE6:
3853 				for (j = 0; j < 4; j++)
3854 					nodebuf[j] =
3855 						c->u.node6.addr
3856 							[j]; /* network order */
3857 				for (j = 0; j < 4; j++)
3858 					nodebuf[j + 4] =
3859 						c->u.node6.mask
3860 							[j]; /* network order */
3861 				rc = put_entry(nodebuf, sizeof(u32), 8, fp);
3862 				if (rc)
3863 					return rc;
3864 				rc = context_write(p, &c->context[0], fp);
3865 				if (rc)
3866 					return rc;
3867 				break;
3868 			case OCON_IBPKEY:
3869 				/* subnet_prefix is in CPU order */
3870 				prefixbuf[0] =
3871 					cpu_to_be64(c->u.ibpkey.subnet_prefix);
3872 
3873 				rc = put_entry(prefixbuf, sizeof(u64), 1, fp);
3874 				if (rc)
3875 					return rc;
3876 
3877 				buf[0] = cpu_to_le32(c->u.ibpkey.low_pkey);
3878 				buf[1] = cpu_to_le32(c->u.ibpkey.high_pkey);
3879 
3880 				rc = put_entry(buf, sizeof(u32), 2, fp);
3881 				if (rc)
3882 					return rc;
3883 				rc = context_write(p, &c->context[0], fp);
3884 				if (rc)
3885 					return rc;
3886 				break;
3887 			case OCON_IBENDPORT:
3888 				len = strlen(c->u.ibendport.dev_name);
3889 				buf[0] = cpu_to_le32(len);
3890 				buf[1] = cpu_to_le32(c->u.ibendport.port);
3891 				rc = put_entry(buf, sizeof(u32), 2, fp);
3892 				if (rc)
3893 					return rc;
3894 				rc = put_entry(c->u.ibendport.dev_name, 1, len,
3895 					       fp);
3896 				if (rc)
3897 					return rc;
3898 				rc = context_write(p, &c->context[0], fp);
3899 				if (rc)
3900 					return rc;
3901 				break;
3902 			}
3903 		}
3904 	}
3905 	return 0;
3906 }
3907 
3908 static int genfs_write(struct policydb *p, struct policy_file *fp)
3909 {
3910 	struct genfs *genfs;
3911 	struct ocontext *c;
3912 	size_t len;
3913 	__le32 buf[1];
3914 	int rc;
3915 
3916 	len = 0;
3917 	for (genfs = p->genfs; genfs; genfs = genfs->next)
3918 		len++;
3919 	buf[0] = cpu_to_le32(len);
3920 	rc = put_entry(buf, sizeof(u32), 1, fp);
3921 	if (rc)
3922 		return rc;
3923 	for (genfs = p->genfs; genfs; genfs = genfs->next) {
3924 		len = strlen(genfs->fstype);
3925 		buf[0] = cpu_to_le32(len);
3926 		rc = put_entry(buf, sizeof(u32), 1, fp);
3927 		if (rc)
3928 			return rc;
3929 		rc = put_entry(genfs->fstype, 1, len, fp);
3930 		if (rc)
3931 			return rc;
3932 		len = 0;
3933 		for (c = genfs->head; c; c = c->next)
3934 			len++;
3935 		buf[0] = cpu_to_le32(len);
3936 		rc = put_entry(buf, sizeof(u32), 1, fp);
3937 		if (rc)
3938 			return rc;
3939 		for (c = genfs->head; c; c = c->next) {
3940 			len = strlen(c->u.name);
3941 			buf[0] = cpu_to_le32(len);
3942 			rc = put_entry(buf, sizeof(u32), 1, fp);
3943 			if (rc)
3944 				return rc;
3945 			rc = put_entry(c->u.name, 1, len, fp);
3946 			if (rc)
3947 				return rc;
3948 			buf[0] = cpu_to_le32(c->v.sclass);
3949 			rc = put_entry(buf, sizeof(u32), 1, fp);
3950 			if (rc)
3951 				return rc;
3952 			rc = context_write(p, &c->context[0], fp);
3953 			if (rc)
3954 				return rc;
3955 		}
3956 	}
3957 	return 0;
3958 }
3959 
3960 static int range_write_helper(void *key, void *data, void *ptr)
3961 {
3962 	__le32 buf[2];
3963 	struct range_trans *rt = key;
3964 	struct mls_range *r = data;
3965 	struct policy_data *pd = ptr;
3966 	struct policy_file *fp = pd->fp;
3967 	struct policydb *p = pd->p;
3968 	int rc;
3969 
3970 	buf[0] = cpu_to_le32(rt->source_type);
3971 	buf[1] = cpu_to_le32(rt->target_type);
3972 	rc = put_entry(buf, sizeof(u32), 2, fp);
3973 	if (rc)
3974 		return rc;
3975 	if (p->policyvers >= POLICYDB_VERSION_RANGETRANS) {
3976 		buf[0] = cpu_to_le32(rt->target_class);
3977 		rc = put_entry(buf, sizeof(u32), 1, fp);
3978 		if (rc)
3979 			return rc;
3980 	}
3981 	rc = mls_write_range_helper(r, fp);
3982 	if (rc)
3983 		return rc;
3984 
3985 	return 0;
3986 }
3987 
3988 static int range_write(struct policydb *p, struct policy_file *fp)
3989 {
3990 	__le32 buf[1];
3991 	int rc;
3992 	struct policy_data pd;
3993 
3994 	pd.p = p;
3995 	pd.fp = fp;
3996 
3997 	buf[0] = cpu_to_le32(p->range_tr.nel);
3998 	rc = put_entry(buf, sizeof(u32), 1, fp);
3999 	if (rc)
4000 		return rc;
4001 
4002 	/* actually write all of the entries */
4003 	rc = hashtab_map(&p->range_tr, range_write_helper, &pd);
4004 	if (rc)
4005 		return rc;
4006 
4007 	return 0;
4008 }
4009 
4010 static int filename_write_helper_compat(void *key, void *data, void *ptr)
4011 {
4012 	struct filename_trans_key *ft = key;
4013 	struct filename_trans_datum *datum = data;
4014 	struct ebitmap_node *node;
4015 	struct policy_file *fp = ptr;
4016 	__le32 buf[4];
4017 	int rc;
4018 	u32 bit, len = strlen(ft->name);
4019 
4020 	do {
4021 		ebitmap_for_each_positive_bit(&datum->stypes, node, bit)
4022 		{
4023 			buf[0] = cpu_to_le32(len);
4024 			rc = put_entry(buf, sizeof(u32), 1, fp);
4025 			if (rc)
4026 				return rc;
4027 
4028 			rc = put_entry(ft->name, sizeof(char), len, fp);
4029 			if (rc)
4030 				return rc;
4031 
4032 			buf[0] = cpu_to_le32(bit + 1);
4033 			buf[1] = cpu_to_le32(ft->ttype);
4034 			buf[2] = cpu_to_le32(ft->tclass);
4035 			buf[3] = cpu_to_le32(datum->otype);
4036 
4037 			rc = put_entry(buf, sizeof(u32), 4, fp);
4038 			if (rc)
4039 				return rc;
4040 		}
4041 
4042 		datum = datum->next;
4043 	} while (unlikely(datum));
4044 
4045 	return 0;
4046 }
4047 
4048 static int filename_write_helper(void *key, void *data, void *ptr)
4049 {
4050 	struct filename_trans_key *ft = key;
4051 	struct filename_trans_datum *datum;
4052 	struct policy_file *fp = ptr;
4053 	__le32 buf[3];
4054 	int rc;
4055 	u32 ndatum, len = strlen(ft->name);
4056 
4057 	buf[0] = cpu_to_le32(len);
4058 	rc = put_entry(buf, sizeof(u32), 1, fp);
4059 	if (rc)
4060 		return rc;
4061 
4062 	rc = put_entry(ft->name, sizeof(char), len, fp);
4063 	if (rc)
4064 		return rc;
4065 
4066 	ndatum = 0;
4067 	datum = data;
4068 	do {
4069 		ndatum++;
4070 		datum = datum->next;
4071 	} while (unlikely(datum));
4072 
4073 	buf[0] = cpu_to_le32(ft->ttype);
4074 	buf[1] = cpu_to_le32(ft->tclass);
4075 	buf[2] = cpu_to_le32(ndatum);
4076 	rc = put_entry(buf, sizeof(u32), 3, fp);
4077 	if (rc)
4078 		return rc;
4079 
4080 	datum = data;
4081 	do {
4082 		rc = ebitmap_write(&datum->stypes, fp);
4083 		if (rc)
4084 			return rc;
4085 
4086 		buf[0] = cpu_to_le32(datum->otype);
4087 		rc = put_entry(buf, sizeof(u32), 1, fp);
4088 		if (rc)
4089 			return rc;
4090 
4091 		datum = datum->next;
4092 	} while (unlikely(datum));
4093 
4094 	return 0;
4095 }
4096 
4097 static int filename_trans_write(struct policydb *p, struct policy_file *fp)
4098 {
4099 	__le32 buf[1];
4100 	int rc;
4101 
4102 	if (p->policyvers < POLICYDB_VERSION_FILENAME_TRANS)
4103 		return 0;
4104 
4105 	if (p->policyvers < POLICYDB_VERSION_COMP_FTRANS) {
4106 		buf[0] = cpu_to_le32(p->compat_filename_trans_count);
4107 		rc = put_entry(buf, sizeof(u32), 1, fp);
4108 		if (rc)
4109 			return rc;
4110 
4111 		rc = hashtab_map(&p->filename_trans,
4112 				 filename_write_helper_compat, fp);
4113 	} else {
4114 		buf[0] = cpu_to_le32(p->filename_trans.nel);
4115 		rc = put_entry(buf, sizeof(u32), 1, fp);
4116 		if (rc)
4117 			return rc;
4118 
4119 		rc = hashtab_map(&p->filename_trans, filename_write_helper, fp);
4120 	}
4121 	return rc;
4122 }
4123 
4124 /*
4125  * Write the configuration data in a policy database
4126  * structure to a policy database binary representation
4127  * file.
4128  */
4129 int policydb_write(struct policydb *p, struct policy_file *fp)
4130 {
4131 	unsigned int num_syms;
4132 	int rc;
4133 	__le32 buf[4];
4134 	u32 config, i;
4135 	size_t len;
4136 	const struct policydb_compat_info *info;
4137 
4138 	/*
4139 	 * refuse to write policy older than compressed avtab
4140 	 * to simplify the writer.  There are other tests dropped
4141 	 * since we assume this throughout the writer code.  Be
4142 	 * careful if you ever try to remove this restriction
4143 	 */
4144 	if (p->policyvers < POLICYDB_VERSION_AVTAB) {
4145 		pr_err("SELinux: refusing to write policy version %d."
4146 		       "  Because it is less than version %d\n",
4147 		       p->policyvers, POLICYDB_VERSION_AVTAB);
4148 		return -EINVAL;
4149 	}
4150 
4151 	config = 0;
4152 	if (p->mls_enabled)
4153 		config |= POLICYDB_CONFIG_MLS;
4154 
4155 	if (p->reject_unknown)
4156 		config |= REJECT_UNKNOWN;
4157 	if (p->allow_unknown)
4158 		config |= ALLOW_UNKNOWN;
4159 
4160 	/* Write the magic number and string identifiers. */
4161 	buf[0] = cpu_to_le32(POLICYDB_MAGIC);
4162 	len = strlen(POLICYDB_STRING);
4163 	buf[1] = cpu_to_le32(len);
4164 	rc = put_entry(buf, sizeof(u32), 2, fp);
4165 	if (rc)
4166 		return rc;
4167 	rc = put_entry(POLICYDB_STRING, 1, len, fp);
4168 	if (rc)
4169 		return rc;
4170 
4171 	/* Write the version, config, and table sizes. */
4172 	info = policydb_lookup_compat(p->policyvers);
4173 	if (!info) {
4174 		pr_err("SELinux: compatibility lookup failed for policy "
4175 		       "version %d\n",
4176 		       p->policyvers);
4177 		return -EINVAL;
4178 	}
4179 
4180 	buf[0] = cpu_to_le32(p->policyvers);
4181 	buf[1] = cpu_to_le32(config);
4182 	buf[2] = cpu_to_le32(info->sym_num);
4183 	buf[3] = cpu_to_le32(info->ocon_num);
4184 
4185 	rc = put_entry(buf, sizeof(u32), 4, fp);
4186 	if (rc)
4187 		return rc;
4188 
4189 	if (p->policyvers >= POLICYDB_VERSION_POLCAP) {
4190 		rc = ebitmap_write(&p->policycaps, fp);
4191 		if (rc)
4192 			return rc;
4193 	}
4194 
4195 	if (p->policyvers >= POLICYDB_VERSION_PERMISSIVE) {
4196 		rc = ebitmap_write(&p->permissive_map, fp);
4197 		if (rc)
4198 			return rc;
4199 	}
4200 
4201 	if (p->policyvers >= POLICYDB_VERSION_NEVERAUDIT) {
4202 		rc = ebitmap_write(&p->neveraudit_map, fp);
4203 		if (rc)
4204 			return rc;
4205 	}
4206 
4207 	num_syms = info->sym_num;
4208 	for (i = 0; i < num_syms; i++) {
4209 		struct policy_data pd;
4210 
4211 		pd.fp = fp;
4212 		pd.p = p;
4213 
4214 		buf[0] = cpu_to_le32(p->symtab[i].nprim);
4215 		buf[1] = cpu_to_le32(p->symtab[i].table.nel);
4216 
4217 		rc = put_entry(buf, sizeof(u32), 2, fp);
4218 		if (rc)
4219 			return rc;
4220 		rc = hashtab_map(&p->symtab[i].table, write_f[i], &pd);
4221 		if (rc)
4222 			return rc;
4223 	}
4224 
4225 	rc = avtab_write(p, &p->te_avtab, fp);
4226 	if (rc)
4227 		return rc;
4228 
4229 	rc = cond_write_list(p, fp);
4230 	if (rc)
4231 		return rc;
4232 
4233 	rc = role_trans_write(p, fp);
4234 	if (rc)
4235 		return rc;
4236 
4237 	rc = role_allow_write(p->role_allow, fp);
4238 	if (rc)
4239 		return rc;
4240 
4241 	rc = filename_trans_write(p, fp);
4242 	if (rc)
4243 		return rc;
4244 
4245 	rc = ocontext_write(p, info, fp);
4246 	if (rc)
4247 		return rc;
4248 
4249 	rc = genfs_write(p, fp);
4250 	if (rc)
4251 		return rc;
4252 
4253 	rc = range_write(p, fp);
4254 	if (rc)
4255 		return rc;
4256 
4257 	for (i = 0; i < p->p_types.nprim; i++) {
4258 		struct ebitmap *e = &p->type_attr_map_array[i];
4259 
4260 		rc = ebitmap_write(e, fp);
4261 		if (rc)
4262 			return rc;
4263 	}
4264 
4265 	return 0;
4266 }
4267