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