xref: /linux/security/apparmor/policy_unpack.c (revision a0b7091c4de45a7325c8780e6934a894f92ac86b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * AppArmor security module
4  *
5  * This file contains AppArmor functions for unpacking policy loaded from
6  * userspace.
7  *
8  * Copyright (C) 1998-2008 Novell/SUSE
9  * Copyright 2009-2010 Canonical Ltd.
10  *
11  * AppArmor uses a serialized binary format for loading policy. To find
12  * policy format documentation see Documentation/admin-guide/LSM/apparmor.rst
13  * All policy is validated before it is used.
14  */
15 
16 #include <linux/unaligned.h>
17 #include <kunit/visibility.h>
18 #include <linux/ctype.h>
19 #include <linux/errno.h>
20 #include <linux/zstd.h>
21 
22 #include "include/apparmor.h"
23 #include "include/audit.h"
24 #include "include/cred.h"
25 #include "include/crypto.h"
26 #include "include/file.h"
27 #include "include/match.h"
28 #include "include/path.h"
29 #include "include/policy.h"
30 #include "include/policy_unpack.h"
31 #include "include/policy_compat.h"
32 #include "include/signal.h"
33 
34 /* audit callback for unpack fields */
35 static void audit_cb(struct audit_buffer *ab, void *va)
36 {
37 	struct common_audit_data *sa = va;
38 	struct apparmor_audit_data *ad = aad(sa);
39 
40 	if (ad->iface.ns) {
41 		audit_log_format(ab, " ns=");
42 		audit_log_untrustedstring(ab, ad->iface.ns);
43 	}
44 	if (ad->name) {
45 		audit_log_format(ab, " name=");
46 		audit_log_untrustedstring(ab, ad->name);
47 	}
48 	if (ad->iface.pos)
49 		audit_log_format(ab, " offset=%ld", ad->iface.pos);
50 }
51 
52 /**
53  * audit_iface - do audit message for policy unpacking/load/replace/remove
54  * @new: profile if it has been allocated (MAYBE NULL)
55  * @ns_name: name of the ns the profile is to be loaded to (MAY BE NULL)
56  * @name: name of the profile being manipulated (MAYBE NULL)
57  * @info: any extra info about the failure (MAYBE NULL)
58  * @e: buffer position info
59  * @error: error code
60  *
61  * Returns: %0 or error
62  */
63 static int audit_iface(struct aa_profile *new, const char *ns_name,
64 		       const char *name, const char *info, struct aa_ext *e,
65 		       int error)
66 {
67 	struct aa_profile *profile = labels_profile(aa_current_raw_label());
68 	DEFINE_AUDIT_DATA(ad, LSM_AUDIT_DATA_NONE, AA_CLASS_NONE, NULL);
69 	if (e)
70 		ad.iface.pos = e->pos - e->start;
71 	ad.iface.ns = ns_name;
72 	if (new)
73 		ad.name = new->base.hname;
74 	else
75 		ad.name = name;
76 	ad.info = info;
77 	ad.error = error;
78 
79 	return aa_audit(AUDIT_APPARMOR_STATUS, profile, &ad, audit_cb);
80 }
81 
82 void __aa_loaddata_update(struct aa_loaddata *data, long revision)
83 {
84 	AA_BUG(!data);
85 	AA_BUG(!data->ns);
86 	AA_BUG(!mutex_is_locked(&data->ns->lock));
87 	AA_BUG(data->revision > revision);
88 
89 	data->revision = revision;
90 	if ((data->dents[AAFS_LOADDATA_REVISION])) {
91 		struct inode *inode;
92 
93 		inode = d_inode(data->dents[AAFS_LOADDATA_DIR]);
94 		inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
95 
96 		inode = d_inode(data->dents[AAFS_LOADDATA_REVISION]);
97 		inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
98 	}
99 }
100 
101 bool aa_rawdata_eq(struct aa_loaddata *l, struct aa_loaddata *r)
102 {
103 	if (l->size != r->size)
104 		return false;
105 	if (l->compressed_size != r->compressed_size)
106 		return false;
107 	if (aa_g_hash_policy && memcmp(l->hash, r->hash, aa_hash_size()) != 0)
108 		return false;
109 	return memcmp(l->data, r->data, r->compressed_size ?: r->size) == 0;
110 }
111 
112 static void do_loaddata_free(struct aa_loaddata *d)
113 {
114 	kfree_sensitive(d->hash);
115 	kfree_sensitive(d->name);
116 	kvfree(d->data);
117 	kfree_sensitive(d);
118 }
119 
120 void aa_loaddata_kref(struct kref *kref)
121 {
122 	struct aa_loaddata *d = container_of(kref, struct aa_loaddata, count);
123 
124 	do_loaddata_free(d);
125 }
126 
127 /*
128  * need to take the ns mutex lock which is NOT safe most places that
129  * put_loaddata is called, so we have to delay freeing it
130  */
131 static void do_ploaddata_rmfs(struct work_struct *work)
132 {
133 	struct aa_loaddata *d = container_of(work, struct aa_loaddata, work);
134 	struct aa_ns *ns = aa_get_ns(d->ns);
135 
136 	if (ns) {
137 		mutex_lock_nested(&ns->lock, ns->level);
138 		/* remove fs ref to loaddata */
139 		__aa_fs_remove_rawdata(d);
140 		mutex_unlock(&ns->lock);
141 		aa_put_ns(ns);
142 	}
143 	/* called by dropping last pcount, so drop its associated icount */
144 	aa_put_i_loaddata(d);
145 }
146 
147 void aa_ploaddata_kref(struct kref *kref)
148 {
149 	struct aa_loaddata *d = container_of(kref, struct aa_loaddata, pcount);
150 
151 	if (d) {
152 		INIT_WORK(&d->work, do_ploaddata_rmfs);
153 		schedule_work(&d->work);
154 	}
155 }
156 
157 struct aa_loaddata *aa_loaddata_alloc(size_t size)
158 {
159 	struct aa_loaddata *d;
160 
161 	d = kzalloc_obj(*d);
162 	if (d == NULL)
163 		return ERR_PTR(-ENOMEM);
164 	d->data = kvzalloc(size, GFP_KERNEL);
165 	if (!d->data) {
166 		kfree(d);
167 		return ERR_PTR(-ENOMEM);
168 	}
169 	kref_init(&d->count);
170 	kref_init(&d->pcount);
171 	INIT_LIST_HEAD(&d->list);
172 
173 	return d;
174 }
175 
176 /* test if read will be in packed data bounds */
177 VISIBLE_IF_KUNIT bool aa_inbounds(struct aa_ext *e, size_t size)
178 {
179 	return (size <= e->end - e->pos);
180 }
181 EXPORT_SYMBOL_IF_KUNIT(aa_inbounds);
182 
183 /**
184  * aa_unpack_u16_chunk - test and do bounds checking for a u16 size based chunk
185  * @e: serialized data read head (NOT NULL)
186  * @chunk: start address for chunk of data (NOT NULL)
187  *
188  * Returns: the size of chunk found with the read head at the end of the chunk.
189  */
190 VISIBLE_IF_KUNIT size_t aa_unpack_u16_chunk(struct aa_ext *e, char **chunk)
191 {
192 	size_t size = 0;
193 	void *pos = e->pos;
194 
195 	if (!aa_inbounds(e, sizeof(u16)))
196 		goto fail;
197 	size = le16_to_cpu(get_unaligned((__le16 *) e->pos));
198 	e->pos += sizeof(__le16);
199 	if (!aa_inbounds(e, size))
200 		goto fail;
201 	*chunk = e->pos;
202 	e->pos += size;
203 	return size;
204 
205 fail:
206 	e->pos = pos;
207 	return 0;
208 }
209 EXPORT_SYMBOL_IF_KUNIT(aa_unpack_u16_chunk);
210 
211 /* unpack control byte */
212 VISIBLE_IF_KUNIT bool aa_unpack_X(struct aa_ext *e, enum aa_code code)
213 {
214 	if (!aa_inbounds(e, 1))
215 		return false;
216 	if (*(u8 *) e->pos != code)
217 		return false;
218 	e->pos++;
219 	return true;
220 }
221 EXPORT_SYMBOL_IF_KUNIT(aa_unpack_X);
222 
223 /**
224  * aa_unpack_nameX - check is the next element is of type X with a name of @name
225  * @e: serialized data extent information  (NOT NULL)
226  * @code: type code
227  * @name: name to match to the serialized element.  (MAYBE NULL)
228  *
229  * check that the next serialized data element is of type X and has a tag
230  * name @name.  If @name is specified then there must be a matching
231  * name element in the stream.  If @name is NULL any name element will be
232  * skipped and only the typecode will be tested.
233  *
234  * Returns true on success (both type code and name tests match) and the read
235  * head is advanced past the headers
236  *
237  * Returns: false if either match fails, the read head does not move
238  */
239 VISIBLE_IF_KUNIT bool aa_unpack_nameX(struct aa_ext *e, enum aa_code code, const char *name)
240 {
241 	/*
242 	 * May need to reset pos if name or type doesn't match
243 	 */
244 	void *pos = e->pos;
245 	/*
246 	 * Check for presence of a tagname, and if present name size
247 	 * AA_NAME tag value is a u16.
248 	 */
249 	if (aa_unpack_X(e, AA_NAME)) {
250 		char *tag = NULL;
251 		size_t size = aa_unpack_u16_chunk(e, &tag);
252 		/* if a name is specified it must match. otherwise skip tag */
253 		if (name && (!size || tag[size-1] != '\0' || strcmp(name, tag)))
254 			goto fail;
255 	} else if (name) {
256 		/* if a name is specified and there is no name tag fail */
257 		goto fail;
258 	}
259 
260 	/* now check if type code matches */
261 	if (aa_unpack_X(e, code))
262 		return true;
263 
264 fail:
265 	e->pos = pos;
266 	return false;
267 }
268 EXPORT_SYMBOL_IF_KUNIT(aa_unpack_nameX);
269 
270 static bool unpack_u8(struct aa_ext *e, u8 *data, const char *name)
271 {
272 	void *pos = e->pos;
273 
274 	if (aa_unpack_nameX(e, AA_U8, name)) {
275 		if (!aa_inbounds(e, sizeof(u8)))
276 			goto fail;
277 		if (data)
278 			*data = *((u8 *)e->pos);
279 		e->pos += sizeof(u8);
280 		return true;
281 	}
282 
283 fail:
284 	e->pos = pos;
285 	return false;
286 }
287 
288 VISIBLE_IF_KUNIT bool aa_unpack_u32(struct aa_ext *e, u32 *data, const char *name)
289 {
290 	void *pos = e->pos;
291 
292 	if (aa_unpack_nameX(e, AA_U32, name)) {
293 		if (!aa_inbounds(e, sizeof(u32)))
294 			goto fail;
295 		if (data)
296 			*data = le32_to_cpu(get_unaligned((__le32 *) e->pos));
297 		e->pos += sizeof(u32);
298 		return true;
299 	}
300 
301 fail:
302 	e->pos = pos;
303 	return false;
304 }
305 EXPORT_SYMBOL_IF_KUNIT(aa_unpack_u32);
306 
307 VISIBLE_IF_KUNIT bool aa_unpack_u64(struct aa_ext *e, u64 *data, const char *name)
308 {
309 	void *pos = e->pos;
310 
311 	if (aa_unpack_nameX(e, AA_U64, name)) {
312 		if (!aa_inbounds(e, sizeof(u64)))
313 			goto fail;
314 		if (data)
315 			*data = le64_to_cpu(get_unaligned((__le64 *) e->pos));
316 		e->pos += sizeof(u64);
317 		return true;
318 	}
319 
320 fail:
321 	e->pos = pos;
322 	return false;
323 }
324 EXPORT_SYMBOL_IF_KUNIT(aa_unpack_u64);
325 
326 static bool aa_unpack_cap_low(struct aa_ext *e, kernel_cap_t *data, const char *name)
327 {
328 	u32 val;
329 
330 	if (!aa_unpack_u32(e, &val, name))
331 		return false;
332 	data->val = val;
333 	return true;
334 }
335 
336 static bool aa_unpack_cap_high(struct aa_ext *e, kernel_cap_t *data, const char *name)
337 {
338 	u32 val;
339 
340 	if (!aa_unpack_u32(e, &val, name))
341 		return false;
342 	data->val = (u32)data->val | ((u64)val << 32);
343 	return true;
344 }
345 
346 VISIBLE_IF_KUNIT bool aa_unpack_array(struct aa_ext *e, const char *name, u16 *size)
347 {
348 	void *pos = e->pos;
349 
350 	if (aa_unpack_nameX(e, AA_ARRAY, name)) {
351 		if (!aa_inbounds(e, sizeof(u16)))
352 			goto fail;
353 		*size = le16_to_cpu(get_unaligned((__le16 *) e->pos));
354 		e->pos += sizeof(u16);
355 		return true;
356 	}
357 
358 fail:
359 	e->pos = pos;
360 	return false;
361 }
362 EXPORT_SYMBOL_IF_KUNIT(aa_unpack_array);
363 
364 VISIBLE_IF_KUNIT size_t aa_unpack_blob(struct aa_ext *e, char **blob, const char *name)
365 {
366 	void *pos = e->pos;
367 
368 	if (aa_unpack_nameX(e, AA_BLOB, name)) {
369 		u32 size;
370 		if (!aa_inbounds(e, sizeof(u32)))
371 			goto fail;
372 		size = le32_to_cpu(get_unaligned((__le32 *) e->pos));
373 		e->pos += sizeof(u32);
374 		if (aa_inbounds(e, (size_t) size)) {
375 			*blob = e->pos;
376 			e->pos += size;
377 			return size;
378 		}
379 	}
380 
381 fail:
382 	e->pos = pos;
383 	return 0;
384 }
385 EXPORT_SYMBOL_IF_KUNIT(aa_unpack_blob);
386 
387 VISIBLE_IF_KUNIT int aa_unpack_str(struct aa_ext *e, const char **string, const char *name)
388 {
389 	char *src_str;
390 	size_t size = 0;
391 	void *pos = e->pos;
392 	*string = NULL;
393 	if (aa_unpack_nameX(e, AA_STRING, name)) {
394 		size = aa_unpack_u16_chunk(e, &src_str);
395 		if (size) {
396 			/* strings are null terminated, length is size - 1 */
397 			if (src_str[size - 1] != 0)
398 				goto fail;
399 			*string = src_str;
400 
401 			return size;
402 		}
403 	}
404 
405 fail:
406 	e->pos = pos;
407 	return 0;
408 }
409 EXPORT_SYMBOL_IF_KUNIT(aa_unpack_str);
410 
411 VISIBLE_IF_KUNIT int aa_unpack_strdup(struct aa_ext *e, char **string, const char *name)
412 {
413 	const char *tmp;
414 	void *pos = e->pos;
415 	int res = aa_unpack_str(e, &tmp, name);
416 	*string = NULL;
417 
418 	if (!res)
419 		return 0;
420 
421 	*string = kmemdup(tmp, res, GFP_KERNEL);
422 	if (!*string) {
423 		e->pos = pos;
424 		return 0;
425 	}
426 
427 	return res;
428 }
429 EXPORT_SYMBOL_IF_KUNIT(aa_unpack_strdup);
430 
431 
432 /**
433  * unpack_dfa - unpack a file rule dfa
434  * @e: serialized data extent information (NOT NULL)
435  * @flags: dfa flags to check
436  *
437  * returns dfa or ERR_PTR or NULL if no dfa
438  */
439 static struct aa_dfa *unpack_dfa(struct aa_ext *e, int flags)
440 {
441 	char *blob = NULL;
442 	size_t size;
443 	struct aa_dfa *dfa = NULL;
444 
445 	size = aa_unpack_blob(e, &blob, "aadfa");
446 	if (size) {
447 		/*
448 		 * The dfa is aligned with in the blob to 8 bytes
449 		 * from the beginning of the stream.
450 		 * alignment adjust needed by dfa unpack
451 		 */
452 		size_t sz = blob - (char *) e->start -
453 			((e->pos - e->start) & 7);
454 		size_t pad = ALIGN(sz, 8) - sz;
455 		if (aa_g_paranoid_load)
456 			flags |= DFA_FLAG_VERIFY_STATES;
457 		dfa = aa_dfa_unpack(blob + pad, size - pad, flags);
458 
459 		if (IS_ERR(dfa))
460 			return dfa;
461 
462 	}
463 
464 	return dfa;
465 }
466 
467 static int process_strs_entry(char *str, int size, bool multi)
468 {
469 	int c = 1;
470 
471 	if (size <= 0)
472 		return -1;
473 	if (multi) {
474 		if (size < 2)
475 			return -2;
476 		/* multi ends with double \0 */
477 		if (str[size - 2])
478 			return -3;
479 	}
480 
481 	char *save = str;
482 	char *pos = str;
483 	char *end = multi ? str + size - 2 : str + size - 1;
484 	/* count # of internal \0 */
485 	while (str < end) {
486 		if (str == pos) {
487 			/* starts with ... */
488 			if (!*str) {
489 				AA_DEBUG(DEBUG_UNPACK,
490 					 "starting with null save=%lu size %d c=%d",
491 					 (unsigned long)(str - save), size, c);
492 				return -4;
493 			}
494 			if (isspace(*str))
495 				return -5;
496 			if (*str == ':') {
497 				/* :ns_str\0str\0
498 				 * first character after : must be valid
499 				 */
500 				if (!str[1])
501 					return -6;
502 			}
503 		} else if (!*str) {
504 			if (*pos == ':')
505 				*str = ':';
506 			else
507 				c++;
508 			pos = str +  1;
509 		}
510 		str++;
511 	} /* while */
512 
513 	return c;
514 }
515 
516 /**
517  * unpack_strs_table - unpack a profile transition table
518  * @e: serialized data extent information  (NOT NULL)
519  * @name: name of table (MAY BE NULL)
520  * @multi: allow multiple strings on a single entry
521  * @strs: str table to unpack to (NOT NULL)
522  *
523  * Returns: 0 if table successfully unpacked or not present, else error
524  */
525 static int unpack_strs_table(struct aa_ext *e, const char *name, bool multi,
526 			      struct aa_str_table *strs)
527 {
528 	void *saved_pos = e->pos;
529 	struct aa_str_table_ent *table = NULL;
530 	int error = -EPROTO;
531 
532 	/* exec table is optional */
533 	if (aa_unpack_nameX(e, AA_STRUCT, name)) {
534 		u16 size;
535 		int i;
536 
537 		if (!aa_unpack_array(e, NULL, &size))
538 			/*
539 			 * Note: index into trans table array is a max
540 			 * of 2^24, but unpack array can only unpack
541 			 * an array of 2^16 in size atm so no need
542 			 * for size check here
543 			 */
544 			goto fail;
545 		table = kzalloc_objs(struct aa_str_table_ent, size);
546 		if (!table) {
547 			error = -ENOMEM;
548 			goto fail;
549 		}
550 		strs->table = table;
551 		strs->size = size;
552 		for (i = 0; i < size; i++) {
553 			char *str;
554 			int c, size2 = aa_unpack_strdup(e, &str, NULL);
555 			/* aa_unpack_strdup verifies that the last character is
556 			 * null termination byte.
557 			 */
558 			c = process_strs_entry(str, size2, multi);
559 			if (c <= 0) {
560 				AA_DEBUG(DEBUG_UNPACK, "process_strs %d i %d pos %ld",
561 					 c, i,
562 					 (unsigned long)(e->pos - saved_pos));
563 				goto fail;
564 			}
565 			if (!multi && c > 1) {
566 				AA_DEBUG(DEBUG_UNPACK, "!multi && c > 1");
567 				/* fail - all other cases with embedded \0 */
568 				goto fail;
569 			}
570 			table[i].strs = str;
571 			table[i].count = c;
572 			table[i].size = size2;
573 		}
574 		if (!aa_unpack_nameX(e, AA_ARRAYEND, NULL))
575 			goto fail;
576 		if (!aa_unpack_nameX(e, AA_STRUCTEND, NULL))
577 			goto fail;
578 	}
579 	return 0;
580 
581 fail:
582 	aa_destroy_str_table(strs);
583 	e->pos = saved_pos;
584 	return error;
585 }
586 
587 static bool unpack_xattrs(struct aa_ext *e, struct aa_profile *profile)
588 {
589 	void *pos = e->pos;
590 
591 	if (aa_unpack_nameX(e, AA_STRUCT, "xattrs")) {
592 		u16 size;
593 		int i;
594 
595 		if (!aa_unpack_array(e, NULL, &size))
596 			goto fail;
597 		profile->attach.xattr_count = size;
598 		profile->attach.xattrs = kcalloc(size, sizeof(char *), GFP_KERNEL);
599 		if (!profile->attach.xattrs)
600 			goto fail;
601 		for (i = 0; i < size; i++) {
602 			if (!aa_unpack_strdup(e, &profile->attach.xattrs[i], NULL))
603 				goto fail;
604 		}
605 		if (!aa_unpack_nameX(e, AA_ARRAYEND, NULL))
606 			goto fail;
607 		if (!aa_unpack_nameX(e, AA_STRUCTEND, NULL))
608 			goto fail;
609 	}
610 
611 	return true;
612 
613 fail:
614 	e->pos = pos;
615 	return false;
616 }
617 
618 static bool unpack_secmark(struct aa_ext *e, struct aa_ruleset *rules)
619 {
620 	void *pos = e->pos;
621 	u16 size;
622 	int i;
623 
624 	if (aa_unpack_nameX(e, AA_STRUCT, "secmark")) {
625 		if (!aa_unpack_array(e, NULL, &size))
626 			goto fail;
627 
628 		rules->secmark = kzalloc_objs(struct aa_secmark, size);
629 		if (!rules->secmark)
630 			goto fail;
631 
632 		rules->secmark_count = size;
633 
634 		for (i = 0; i < size; i++) {
635 			if (!unpack_u8(e, &rules->secmark[i].audit, NULL))
636 				goto fail;
637 			if (!unpack_u8(e, &rules->secmark[i].deny, NULL))
638 				goto fail;
639 			if (!aa_unpack_strdup(e, &rules->secmark[i].label, NULL))
640 				goto fail;
641 		}
642 		if (!aa_unpack_nameX(e, AA_ARRAYEND, NULL))
643 			goto fail;
644 		if (!aa_unpack_nameX(e, AA_STRUCTEND, NULL))
645 			goto fail;
646 	}
647 
648 	return true;
649 
650 fail:
651 	if (rules->secmark) {
652 		for (i = 0; i < size; i++)
653 			kfree_sensitive(rules->secmark[i].label);
654 		kfree_sensitive(rules->secmark);
655 		rules->secmark_count = 0;
656 		rules->secmark = NULL;
657 	}
658 
659 	e->pos = pos;
660 	return false;
661 }
662 
663 static bool unpack_rlimits(struct aa_ext *e, struct aa_ruleset *rules)
664 {
665 	void *pos = e->pos;
666 
667 	/* rlimits are optional */
668 	if (aa_unpack_nameX(e, AA_STRUCT, "rlimits")) {
669 		u16 size;
670 		int i;
671 		u32 tmp = 0;
672 		if (!aa_unpack_u32(e, &tmp, NULL))
673 			goto fail;
674 		rules->rlimits.mask = tmp;
675 
676 		if (!aa_unpack_array(e, NULL, &size) ||
677 		    size > RLIM_NLIMITS)
678 			goto fail;
679 		for (i = 0; i < size; i++) {
680 			u64 tmp2 = 0;
681 			int a = aa_map_resource(i);
682 			if (!aa_unpack_u64(e, &tmp2, NULL))
683 				goto fail;
684 			rules->rlimits.limits[a].rlim_max = tmp2;
685 		}
686 		if (!aa_unpack_nameX(e, AA_ARRAYEND, NULL))
687 			goto fail;
688 		if (!aa_unpack_nameX(e, AA_STRUCTEND, NULL))
689 			goto fail;
690 	}
691 	return true;
692 
693 fail:
694 	e->pos = pos;
695 	return false;
696 }
697 
698 
699 static bool verify_tags(struct aa_tags_struct *tags, const char **info)
700 {
701 	if ((tags->hdrs.size && !tags->hdrs.table) ||
702 	    (!tags->hdrs.size && tags->hdrs.table)) {
703 		*info = "failed verification tag.hdrs disagree";
704 		return false;
705 	}
706 	if ((tags->sets.size && !tags->sets.table) ||
707 	    (!tags->sets.size && tags->sets.table)) {
708 		*info = "failed verification tag.sets disagree";
709 		return false;
710 	}
711 	if ((tags->strs.size && !tags->strs.table) ||
712 	    (!tags->strs.size && tags->strs.table)) {
713 		*info = "failed verification tags->strs disagree";
714 		return false;
715 	}
716 	/* no data present */
717 	if (!tags->sets.size && !tags->hdrs.size && !tags->strs.size) {
718 		return true;
719 	} else if (!(tags->sets.size && tags->hdrs.size && tags->strs.size)) {
720 		/* some data present but not all */
721 		*info = "failed verification tags partial data present";
722 		return false;
723 	}
724 
725 	u32 i;
726 
727 	for (i = 0; i < tags->sets.size; i++) {
728 		/* count followed by count indexes into hdrs */
729 		u32 cnt = tags->sets.table[i];
730 
731 		if (i+cnt >= tags->sets.size) {
732 			AA_DEBUG(DEBUG_UNPACK,
733 				 "tagset too large %d+%d > sets.table[%d]",
734 				 i, cnt, tags->sets.size);
735 			*info = "failed verification tagset too large";
736 			return false;
737 		}
738 		for (; cnt; cnt--) {
739 			if (tags->sets.table[++i] >= tags->hdrs.size) {
740 				AA_DEBUG(DEBUG_UNPACK,
741 					 "tagsets idx out of bounds cnt %d sets.table[%d] >= %d",
742 					 cnt, i-1, tags->hdrs.size);
743 				*info = "failed verification tagsets idx out of bounds";
744 				return false;
745 			}
746 		}
747 	}
748 	for (i = 0; i < tags->hdrs.size; i++) {
749 		u32 idx = tags->hdrs.table[i].tags;
750 
751 		if (idx >= tags->strs.size) {
752 			AA_DEBUG(DEBUG_UNPACK,
753 				 "tag.hdrs idx oob idx %d > tags->strs.size=%d",
754 				 idx, tags->strs.size);
755 			*info = "failed verification tags.hdrs idx out of bounds";
756 			return false;
757 		}
758 		if (tags->hdrs.table[i].count != tags->strs.table[idx].count) {
759 			AA_DEBUG(DEBUG_UNPACK, "hdrs.table[%d].count=%d != tags->strs.table[%d]=%d",
760 				 i, tags->hdrs.table[i].count, idx, tags->strs.table[idx].count);
761 			*info = "failed verification tagd.hdrs[idx].count";
762 			return false;
763 		}
764 		if (tags->hdrs.table[i].size != tags->strs.table[idx].size) {
765 			AA_DEBUG(DEBUG_UNPACK, "hdrs.table[%d].size=%d != strs.table[%d].size=%d",
766 				 i, tags->hdrs.table[i].size, idx, tags->strs.table[idx].size);
767 			*info = "failed verification tagd.hdrs[idx].size";
768 			return false;
769 		}
770 	}
771 
772 	return true;
773 }
774 
775 static int unpack_tagsets(struct aa_ext *e, struct aa_tags_struct *tags)
776 {
777 	u32 *sets;
778 	u16 i, size;
779 	int error = -EPROTO;
780 	void *pos = e->pos;
781 
782 	if (!aa_unpack_array(e, "sets", &size))
783 		goto fail_reset;
784 	sets = kcalloc(size, sizeof(u32), GFP_KERNEL);
785 	if (!sets) {
786 		error = -ENOMEM;
787 		goto fail_reset;
788 	}
789 	for (i = 0; i < size; i++) {
790 		if (!aa_unpack_u32(e, &sets[i], NULL))
791 			goto fail;
792 	}
793 	if (!aa_unpack_nameX(e, AA_ARRAYEND, NULL))
794 		goto fail;
795 
796 	tags->sets.size = size;
797 	tags->sets.table = sets;
798 
799 	return 0;
800 
801 fail:
802 	kfree_sensitive(sets);
803 fail_reset:
804 	e->pos = pos;
805 	return error;
806 }
807 
808 static bool unpack_tag_header_ent(struct aa_ext *e, struct aa_tags_header *h)
809 {
810 	return aa_unpack_u32(e, &h->mask, NULL) &&
811 		aa_unpack_u32(e, &h->count, NULL) &&
812 		aa_unpack_u32(e, &h->size, NULL) &&
813 		aa_unpack_u32(e, &h->tags, NULL);
814 }
815 
816 static int unpack_tag_headers(struct aa_ext *e, struct aa_tags_struct *tags)
817 {
818 	struct aa_tags_header *hdrs;
819 	u16 i, size;
820 	int error = -EPROTO;
821 	void *pos = e->pos;
822 
823 	if (!aa_unpack_array(e, "hdrs", &size))
824 		goto fail_reset;
825 	hdrs = kzalloc_objs(struct aa_tags_header, size);
826 	if (!hdrs) {
827 		error = -ENOMEM;
828 		goto fail_reset;
829 	}
830 	for (i = 0; i < size; i++) {
831 		if (!unpack_tag_header_ent(e, &hdrs[i]))
832 			goto fail;
833 	}
834 	if (!aa_unpack_nameX(e, AA_ARRAYEND, NULL))
835 		goto fail;
836 
837 	tags->hdrs.size = size;
838 	tags->hdrs.table = hdrs;
839 	AA_DEBUG(DEBUG_UNPACK, "headers %ld size %d", (long) hdrs, size);
840 	return true;
841 
842 fail:
843 	kfree_sensitive(hdrs);
844 fail_reset:
845 	e->pos = pos;
846 	return error;
847 }
848 
849 
850 static int unpack_tags(struct aa_ext *e, struct aa_tags_struct *tags,
851 	const char **info)
852 {
853 	int error = -EPROTO;
854 	void *pos = e->pos;
855 
856 	AA_BUG(!tags);
857 	/* policy tags are optional */
858 	if (aa_unpack_nameX(e, AA_STRUCT, "tags")) {
859 		u32 version;
860 
861 		if (!aa_unpack_u32(e, &version, "version") || version != 1) {
862 			*info = "invalid tags version";
863 			goto fail_reset;
864 		}
865 		error = unpack_strs_table(e, "strs", true, &tags->strs);
866 		if (error) {
867 			*info = "failed to unpack profile tag.strs";
868 			goto fail;
869 		}
870 		error = unpack_tag_headers(e, tags);
871 		if (error) {
872 			*info = "failed to unpack profile tag.headers";
873 			goto fail;
874 		}
875 		error = unpack_tagsets(e, tags);
876 		if (error) {
877 			*info = "failed to unpack profile tag.sets";
878 			goto fail;
879 		}
880 		if (!aa_unpack_nameX(e, AA_STRUCTEND, NULL))
881 			goto fail;
882 
883 		if (!verify_tags(tags, info))
884 			goto fail;
885 	}
886 
887 	return 0;
888 
889 fail:
890 	aa_destroy_tags(tags);
891 fail_reset:
892 	e->pos = pos;
893 	return error;
894 }
895 
896 static bool unpack_perm(struct aa_ext *e, u32 version, struct aa_perms *perm)
897 {
898 	u32 reserved;
899 
900 	if (version != 1)
901 		return false;
902 
903 	/* reserved entry is for later expansion, discard for now */
904 	return	aa_unpack_u32(e, &reserved, NULL) &&
905 		aa_unpack_u32(e, &perm->allow, NULL) &&
906 		aa_unpack_u32(e, &perm->deny, NULL) &&
907 		aa_unpack_u32(e, &perm->subtree, NULL) &&
908 		aa_unpack_u32(e, &perm->cond, NULL) &&
909 		aa_unpack_u32(e, &perm->kill, NULL) &&
910 		aa_unpack_u32(e, &perm->complain, NULL) &&
911 		aa_unpack_u32(e, &perm->prompt, NULL) &&
912 		aa_unpack_u32(e, &perm->audit, NULL) &&
913 		aa_unpack_u32(e, &perm->quiet, NULL) &&
914 		aa_unpack_u32(e, &perm->hide, NULL) &&
915 		aa_unpack_u32(e, &perm->xindex, NULL) &&
916 		aa_unpack_u32(e, &perm->tag, NULL) &&
917 		aa_unpack_u32(e, &perm->label, NULL);
918 }
919 
920 static ssize_t unpack_perms_table(struct aa_ext *e, struct aa_perms **perms)
921 {
922 	void *pos = e->pos;
923 	u16 size = 0;
924 
925 	AA_BUG(!perms);
926 	/*
927 	 * policy perms are optional, in which case perms are embedded
928 	 * in the dfa accept table
929 	 */
930 	if (aa_unpack_nameX(e, AA_STRUCT, "perms")) {
931 		int i;
932 		u32 version;
933 
934 		if (!aa_unpack_u32(e, &version, "version"))
935 			goto fail_reset;
936 		if (!aa_unpack_array(e, NULL, &size))
937 			goto fail_reset;
938 		*perms = kzalloc_objs(struct aa_perms, size);
939 		if (!*perms) {
940 			e->pos = pos;
941 			return -ENOMEM;
942 		}
943 		for (i = 0; i < size; i++) {
944 			if (!unpack_perm(e, version, &(*perms)[i]))
945 				goto fail;
946 		}
947 		if (!aa_unpack_nameX(e, AA_ARRAYEND, NULL))
948 			goto fail;
949 		if (!aa_unpack_nameX(e, AA_STRUCTEND, NULL))
950 			goto fail;
951 	} else
952 		*perms = NULL;
953 
954 	return size;
955 
956 fail:
957 	kfree(*perms);
958 fail_reset:
959 	e->pos = pos;
960 	return -EPROTO;
961 }
962 
963 static int unpack_pdb(struct aa_ext *e, struct aa_policydb **policy,
964 		      bool required_dfa, bool required_trans,
965 		      const char **info)
966 {
967 	struct aa_policydb *pdb;
968 	void *pos = e->pos;
969 	int i, flags, error = -EPROTO;
970 	ssize_t size;
971 	u32 version = 0;
972 
973 	pdb = aa_alloc_pdb(GFP_KERNEL);
974 	if (!pdb)
975 		return -ENOMEM;
976 
977 	AA_DEBUG(DEBUG_UNPACK, "unpacking tags");
978 	if (unpack_tags(e, &pdb->tags, info) < 0)
979 		goto fail;
980 	AA_DEBUG(DEBUG_UNPACK, "done unpacking tags");
981 
982 	size = unpack_perms_table(e, &pdb->perms);
983 	if (size < 0) {
984 		error = size;
985 		pdb->perms = NULL;
986 		*info = "failed to unpack - perms";
987 		goto fail;
988 	}
989 	pdb->size = size;
990 
991 	if (pdb->perms) {
992 		/* perms table present accept is index */
993 		flags = TO_ACCEPT1_FLAG(YYTD_DATA32);
994 		if (aa_unpack_u32(e, &version, "permsv") && version > 2)
995 			/* accept2 used for dfa flags */
996 			flags |= TO_ACCEPT2_FLAG(YYTD_DATA32);
997 	} else {
998 		/* packed perms in accept1 and accept2 */
999 		flags = TO_ACCEPT1_FLAG(YYTD_DATA32) |
1000 			TO_ACCEPT2_FLAG(YYTD_DATA32);
1001 	}
1002 
1003 	pdb->dfa = unpack_dfa(e, flags);
1004 	if (IS_ERR(pdb->dfa)) {
1005 		error = PTR_ERR(pdb->dfa);
1006 		pdb->dfa = NULL;
1007 		*info = "failed to unpack - dfa";
1008 		goto fail;
1009 	} else if (!pdb->dfa) {
1010 		if (required_dfa) {
1011 			*info = "missing required dfa";
1012 			goto fail;
1013 		}
1014 	} else {
1015 		/*
1016 		 * only unpack the following if a dfa is present
1017 		 *
1018 		 * sadly start was given different names for file and policydb
1019 		 * but since it is optional we can try both
1020 		 */
1021 		if (!aa_unpack_u32(e, &pdb->start[0], "start"))
1022 			/* default start state */
1023 			pdb->start[0] = DFA_START;
1024 		if (!aa_unpack_u32(e, &pdb->start[AA_CLASS_FILE], "dfa_start")) {
1025 			/* default start state for xmatch and file dfa */
1026 			pdb->start[AA_CLASS_FILE] = DFA_START;
1027 		}
1028 
1029 		size_t state_count = pdb->dfa->tables[YYTD_ID_BASE]->td_lolen;
1030 
1031 		if (pdb->start[0] >= state_count ||
1032 		    pdb->start[AA_CLASS_FILE] >= state_count) {
1033 			*info = "invalid dfa start state";
1034 			goto fail;
1035 		}
1036 
1037 		/* setup class index */
1038 		for (i = AA_CLASS_FILE + 1; i <= AA_CLASS_LAST; i++) {
1039 			pdb->start[i] = aa_dfa_next(pdb->dfa, pdb->start[0],
1040 						    i);
1041 		}
1042 	}
1043 
1044 	/* accept2 is in some cases being allocated, even with perms */
1045 	if (pdb->perms && !pdb->dfa->tables[YYTD_ID_ACCEPT2]) {
1046 		/* add dfa flags table missing in v2 */
1047 		u32 noents = pdb->dfa->tables[YYTD_ID_ACCEPT]->td_lolen;
1048 		u16 tdflags = pdb->dfa->tables[YYTD_ID_ACCEPT]->td_flags;
1049 		size_t tsize = table_size(noents, tdflags);
1050 
1051 		pdb->dfa->tables[YYTD_ID_ACCEPT2] = kvzalloc(tsize, GFP_KERNEL);
1052 		if (!pdb->dfa->tables[YYTD_ID_ACCEPT2]) {
1053 			*info = "failed to alloc dfa flags table";
1054 			goto out;
1055 		}
1056 		pdb->dfa->tables[YYTD_ID_ACCEPT2]->td_lolen = noents;
1057 		pdb->dfa->tables[YYTD_ID_ACCEPT2]->td_flags = tdflags;
1058 	}
1059 	/*
1060 	 * Unfortunately due to a bug in earlier userspaces, a
1061 	 * transition table may be present even when the dfa is
1062 	 * not. For compatibility reasons unpack and discard.
1063 	 */
1064 	error = unpack_strs_table(e, "xtable", false, &pdb->trans);
1065 	if (error && required_trans) {
1066 		*info = "failed to unpack profile transition table";
1067 		goto fail;
1068 	}
1069 
1070 	if (!pdb->dfa && pdb->trans.table)
1071 		aa_destroy_str_table(&pdb->trans);
1072 
1073 	/* TODO:
1074 	 * - move compat mapping here, requires dfa merging first
1075 	 * - move verify here, it has to be done after compat mappings
1076 	 * - move free of unneeded trans table here, has to be done
1077 	 *   after perm mapping.
1078 	 */
1079 out:
1080 	*policy = pdb;
1081 	return 0;
1082 
1083 fail:
1084 	aa_put_pdb(pdb);
1085 	e->pos = pos;
1086 	return error;
1087 }
1088 
1089 static u32 strhash(const void *data, u32 len, u32 seed)
1090 {
1091 	const char * const *key = data;
1092 
1093 	return jhash(*key, strlen(*key), seed);
1094 }
1095 
1096 static int datacmp(struct rhashtable_compare_arg *arg, const void *obj)
1097 {
1098 	const struct aa_data *data = obj;
1099 	const char * const *key = arg->key;
1100 
1101 	return strcmp(data->key, *key);
1102 }
1103 
1104 /**
1105  * unpack_profile - unpack a serialized profile
1106  * @e: serialized data extent information (NOT NULL)
1107  * @ns_name: pointer of newly allocated copy of %NULL in case of error
1108  *
1109  * NOTE: unpack profile sets audit struct if there is a failure
1110  */
1111 static struct aa_profile *unpack_profile(struct aa_ext *e, char **ns_name)
1112 {
1113 	struct aa_ruleset *rules;
1114 	struct aa_profile *profile = NULL;
1115 	const char *tmpname, *tmpns = NULL, *name = NULL;
1116 	const char *info = "failed to unpack profile";
1117 	size_t ns_len;
1118 	struct rhashtable_params params = { 0 };
1119 	char *key = NULL, *disconnected = NULL;
1120 	struct aa_data *data;
1121 	int error = -EPROTO;
1122 	kernel_cap_t tmpcap;
1123 	u32 tmp;
1124 
1125 	*ns_name = NULL;
1126 
1127 	/* check that we have the right struct being passed */
1128 	if (!aa_unpack_nameX(e, AA_STRUCT, "profile"))
1129 		goto fail;
1130 	if (!aa_unpack_str(e, &name, NULL))
1131 		goto fail;
1132 	if (*name == '\0')
1133 		goto fail;
1134 
1135 	tmpname = aa_splitn_fqname(name, strlen(name), &tmpns, &ns_len);
1136 	if (tmpns) {
1137 		if (!tmpname) {
1138 			info = "empty profile name";
1139 			goto fail;
1140 		}
1141 		*ns_name = kstrndup(tmpns, ns_len, GFP_KERNEL);
1142 		if (!*ns_name) {
1143 			info = "out of memory";
1144 			error = -ENOMEM;
1145 			goto fail;
1146 		}
1147 		name = tmpname;
1148 	}
1149 
1150 	profile = aa_alloc_profile(name, NULL, GFP_KERNEL);
1151 	if (!profile) {
1152 		info = "out of memory";
1153 		error = -ENOMEM;
1154 		goto fail;
1155 	}
1156 	rules = profile->label.rules[0];
1157 
1158 	/* profile renaming is optional */
1159 	(void) aa_unpack_str(e, &profile->rename, "rename");
1160 
1161 	/* attachment string is optional */
1162 	(void) aa_unpack_str(e, &profile->attach.xmatch_str, "attach");
1163 
1164 	/* xmatch is optional and may be NULL */
1165 	error = unpack_pdb(e, &profile->attach.xmatch, false, false, &info);
1166 	if (error) {
1167 		info = "bad xmatch";
1168 		goto fail;
1169 	}
1170 
1171 	/* neither xmatch_len not xmatch_perms are optional if xmatch is set */
1172 	if (profile->attach.xmatch->dfa) {
1173 		if (!aa_unpack_u32(e, &tmp, NULL)) {
1174 			info = "missing xmatch len";
1175 			goto fail;
1176 		}
1177 		profile->attach.xmatch_len = tmp;
1178 		profile->attach.xmatch->start[AA_CLASS_XMATCH] = DFA_START;
1179 		if (!profile->attach.xmatch->perms) {
1180 			error = aa_compat_map_xmatch(profile->attach.xmatch);
1181 			if (error) {
1182 				info = "failed to convert xmatch permission table";
1183 				goto fail;
1184 			}
1185 		}
1186 	}
1187 
1188 	/* disconnected attachment string is optional */
1189 	(void) aa_unpack_strdup(e, &disconnected, "disconnected");
1190 	profile->disconnected = disconnected;
1191 
1192 	/* optional */
1193 	(void) aa_unpack_u32(e, &profile->signal, "kill");
1194 	if (profile->signal < 1 || profile->signal > MAXMAPPED_SIG) {
1195 		info = "profile kill.signal invalid value";
1196 		goto fail;
1197 	}
1198 	/* per profile debug flags (complain, audit) */
1199 	if (!aa_unpack_nameX(e, AA_STRUCT, "flags")) {
1200 		info = "profile missing flags";
1201 		goto fail;
1202 	}
1203 	info = "failed to unpack profile flags";
1204 	if (!aa_unpack_u32(e, &tmp, NULL))
1205 		goto fail;
1206 	if (tmp & PACKED_FLAG_HAT)
1207 		profile->label.flags |= FLAG_HAT;
1208 	if (tmp & PACKED_FLAG_DEBUG1)
1209 		profile->label.flags |= FLAG_DEBUG1;
1210 	if (tmp & PACKED_FLAG_DEBUG2)
1211 		profile->label.flags |= FLAG_DEBUG2;
1212 	if (!aa_unpack_u32(e, &tmp, NULL))
1213 		goto fail;
1214 	if (tmp == PACKED_MODE_COMPLAIN || (e->version & FORCE_COMPLAIN_FLAG)) {
1215 		profile->mode = APPARMOR_COMPLAIN;
1216 	} else if (tmp == PACKED_MODE_ENFORCE) {
1217 		profile->mode = APPARMOR_ENFORCE;
1218 	} else if (tmp == PACKED_MODE_KILL) {
1219 		profile->mode = APPARMOR_KILL;
1220 	} else if (tmp == PACKED_MODE_UNCONFINED) {
1221 		profile->mode = APPARMOR_UNCONFINED;
1222 		profile->label.flags |= FLAG_UNCONFINED;
1223 	} else if (tmp == PACKED_MODE_USER) {
1224 		profile->mode = APPARMOR_USER;
1225 	} else {
1226 		goto fail;
1227 	}
1228 	if (!aa_unpack_u32(e, &tmp, NULL))
1229 		goto fail;
1230 	if (tmp)
1231 		profile->audit = AUDIT_ALL;
1232 
1233 	if (!aa_unpack_nameX(e, AA_STRUCTEND, NULL))
1234 		goto fail;
1235 
1236 	/* path_flags is optional */
1237 	if (aa_unpack_u32(e, &profile->path_flags, "path_flags"))
1238 		profile->path_flags |= profile->label.flags &
1239 			PATH_MEDIATE_DELETED;
1240 	else
1241 		/* set a default value if path_flags field is not present */
1242 		profile->path_flags = PATH_MEDIATE_DELETED;
1243 
1244 	info = "failed to unpack profile capabilities";
1245 	if (!aa_unpack_cap_low(e, &rules->caps.allow, NULL))
1246 		goto fail;
1247 	if (!aa_unpack_cap_low(e, &rules->caps.audit, NULL))
1248 		goto fail;
1249 	if (!aa_unpack_cap_low(e, &rules->caps.quiet, NULL))
1250 		goto fail;
1251 	if (!aa_unpack_cap_low(e, &tmpcap, NULL))
1252 		goto fail;
1253 
1254 	info = "failed to unpack upper profile capabilities";
1255 	if (aa_unpack_nameX(e, AA_STRUCT, "caps64")) {
1256 		/* optional upper half of 64 bit caps */
1257 		if (!aa_unpack_cap_high(e, &rules->caps.allow, NULL))
1258 			goto fail;
1259 		if (!aa_unpack_cap_high(e, &rules->caps.audit, NULL))
1260 			goto fail;
1261 		if (!aa_unpack_cap_high(e, &rules->caps.quiet, NULL))
1262 			goto fail;
1263 		if (!aa_unpack_cap_high(e, &tmpcap, NULL))
1264 			goto fail;
1265 		if (!aa_unpack_nameX(e, AA_STRUCTEND, NULL))
1266 			goto fail;
1267 	}
1268 
1269 	info = "failed to unpack extended profile capabilities";
1270 	if (aa_unpack_nameX(e, AA_STRUCT, "capsx")) {
1271 		/* optional extended caps mediation mask */
1272 		if (!aa_unpack_cap_low(e, &rules->caps.extended, NULL))
1273 			goto fail;
1274 		if (!aa_unpack_cap_high(e, &rules->caps.extended, NULL))
1275 			goto fail;
1276 		if (!aa_unpack_nameX(e, AA_STRUCTEND, NULL))
1277 			goto fail;
1278 	}
1279 
1280 	if (!unpack_xattrs(e, profile)) {
1281 		info = "failed to unpack profile xattrs";
1282 		goto fail;
1283 	}
1284 
1285 	if (!unpack_rlimits(e, rules)) {
1286 		info = "failed to unpack profile rlimits";
1287 		goto fail;
1288 	}
1289 
1290 	if (!unpack_secmark(e, rules)) {
1291 		info = "failed to unpack profile secmark rules";
1292 		goto fail;
1293 	}
1294 
1295 	if (aa_unpack_nameX(e, AA_STRUCT, "policydb")) {
1296 		/* generic policy dfa - optional and may be NULL */
1297 		info = "failed to unpack policydb";
1298 		error = unpack_pdb(e, &rules->policy, true, false,
1299 				   &info);
1300 		if (error)
1301 			goto fail;
1302 		/* Fixup: drop when we get rid of start array */
1303 		if (aa_dfa_next(rules->policy->dfa, rules->policy->start[0],
1304 				AA_CLASS_FILE))
1305 			rules->policy->start[AA_CLASS_FILE] =
1306 			  aa_dfa_next(rules->policy->dfa,
1307 				      rules->policy->start[0],
1308 				      AA_CLASS_FILE);
1309 		if (!aa_unpack_nameX(e, AA_STRUCTEND, NULL))
1310 			goto fail;
1311 		if (!rules->policy->perms) {
1312 			error = aa_compat_map_policy(rules->policy,
1313 						     e->version);
1314 			if (error) {
1315 				info = "failed to remap policydb permission table";
1316 				goto fail;
1317 			}
1318 		}
1319 	} else {
1320 		rules->policy = aa_get_pdb(nullpdb);
1321 	}
1322 	/* get file rules */
1323 	error = unpack_pdb(e, &rules->file, false, true, &info);
1324 	if (error) {
1325 		goto fail;
1326 	} else if (rules->file->dfa) {
1327 		if (!rules->file->perms) {
1328 			AA_DEBUG(DEBUG_UNPACK, "compat mapping perms");
1329 			error = aa_compat_map_file(rules->file);
1330 			if (error) {
1331 				info = "failed to remap file permission table";
1332 				goto fail;
1333 			}
1334 		}
1335 	} else if (rules->policy->dfa &&
1336 		   rules->policy->start[AA_CLASS_FILE]) {
1337 		aa_put_pdb(rules->file);
1338 		rules->file = aa_get_pdb(rules->policy);
1339 	} else {
1340 		aa_put_pdb(rules->file);
1341 		rules->file = aa_get_pdb(nullpdb);
1342 	}
1343 	error = -EPROTO;
1344 	if (aa_unpack_nameX(e, AA_STRUCT, "data")) {
1345 		info = "out of memory";
1346 		profile->data = kzalloc_obj(*profile->data);
1347 		if (!profile->data) {
1348 			error = -ENOMEM;
1349 			goto fail;
1350 		}
1351 		params.nelem_hint = 3;
1352 		params.key_len = sizeof(void *);
1353 		params.key_offset = offsetof(struct aa_data, key);
1354 		params.head_offset = offsetof(struct aa_data, head);
1355 		params.hashfn = strhash;
1356 		params.obj_cmpfn = datacmp;
1357 
1358 		if (rhashtable_init(profile->data, &params)) {
1359 			info = "failed to init key, value hash table";
1360 			goto fail;
1361 		}
1362 
1363 		while (aa_unpack_strdup(e, &key, NULL)) {
1364 			data = kzalloc_obj(*data);
1365 			if (!data) {
1366 				kfree_sensitive(key);
1367 				error = -ENOMEM;
1368 				goto fail;
1369 			}
1370 
1371 			data->key = key;
1372 			data->size = aa_unpack_blob(e, &data->data, NULL);
1373 			data->data = kvmemdup(data->data, data->size, GFP_KERNEL);
1374 			if (data->size && !data->data) {
1375 				kfree_sensitive(data->key);
1376 				kfree_sensitive(data);
1377 				error = -ENOMEM;
1378 				goto fail;
1379 			}
1380 
1381 			if (rhashtable_insert_fast(profile->data, &data->head,
1382 						   profile->data->p)) {
1383 				kvfree_sensitive(data->data, data->size);
1384 				kfree_sensitive(data->key);
1385 				kfree_sensitive(data);
1386 				info = "failed to insert data to table";
1387 				goto fail;
1388 			}
1389 		}
1390 
1391 		if (!aa_unpack_nameX(e, AA_STRUCTEND, NULL)) {
1392 			info = "failed to unpack end of key, value data table";
1393 			goto fail;
1394 		}
1395 	}
1396 
1397 	if (!aa_unpack_nameX(e, AA_STRUCTEND, NULL)) {
1398 		info = "failed to unpack end of profile";
1399 		goto fail;
1400 	}
1401 
1402 	aa_compute_profile_mediates(profile);
1403 
1404 	return profile;
1405 
1406 fail:
1407 	if (error == 0)
1408 		/* default error covers most cases */
1409 		error = -EPROTO;
1410 	if (*ns_name) {
1411 		kfree(*ns_name);
1412 		*ns_name = NULL;
1413 	}
1414 	if (profile)
1415 		name = NULL;
1416 	else if (!name)
1417 		name = "unknown";
1418 	audit_iface(profile, NULL, name, info, e, error);
1419 	aa_free_profile(profile);
1420 
1421 	return ERR_PTR(error);
1422 }
1423 
1424 /**
1425  * verify_header - unpack serialized stream header
1426  * @e: serialized data read head (NOT NULL)
1427  * @required: whether the header is required or optional
1428  * @ns: Returns - namespace if one is specified else NULL (NOT NULL)
1429  *
1430  * Returns: error or 0 if header is good
1431  */
1432 static int verify_header(struct aa_ext *e, int required, const char **ns)
1433 {
1434 	int error = -EPROTONOSUPPORT;
1435 	const char *name = NULL;
1436 
1437 	/* get the interface version */
1438 	if (!aa_unpack_u32(e, &e->version, "version")) {
1439 		if (required) {
1440 			audit_iface(NULL, NULL, NULL, "invalid profile format",
1441 				    e, error);
1442 			return error;
1443 		}
1444 	}
1445 
1446 	/* Check that the interface version is currently supported.
1447 	 * if not specified use previous version
1448 	 * Mask off everything that is not kernel abi version
1449 	 */
1450 	if (VERSION_LT(e->version, v5) || VERSION_GT(e->version, v9)) {
1451 		audit_iface(NULL, NULL, NULL, "unsupported interface version",
1452 			    e, error);
1453 		return error;
1454 	}
1455 
1456 	/* read the namespace if present */
1457 	if (aa_unpack_str(e, &name, "namespace")) {
1458 		if (*name == '\0') {
1459 			audit_iface(NULL, NULL, NULL, "invalid namespace name",
1460 				    e, error);
1461 			return error;
1462 		}
1463 		if (*ns && strcmp(*ns, name)) {
1464 			audit_iface(NULL, NULL, NULL, "invalid ns change", e,
1465 				    error);
1466 		} else if (!*ns) {
1467 			*ns = kstrdup(name, GFP_KERNEL);
1468 			if (!*ns)
1469 				return -ENOMEM;
1470 		}
1471 	}
1472 
1473 	return 0;
1474 }
1475 
1476 /**
1477  * verify_dfa_accept_index - verify accept indexes are in range of perms table
1478  * @dfa: the dfa to check accept indexes are in range
1479  * @table_size: the permission table size the indexes should be within
1480  */
1481 static bool verify_dfa_accept_index(struct aa_dfa *dfa, int table_size)
1482 {
1483 	int i;
1484 	for (i = 0; i < dfa->tables[YYTD_ID_ACCEPT]->td_lolen; i++) {
1485 		if (ACCEPT_TABLE(dfa)[i] >= table_size)
1486 			return false;
1487 	}
1488 	return true;
1489 }
1490 
1491 static bool verify_perm(struct aa_perms *perm)
1492 {
1493 	/* TODO: allow option to just force the perms into a valid state */
1494 	if (perm->allow & perm->deny)
1495 		return false;
1496 	if (perm->subtree & ~perm->allow)
1497 		return false;
1498 	if (perm->cond & (perm->allow | perm->deny))
1499 		return false;
1500 	if (perm->kill & perm->allow)
1501 		return false;
1502 	if (perm->complain & (perm->allow | perm->deny))
1503 		return false;
1504 	if (perm->prompt & (perm->allow | perm->deny))
1505 		return false;
1506 	if (perm->complain & perm->prompt)
1507 		return false;
1508 	if (perm->hide & perm->allow)
1509 		return false;
1510 
1511 	return true;
1512 }
1513 
1514 static bool verify_perms(struct aa_policydb *pdb)
1515 {
1516 	int i;
1517 	int xidx, xmax = -1;
1518 
1519 	for (i = 0; i < pdb->size; i++) {
1520 		if (!verify_perm(&pdb->perms[i]))
1521 			return false;
1522 		/* verify indexes into str table */
1523 		if ((pdb->perms[i].xindex & AA_X_TYPE_MASK) == AA_X_TABLE) {
1524 			xidx = pdb->perms[i].xindex & AA_X_INDEX_MASK;
1525 			if (xidx >= pdb->trans.size)
1526 				return false;
1527 			if (xmax < xidx)
1528 				xmax = xidx;
1529 		}
1530 		if (pdb->perms[i].tag && pdb->perms[i].tag >= pdb->tags.sets.size)
1531 			return false;
1532 		if (pdb->perms[i].label &&
1533 		    pdb->perms[i].label >= pdb->trans.size)
1534 			return false;
1535 	}
1536 	/* deal with incorrectly constructed string tables */
1537 	if (xmax == -1) {
1538 		aa_destroy_str_table(&pdb->trans);
1539 	} else if (pdb->trans.size > xmax + 1) {
1540 		if (!aa_resize_str_table(&pdb->trans, xmax + 1, GFP_KERNEL))
1541 			return false;
1542 	}
1543 	return true;
1544 }
1545 
1546 /**
1547  * verify_profile - Do post unpack analysis to verify profile consistency
1548  * @profile: profile to verify (NOT NULL)
1549  *
1550  * Returns: 0 if passes verification else error
1551  *
1552  * This verification is post any unpack mapping or changes
1553  */
1554 static int verify_profile(struct aa_profile *profile)
1555 {
1556 	struct aa_ruleset *rules = profile->label.rules[0];
1557 
1558 	if (!rules)
1559 		return 0;
1560 
1561 	if (rules->file->dfa && !verify_dfa_accept_index(rules->file->dfa,
1562 							rules->file->size)) {
1563 		audit_iface(profile, NULL, NULL,
1564 			    "Unpack: file Invalid named transition", NULL,
1565 			    -EPROTO);
1566 		return -EPROTO;
1567 	}
1568 	if (rules->policy->dfa &&
1569 	    !verify_dfa_accept_index(rules->policy->dfa, rules->policy->size)) {
1570 		audit_iface(profile, NULL, NULL,
1571 			    "Unpack: policy Invalid named transition", NULL,
1572 			    -EPROTO);
1573 		return -EPROTO;
1574 	}
1575 
1576 	if (!verify_perms(rules->file)) {
1577 		audit_iface(profile, NULL, NULL,
1578 			    "Unpack: Invalid perm index", NULL, -EPROTO);
1579 		return -EPROTO;
1580 	}
1581 	if (!verify_perms(rules->policy)) {
1582 		audit_iface(profile, NULL, NULL,
1583 			    "Unpack: Invalid perm index", NULL, -EPROTO);
1584 		return -EPROTO;
1585 	}
1586 	if (!verify_perms(profile->attach.xmatch)) {
1587 		audit_iface(profile, NULL, NULL,
1588 			    "Unpack: Invalid perm index", NULL, -EPROTO);
1589 		return -EPROTO;
1590 	}
1591 
1592 	return 0;
1593 }
1594 
1595 void aa_load_ent_free(struct aa_load_ent *ent)
1596 {
1597 	if (ent) {
1598 		aa_put_profile(ent->rename);
1599 		aa_put_profile(ent->old);
1600 		aa_put_profile(ent->new);
1601 		kfree(ent->ns_name);
1602 		kfree_sensitive(ent);
1603 	}
1604 }
1605 
1606 struct aa_load_ent *aa_load_ent_alloc(void)
1607 {
1608 	struct aa_load_ent *ent = kzalloc_obj(*ent);
1609 	if (ent)
1610 		INIT_LIST_HEAD(&ent->list);
1611 	return ent;
1612 }
1613 
1614 static int compress_zstd(const char *src, size_t slen, char **dst, size_t *dlen)
1615 {
1616 #ifdef CONFIG_SECURITY_APPARMOR_EXPORT_BINARY
1617 	const zstd_parameters params =
1618 		zstd_get_params(aa_g_rawdata_compression_level, slen);
1619 	const size_t wksp_len = zstd_cctx_workspace_bound(&params.cParams);
1620 	void *wksp = NULL;
1621 	zstd_cctx *ctx = NULL;
1622 	size_t out_len = zstd_compress_bound(slen);
1623 	void *out = NULL;
1624 	int ret = 0;
1625 
1626 	out = kvzalloc(out_len, GFP_KERNEL);
1627 	if (!out) {
1628 		ret = -ENOMEM;
1629 		goto cleanup;
1630 	}
1631 
1632 	wksp = kvzalloc(wksp_len, GFP_KERNEL);
1633 	if (!wksp) {
1634 		ret = -ENOMEM;
1635 		goto cleanup;
1636 	}
1637 
1638 	ctx = zstd_init_cctx(wksp, wksp_len);
1639 	if (!ctx) {
1640 		ret = -EINVAL;
1641 		goto cleanup;
1642 	}
1643 
1644 	out_len = zstd_compress_cctx(ctx, out, out_len, src, slen, &params);
1645 	if (zstd_is_error(out_len) || out_len >= slen) {
1646 		ret = -EINVAL;
1647 		goto cleanup;
1648 	}
1649 
1650 	if (is_vmalloc_addr(out)) {
1651 		*dst = kvzalloc(out_len, GFP_KERNEL);
1652 		if (*dst) {
1653 			memcpy(*dst, out, out_len);
1654 			kvfree(out);
1655 			out = NULL;
1656 		}
1657 	} else {
1658 		/*
1659 		 * If the staging buffer was kmalloc'd, then using krealloc is
1660 		 * probably going to be faster. The destination buffer will
1661 		 * always be smaller, so it's just shrunk, avoiding a memcpy
1662 		 */
1663 		*dst = krealloc(out, out_len, GFP_KERNEL);
1664 	}
1665 
1666 	if (!*dst) {
1667 		ret = -ENOMEM;
1668 		goto cleanup;
1669 	}
1670 
1671 	*dlen = out_len;
1672 
1673 cleanup:
1674 	if (ret) {
1675 		kvfree(out);
1676 		*dst = NULL;
1677 	}
1678 
1679 	kvfree(wksp);
1680 	return ret;
1681 #else
1682 	*dlen = slen;
1683 	return 0;
1684 #endif
1685 }
1686 
1687 static int compress_loaddata(struct aa_loaddata *data)
1688 {
1689 	AA_BUG(data->compressed_size > 0);
1690 
1691 	/*
1692 	 * Shortcut the no compression case, else we increase the amount of
1693 	 * storage required by a small amount
1694 	 */
1695 	if (aa_g_rawdata_compression_level != 0) {
1696 		void *udata = data->data;
1697 		int error = compress_zstd(udata, data->size, &data->data,
1698 					  &data->compressed_size);
1699 		if (error) {
1700 			data->compressed_size = data->size;
1701 			return error;
1702 		}
1703 		if (udata != data->data)
1704 			kvfree(udata);
1705 	} else
1706 		data->compressed_size = data->size;
1707 
1708 	return 0;
1709 }
1710 
1711 /**
1712  * aa_unpack - unpack packed binary profile(s) data loaded from user space
1713  * @udata: user data copied to kmem  (NOT NULL)
1714  * @lh: list to place unpacked profiles in a aa_repl_ws
1715  * @ns: Returns namespace profile is in if specified else NULL (NOT NULL)
1716  *
1717  * Unpack user data and return refcounted allocated profile(s) stored in
1718  * @lh in order of discovery, with the list chain stored in base.list
1719  * or error
1720  *
1721  * Returns: profile(s) on @lh else error pointer if fails to unpack
1722  */
1723 int aa_unpack(struct aa_loaddata *udata, struct list_head *lh,
1724 	      const char **ns)
1725 {
1726 	struct aa_load_ent *tmp, *ent;
1727 	struct aa_profile *profile = NULL;
1728 	char *ns_name = NULL;
1729 	int error;
1730 	struct aa_ext e = {
1731 		.start = udata->data,
1732 		.end = udata->data + udata->size,
1733 		.pos = udata->data,
1734 	};
1735 
1736 	*ns = NULL;
1737 	while (e.pos < e.end) {
1738 		void *start;
1739 		error = verify_header(&e, e.pos == e.start, ns);
1740 		if (error)
1741 			goto fail;
1742 
1743 		start = e.pos;
1744 		profile = unpack_profile(&e, &ns_name);
1745 		if (IS_ERR(profile)) {
1746 			error = PTR_ERR(profile);
1747 			goto fail;
1748 		}
1749 
1750 		error = verify_profile(profile);
1751 		if (error)
1752 			goto fail_profile;
1753 
1754 		if (aa_g_hash_policy)
1755 			error = aa_calc_profile_hash(profile, e.version, start,
1756 						     e.pos - start);
1757 		if (error)
1758 			goto fail_profile;
1759 
1760 		ent = aa_load_ent_alloc();
1761 		if (!ent) {
1762 			error = -ENOMEM;
1763 			goto fail_profile;
1764 		}
1765 
1766 		ent->new = profile;
1767 		ent->ns_name = ns_name;
1768 		ns_name = NULL;
1769 		list_add_tail(&ent->list, lh);
1770 	}
1771 	udata->abi = e.version & K_ABI_MASK;
1772 	if (aa_g_hash_policy) {
1773 		udata->hash = aa_calc_hash(udata->data, udata->size);
1774 		if (IS_ERR(udata->hash)) {
1775 			error = PTR_ERR(udata->hash);
1776 			udata->hash = NULL;
1777 			goto fail;
1778 		}
1779 	}
1780 
1781 	if (aa_g_export_binary) {
1782 		error = compress_loaddata(udata);
1783 		if (error)
1784 			goto fail;
1785 	}
1786 	return 0;
1787 
1788 fail_profile:
1789 	kfree(ns_name);
1790 	aa_put_profile(profile);
1791 
1792 fail:
1793 	list_for_each_entry_safe(ent, tmp, lh, list) {
1794 		list_del_init(&ent->list);
1795 		aa_load_ent_free(ent);
1796 	}
1797 
1798 	return error;
1799 }
1800