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