xref: /linux/security/apparmor/policy_unpack.c (revision caa9f579ca7255e9d6c25f072447d895c5928c97)
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 <asm/unaligned.h>
17 #include <linux/ctype.h>
18 #include <linux/errno.h>
19 #include <linux/zstd.h>
20 
21 #include "include/apparmor.h"
22 #include "include/audit.h"
23 #include "include/cred.h"
24 #include "include/crypto.h"
25 #include "include/file.h"
26 #include "include/match.h"
27 #include "include/path.h"
28 #include "include/policy.h"
29 #include "include/policy_unpack.h"
30 #include "include/policy_compat.h"
31 
32 
33 /*
34  * The AppArmor interface treats data as a type byte followed by the
35  * actual data.  The interface has the notion of a named entry
36  * which has a name (AA_NAME typecode followed by name string) followed by
37  * the entries typecode and data.  Named types allow for optional
38  * elements and extensions to be added and tested for without breaking
39  * backwards compatibility.
40  */
41 
42 enum aa_code {
43 	AA_U8,
44 	AA_U16,
45 	AA_U32,
46 	AA_U64,
47 	AA_NAME,		/* same as string except it is items name */
48 	AA_STRING,
49 	AA_BLOB,
50 	AA_STRUCT,
51 	AA_STRUCTEND,
52 	AA_LIST,
53 	AA_LISTEND,
54 	AA_ARRAY,
55 	AA_ARRAYEND,
56 };
57 
58 /*
59  * aa_ext is the read of the buffer containing the serialized profile.  The
60  * data is copied into a kernel buffer in apparmorfs and then handed off to
61  * the unpack routines.
62  */
63 struct aa_ext {
64 	void *start;
65 	void *end;
66 	void *pos;		/* pointer to current position in the buffer */
67 	u32 version;
68 };
69 
70 /* audit callback for unpack fields */
71 static void audit_cb(struct audit_buffer *ab, void *va)
72 {
73 	struct common_audit_data *sa = va;
74 
75 	if (aad(sa)->iface.ns) {
76 		audit_log_format(ab, " ns=");
77 		audit_log_untrustedstring(ab, aad(sa)->iface.ns);
78 	}
79 	if (aad(sa)->name) {
80 		audit_log_format(ab, " name=");
81 		audit_log_untrustedstring(ab, aad(sa)->name);
82 	}
83 	if (aad(sa)->iface.pos)
84 		audit_log_format(ab, " offset=%ld", aad(sa)->iface.pos);
85 }
86 
87 /**
88  * audit_iface - do audit message for policy unpacking/load/replace/remove
89  * @new: profile if it has been allocated (MAYBE NULL)
90  * @ns_name: name of the ns the profile is to be loaded to (MAY BE NULL)
91  * @name: name of the profile being manipulated (MAYBE NULL)
92  * @info: any extra info about the failure (MAYBE NULL)
93  * @e: buffer position info
94  * @error: error code
95  *
96  * Returns: %0 or error
97  */
98 static int audit_iface(struct aa_profile *new, const char *ns_name,
99 		       const char *name, const char *info, struct aa_ext *e,
100 		       int error)
101 {
102 	struct aa_profile *profile = labels_profile(aa_current_raw_label());
103 	DEFINE_AUDIT_DATA(sa, LSM_AUDIT_DATA_NONE, NULL);
104 	if (e)
105 		aad(&sa)->iface.pos = e->pos - e->start;
106 	aad(&sa)->iface.ns = ns_name;
107 	if (new)
108 		aad(&sa)->name = new->base.hname;
109 	else
110 		aad(&sa)->name = name;
111 	aad(&sa)->info = info;
112 	aad(&sa)->error = error;
113 
114 	return aa_audit(AUDIT_APPARMOR_STATUS, profile, &sa, audit_cb);
115 }
116 
117 void __aa_loaddata_update(struct aa_loaddata *data, long revision)
118 {
119 	AA_BUG(!data);
120 	AA_BUG(!data->ns);
121 	AA_BUG(!mutex_is_locked(&data->ns->lock));
122 	AA_BUG(data->revision > revision);
123 
124 	data->revision = revision;
125 	if ((data->dents[AAFS_LOADDATA_REVISION])) {
126 		d_inode(data->dents[AAFS_LOADDATA_DIR])->i_mtime =
127 			current_time(d_inode(data->dents[AAFS_LOADDATA_DIR]));
128 		d_inode(data->dents[AAFS_LOADDATA_REVISION])->i_mtime =
129 			current_time(d_inode(data->dents[AAFS_LOADDATA_REVISION]));
130 	}
131 }
132 
133 bool aa_rawdata_eq(struct aa_loaddata *l, struct aa_loaddata *r)
134 {
135 	if (l->size != r->size)
136 		return false;
137 	if (l->compressed_size != r->compressed_size)
138 		return false;
139 	if (aa_g_hash_policy && memcmp(l->hash, r->hash, aa_hash_size()) != 0)
140 		return false;
141 	return memcmp(l->data, r->data, r->compressed_size ?: r->size) == 0;
142 }
143 
144 /*
145  * need to take the ns mutex lock which is NOT safe most places that
146  * put_loaddata is called, so we have to delay freeing it
147  */
148 static void do_loaddata_free(struct work_struct *work)
149 {
150 	struct aa_loaddata *d = container_of(work, struct aa_loaddata, work);
151 	struct aa_ns *ns = aa_get_ns(d->ns);
152 
153 	if (ns) {
154 		mutex_lock_nested(&ns->lock, ns->level);
155 		__aa_fs_remove_rawdata(d);
156 		mutex_unlock(&ns->lock);
157 		aa_put_ns(ns);
158 	}
159 
160 	kfree_sensitive(d->hash);
161 	kfree_sensitive(d->name);
162 	kvfree(d->data);
163 	kfree_sensitive(d);
164 }
165 
166 void aa_loaddata_kref(struct kref *kref)
167 {
168 	struct aa_loaddata *d = container_of(kref, struct aa_loaddata, count);
169 
170 	if (d) {
171 		INIT_WORK(&d->work, do_loaddata_free);
172 		schedule_work(&d->work);
173 	}
174 }
175 
176 struct aa_loaddata *aa_loaddata_alloc(size_t size)
177 {
178 	struct aa_loaddata *d;
179 
180 	d = kzalloc(sizeof(*d), GFP_KERNEL);
181 	if (d == NULL)
182 		return ERR_PTR(-ENOMEM);
183 	d->data = kvzalloc(size, GFP_KERNEL);
184 	if (!d->data) {
185 		kfree(d);
186 		return ERR_PTR(-ENOMEM);
187 	}
188 	kref_init(&d->count);
189 	INIT_LIST_HEAD(&d->list);
190 
191 	return d;
192 }
193 
194 /* test if read will be in packed data bounds */
195 static bool inbounds(struct aa_ext *e, size_t size)
196 {
197 	return (size <= e->end - e->pos);
198 }
199 
200 static void *kvmemdup(const void *src, size_t len)
201 {
202 	void *p = kvmalloc(len, GFP_KERNEL);
203 
204 	if (p)
205 		memcpy(p, src, len);
206 	return p;
207 }
208 
209 /**
210  * unpack_u16_chunk - test and do bounds checking for a u16 size based chunk
211  * @e: serialized data read head (NOT NULL)
212  * @chunk: start address for chunk of data (NOT NULL)
213  *
214  * Returns: the size of chunk found with the read head at the end of the chunk.
215  */
216 static size_t unpack_u16_chunk(struct aa_ext *e, char **chunk)
217 {
218 	size_t size = 0;
219 	void *pos = e->pos;
220 
221 	if (!inbounds(e, sizeof(u16)))
222 		goto fail;
223 	size = le16_to_cpu(get_unaligned((__le16 *) e->pos));
224 	e->pos += sizeof(__le16);
225 	if (!inbounds(e, size))
226 		goto fail;
227 	*chunk = e->pos;
228 	e->pos += size;
229 	return size;
230 
231 fail:
232 	e->pos = pos;
233 	return 0;
234 }
235 
236 /* unpack control byte */
237 static bool unpack_X(struct aa_ext *e, enum aa_code code)
238 {
239 	if (!inbounds(e, 1))
240 		return false;
241 	if (*(u8 *) e->pos != code)
242 		return false;
243 	e->pos++;
244 	return true;
245 }
246 
247 /**
248  * unpack_nameX - check is the next element is of type X with a name of @name
249  * @e: serialized data extent information  (NOT NULL)
250  * @code: type code
251  * @name: name to match to the serialized element.  (MAYBE NULL)
252  *
253  * check that the next serialized data element is of type X and has a tag
254  * name @name.  If @name is specified then there must be a matching
255  * name element in the stream.  If @name is NULL any name element will be
256  * skipped and only the typecode will be tested.
257  *
258  * Returns true on success (both type code and name tests match) and the read
259  * head is advanced past the headers
260  *
261  * Returns: false if either match fails, the read head does not move
262  */
263 static bool unpack_nameX(struct aa_ext *e, enum aa_code code, const char *name)
264 {
265 	/*
266 	 * May need to reset pos if name or type doesn't match
267 	 */
268 	void *pos = e->pos;
269 	/*
270 	 * Check for presence of a tagname, and if present name size
271 	 * AA_NAME tag value is a u16.
272 	 */
273 	if (unpack_X(e, AA_NAME)) {
274 		char *tag = NULL;
275 		size_t size = unpack_u16_chunk(e, &tag);
276 		/* if a name is specified it must match. otherwise skip tag */
277 		if (name && (!size || tag[size-1] != '\0' || strcmp(name, tag)))
278 			goto fail;
279 	} else if (name) {
280 		/* if a name is specified and there is no name tag fail */
281 		goto fail;
282 	}
283 
284 	/* now check if type code matches */
285 	if (unpack_X(e, code))
286 		return true;
287 
288 fail:
289 	e->pos = pos;
290 	return false;
291 }
292 
293 static bool unpack_u8(struct aa_ext *e, u8 *data, const char *name)
294 {
295 	void *pos = e->pos;
296 
297 	if (unpack_nameX(e, AA_U8, name)) {
298 		if (!inbounds(e, sizeof(u8)))
299 			goto fail;
300 		if (data)
301 			*data = *((u8 *)e->pos);
302 		e->pos += sizeof(u8);
303 		return true;
304 	}
305 
306 fail:
307 	e->pos = pos;
308 	return false;
309 }
310 
311 static bool unpack_u32(struct aa_ext *e, u32 *data, const char *name)
312 {
313 	void *pos = e->pos;
314 
315 	if (unpack_nameX(e, AA_U32, name)) {
316 		if (!inbounds(e, sizeof(u32)))
317 			goto fail;
318 		if (data)
319 			*data = le32_to_cpu(get_unaligned((__le32 *) e->pos));
320 		e->pos += sizeof(u32);
321 		return true;
322 	}
323 
324 fail:
325 	e->pos = pos;
326 	return false;
327 }
328 
329 static bool unpack_u64(struct aa_ext *e, u64 *data, const char *name)
330 {
331 	void *pos = e->pos;
332 
333 	if (unpack_nameX(e, AA_U64, name)) {
334 		if (!inbounds(e, sizeof(u64)))
335 			goto fail;
336 		if (data)
337 			*data = le64_to_cpu(get_unaligned((__le64 *) e->pos));
338 		e->pos += sizeof(u64);
339 		return true;
340 	}
341 
342 fail:
343 	e->pos = pos;
344 	return false;
345 }
346 
347 static size_t unpack_array(struct aa_ext *e, const char *name)
348 {
349 	void *pos = e->pos;
350 
351 	if (unpack_nameX(e, AA_ARRAY, name)) {
352 		int size;
353 		if (!inbounds(e, sizeof(u16)))
354 			goto fail;
355 		size = (int)le16_to_cpu(get_unaligned((__le16 *) e->pos));
356 		e->pos += sizeof(u16);
357 		return size;
358 	}
359 
360 fail:
361 	e->pos = pos;
362 	return 0;
363 }
364 
365 static size_t unpack_blob(struct aa_ext *e, char **blob, const char *name)
366 {
367 	void *pos = e->pos;
368 
369 	if (unpack_nameX(e, AA_BLOB, name)) {
370 		u32 size;
371 		if (!inbounds(e, sizeof(u32)))
372 			goto fail;
373 		size = le32_to_cpu(get_unaligned((__le32 *) e->pos));
374 		e->pos += sizeof(u32);
375 		if (inbounds(e, (size_t) size)) {
376 			*blob = e->pos;
377 			e->pos += size;
378 			return size;
379 		}
380 	}
381 
382 fail:
383 	e->pos = pos;
384 	return 0;
385 }
386 
387 static int 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 (unpack_nameX(e, AA_STRING, name)) {
394 		size = 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 
410 static int unpack_strdup(struct aa_ext *e, char **string, const char *name)
411 {
412 	const char *tmp;
413 	void *pos = e->pos;
414 	int res = unpack_str(e, &tmp, name);
415 	*string = NULL;
416 
417 	if (!res)
418 		return 0;
419 
420 	*string = kmemdup(tmp, res, GFP_KERNEL);
421 	if (!*string) {
422 		e->pos = pos;
423 		return 0;
424 	}
425 
426 	return res;
427 }
428 
429 
430 /**
431  * unpack_dfa - unpack a file rule dfa
432  * @e: serialized data extent information (NOT NULL)
433  *
434  * returns dfa or ERR_PTR or NULL if no dfa
435  */
436 static struct aa_dfa *unpack_dfa(struct aa_ext *e)
437 {
438 	char *blob = NULL;
439 	size_t size;
440 	struct aa_dfa *dfa = NULL;
441 
442 	size = unpack_blob(e, &blob, "aadfa");
443 	if (size) {
444 		/*
445 		 * The dfa is aligned with in the blob to 8 bytes
446 		 * from the beginning of the stream.
447 		 * alignment adjust needed by dfa unpack
448 		 */
449 		size_t sz = blob - (char *) e->start -
450 			((e->pos - e->start) & 7);
451 		size_t pad = ALIGN(sz, 8) - sz;
452 		int flags = TO_ACCEPT1_FLAG(YYTD_DATA32) |
453 			TO_ACCEPT2_FLAG(YYTD_DATA32);
454 		if (aa_g_paranoid_load)
455 			flags |= DFA_FLAG_VERIFY_STATES;
456 		dfa = aa_dfa_unpack(blob + pad, size - pad, flags);
457 
458 		if (IS_ERR(dfa))
459 			return dfa;
460 
461 	}
462 
463 	return dfa;
464 }
465 
466 /**
467  * unpack_trans_table - unpack a profile transition table
468  * @e: serialized data extent information  (NOT NULL)
469  * @profile: profile to add the accept table to (NOT NULL)
470  *
471  * Returns: true if table successfully unpacked
472  */
473 static bool unpack_trans_table(struct aa_ext *e, struct aa_profile *profile)
474 {
475 	void *saved_pos = e->pos;
476 
477 	/* exec table is optional */
478 	if (unpack_nameX(e, AA_STRUCT, "xtable")) {
479 		int i, size;
480 
481 		size = unpack_array(e, NULL);
482 		/* currently 2^24 bits entries 0-3 */
483 		if (size > (1 << 24))
484 			goto fail;
485 		profile->file.trans.table = kcalloc(size, sizeof(char *),
486 						    GFP_KERNEL);
487 		if (!profile->file.trans.table)
488 			goto fail;
489 
490 		profile->file.trans.size = size;
491 		for (i = 0; i < size; i++) {
492 			char *str;
493 			int c, j, pos, size2 = unpack_strdup(e, &str, NULL);
494 			/* unpack_strdup verifies that the last character is
495 			 * null termination byte.
496 			 */
497 			if (!size2)
498 				goto fail;
499 			profile->file.trans.table[i] = str;
500 			/* verify that name doesn't start with space */
501 			if (isspace(*str))
502 				goto fail;
503 
504 			/* count internal #  of internal \0 */
505 			for (c = j = 0; j < size2 - 1; j++) {
506 				if (!str[j]) {
507 					pos = j;
508 					c++;
509 				}
510 			}
511 			if (*str == ':') {
512 				/* first character after : must be valid */
513 				if (!str[1])
514 					goto fail;
515 				/* beginning with : requires an embedded \0,
516 				 * verify that exactly 1 internal \0 exists
517 				 * trailing \0 already verified by unpack_strdup
518 				 *
519 				 * convert \0 back to : for label_parse
520 				 */
521 				if (c == 1)
522 					str[pos] = ':';
523 				else if (c > 1)
524 					goto fail;
525 			} else if (c)
526 				/* fail - all other cases with embedded \0 */
527 				goto fail;
528 		}
529 		if (!unpack_nameX(e, AA_ARRAYEND, NULL))
530 			goto fail;
531 		if (!unpack_nameX(e, AA_STRUCTEND, NULL))
532 			goto fail;
533 	}
534 	return true;
535 
536 fail:
537 	aa_free_domain_entries(&profile->file.trans);
538 	e->pos = saved_pos;
539 	return false;
540 }
541 
542 static bool unpack_xattrs(struct aa_ext *e, struct aa_profile *profile)
543 {
544 	void *pos = e->pos;
545 
546 	if (unpack_nameX(e, AA_STRUCT, "xattrs")) {
547 		int i, size;
548 
549 		size = unpack_array(e, NULL);
550 		profile->xattr_count = size;
551 		profile->xattrs = kcalloc(size, sizeof(char *), GFP_KERNEL);
552 		if (!profile->xattrs)
553 			goto fail;
554 		for (i = 0; i < size; i++) {
555 			if (!unpack_strdup(e, &profile->xattrs[i], NULL))
556 				goto fail;
557 		}
558 		if (!unpack_nameX(e, AA_ARRAYEND, NULL))
559 			goto fail;
560 		if (!unpack_nameX(e, AA_STRUCTEND, NULL))
561 			goto fail;
562 	}
563 
564 	return true;
565 
566 fail:
567 	e->pos = pos;
568 	return false;
569 }
570 
571 static bool unpack_secmark(struct aa_ext *e, struct aa_profile *profile)
572 {
573 	void *pos = e->pos;
574 	int i, size;
575 
576 	if (unpack_nameX(e, AA_STRUCT, "secmark")) {
577 		size = unpack_array(e, NULL);
578 
579 		profile->secmark = kcalloc(size, sizeof(struct aa_secmark),
580 					   GFP_KERNEL);
581 		if (!profile->secmark)
582 			goto fail;
583 
584 		profile->secmark_count = size;
585 
586 		for (i = 0; i < size; i++) {
587 			if (!unpack_u8(e, &profile->secmark[i].audit, NULL))
588 				goto fail;
589 			if (!unpack_u8(e, &profile->secmark[i].deny, NULL))
590 				goto fail;
591 			if (!unpack_strdup(e, &profile->secmark[i].label, NULL))
592 				goto fail;
593 		}
594 		if (!unpack_nameX(e, AA_ARRAYEND, NULL))
595 			goto fail;
596 		if (!unpack_nameX(e, AA_STRUCTEND, NULL))
597 			goto fail;
598 	}
599 
600 	return true;
601 
602 fail:
603 	if (profile->secmark) {
604 		for (i = 0; i < size; i++)
605 			kfree(profile->secmark[i].label);
606 		kfree(profile->secmark);
607 		profile->secmark_count = 0;
608 		profile->secmark = NULL;
609 	}
610 
611 	e->pos = pos;
612 	return false;
613 }
614 
615 static bool unpack_rlimits(struct aa_ext *e, struct aa_profile *profile)
616 {
617 	void *pos = e->pos;
618 
619 	/* rlimits are optional */
620 	if (unpack_nameX(e, AA_STRUCT, "rlimits")) {
621 		int i, size;
622 		u32 tmp = 0;
623 		if (!unpack_u32(e, &tmp, NULL))
624 			goto fail;
625 		profile->rlimits.mask = tmp;
626 
627 		size = unpack_array(e, NULL);
628 		if (size > RLIM_NLIMITS)
629 			goto fail;
630 		for (i = 0; i < size; i++) {
631 			u64 tmp2 = 0;
632 			int a = aa_map_resource(i);
633 			if (!unpack_u64(e, &tmp2, NULL))
634 				goto fail;
635 			profile->rlimits.limits[a].rlim_max = tmp2;
636 		}
637 		if (!unpack_nameX(e, AA_ARRAYEND, NULL))
638 			goto fail;
639 		if (!unpack_nameX(e, AA_STRUCTEND, NULL))
640 			goto fail;
641 	}
642 	return true;
643 
644 fail:
645 	e->pos = pos;
646 	return false;
647 }
648 
649 static u32 strhash(const void *data, u32 len, u32 seed)
650 {
651 	const char * const *key = data;
652 
653 	return jhash(*key, strlen(*key), seed);
654 }
655 
656 static int datacmp(struct rhashtable_compare_arg *arg, const void *obj)
657 {
658 	const struct aa_data *data = obj;
659 	const char * const *key = arg->key;
660 
661 	return strcmp(data->key, *key);
662 }
663 
664 /**
665  * unpack_profile - unpack a serialized profile
666  * @e: serialized data extent information (NOT NULL)
667  * @ns_name: pointer of newly allocated copy of %NULL in case of error
668  *
669  * NOTE: unpack profile sets audit struct if there is a failure
670  */
671 static struct aa_profile *unpack_profile(struct aa_ext *e, char **ns_name)
672 {
673 	struct aa_profile *profile = NULL;
674 	const char *tmpname, *tmpns = NULL, *name = NULL;
675 	const char *info = "failed to unpack profile";
676 	size_t ns_len;
677 	struct rhashtable_params params = { 0 };
678 	char *key = NULL;
679 	struct aa_data *data;
680 	int i, error = -EPROTO;
681 	kernel_cap_t tmpcap;
682 	u32 tmp;
683 
684 	*ns_name = NULL;
685 
686 	/* check that we have the right struct being passed */
687 	if (!unpack_nameX(e, AA_STRUCT, "profile"))
688 		goto fail;
689 	if (!unpack_str(e, &name, NULL))
690 		goto fail;
691 	if (*name == '\0')
692 		goto fail;
693 
694 	tmpname = aa_splitn_fqname(name, strlen(name), &tmpns, &ns_len);
695 	if (tmpns) {
696 		*ns_name = kstrndup(tmpns, ns_len, GFP_KERNEL);
697 		if (!*ns_name) {
698 			info = "out of memory";
699 			goto fail;
700 		}
701 		name = tmpname;
702 	}
703 
704 	profile = aa_alloc_profile(name, NULL, GFP_KERNEL);
705 	if (!profile)
706 		return ERR_PTR(-ENOMEM);
707 
708 	/* profile renaming is optional */
709 	(void) unpack_str(e, &profile->rename, "rename");
710 
711 	/* attachment string is optional */
712 	(void) unpack_str(e, &profile->attach, "attach");
713 
714 	/* xmatch is optional and may be NULL */
715 	profile->xmatch.dfa = unpack_dfa(e);
716 	if (IS_ERR(profile->xmatch.dfa)) {
717 		error = PTR_ERR(profile->xmatch.dfa);
718 		profile->xmatch.dfa = NULL;
719 		info = "bad xmatch";
720 		goto fail;
721 	}
722 	/* neither xmatch_len not xmatch_perms are optional if xmatch is set */
723 	if (profile->xmatch.dfa) {
724 		if (!unpack_u32(e, &tmp, NULL)) {
725 			info = "missing xmatch len";
726 			goto fail;
727 		}
728 		profile->xmatch_len = tmp;
729 		profile->xmatch.start[AA_CLASS_XMATCH] = DFA_START;
730 		if (aa_compat_map_xmatch(&profile->xmatch)) {
731 			info = "failed to convert xmatch permission table";
732 			goto fail;
733 		}
734 	}
735 
736 	/* disconnected attachment string is optional */
737 	(void) unpack_str(e, &profile->disconnected, "disconnected");
738 
739 	/* per profile debug flags (complain, audit) */
740 	if (!unpack_nameX(e, AA_STRUCT, "flags")) {
741 		info = "profile missing flags";
742 		goto fail;
743 	}
744 	info = "failed to unpack profile flags";
745 	if (!unpack_u32(e, &tmp, NULL))
746 		goto fail;
747 	if (tmp & PACKED_FLAG_HAT)
748 		profile->label.flags |= FLAG_HAT;
749 	if (tmp & PACKED_FLAG_DEBUG1)
750 		profile->label.flags |= FLAG_DEBUG1;
751 	if (tmp & PACKED_FLAG_DEBUG2)
752 		profile->label.flags |= FLAG_DEBUG2;
753 	if (!unpack_u32(e, &tmp, NULL))
754 		goto fail;
755 	if (tmp == PACKED_MODE_COMPLAIN || (e->version & FORCE_COMPLAIN_FLAG)) {
756 		profile->mode = APPARMOR_COMPLAIN;
757 	} else if (tmp == PACKED_MODE_ENFORCE) {
758 		profile->mode = APPARMOR_ENFORCE;
759 	} else if (tmp == PACKED_MODE_KILL) {
760 		profile->mode = APPARMOR_KILL;
761 	} else if (tmp == PACKED_MODE_UNCONFINED) {
762 		profile->mode = APPARMOR_UNCONFINED;
763 		profile->label.flags |= FLAG_UNCONFINED;
764 	} else {
765 		goto fail;
766 	}
767 	if (!unpack_u32(e, &tmp, NULL))
768 		goto fail;
769 	if (tmp)
770 		profile->audit = AUDIT_ALL;
771 
772 	if (!unpack_nameX(e, AA_STRUCTEND, NULL))
773 		goto fail;
774 
775 	/* path_flags is optional */
776 	if (unpack_u32(e, &profile->path_flags, "path_flags"))
777 		profile->path_flags |= profile->label.flags &
778 			PATH_MEDIATE_DELETED;
779 	else
780 		/* set a default value if path_flags field is not present */
781 		profile->path_flags = PATH_MEDIATE_DELETED;
782 
783 	info = "failed to unpack profile capabilities";
784 	if (!unpack_u32(e, &(profile->caps.allow.cap[0]), NULL))
785 		goto fail;
786 	if (!unpack_u32(e, &(profile->caps.audit.cap[0]), NULL))
787 		goto fail;
788 	if (!unpack_u32(e, &(profile->caps.quiet.cap[0]), NULL))
789 		goto fail;
790 	if (!unpack_u32(e, &tmpcap.cap[0], NULL))
791 		goto fail;
792 
793 	info = "failed to unpack upper profile capabilities";
794 	if (unpack_nameX(e, AA_STRUCT, "caps64")) {
795 		/* optional upper half of 64 bit caps */
796 		if (!unpack_u32(e, &(profile->caps.allow.cap[1]), NULL))
797 			goto fail;
798 		if (!unpack_u32(e, &(profile->caps.audit.cap[1]), NULL))
799 			goto fail;
800 		if (!unpack_u32(e, &(profile->caps.quiet.cap[1]), NULL))
801 			goto fail;
802 		if (!unpack_u32(e, &(tmpcap.cap[1]), NULL))
803 			goto fail;
804 		if (!unpack_nameX(e, AA_STRUCTEND, NULL))
805 			goto fail;
806 	}
807 
808 	info = "failed to unpack extended profile capabilities";
809 	if (unpack_nameX(e, AA_STRUCT, "capsx")) {
810 		/* optional extended caps mediation mask */
811 		if (!unpack_u32(e, &(profile->caps.extended.cap[0]), NULL))
812 			goto fail;
813 		if (!unpack_u32(e, &(profile->caps.extended.cap[1]), NULL))
814 			goto fail;
815 		if (!unpack_nameX(e, AA_STRUCTEND, NULL))
816 			goto fail;
817 	}
818 
819 	if (!unpack_xattrs(e, profile)) {
820 		info = "failed to unpack profile xattrs";
821 		goto fail;
822 	}
823 
824 	if (!unpack_rlimits(e, profile)) {
825 		info = "failed to unpack profile rlimits";
826 		goto fail;
827 	}
828 
829 	if (!unpack_secmark(e, profile)) {
830 		info = "failed to unpack profile secmark rules";
831 		goto fail;
832 	}
833 
834 	if (unpack_nameX(e, AA_STRUCT, "policydb")) {
835 		/* generic policy dfa - optional and may be NULL */
836 		info = "failed to unpack policydb";
837 		profile->policy.dfa = unpack_dfa(e);
838 		if (IS_ERR(profile->policy.dfa)) {
839 			error = PTR_ERR(profile->policy.dfa);
840 			profile->policy.dfa = NULL;
841 			goto fail;
842 		} else if (!profile->policy.dfa) {
843 			error = -EPROTO;
844 			goto fail;
845 		}
846 		if (!unpack_u32(e, &profile->policy.start[0], "start"))
847 			/* default start state */
848 			profile->policy.start[0] = DFA_START;
849 		/* setup class index */
850 		for (i = AA_CLASS_FILE; i <= AA_CLASS_LAST; i++) {
851 			profile->policy.start[i] =
852 				aa_dfa_next(profile->policy.dfa,
853 					    profile->policy.start[0],
854 					    i);
855 		}
856 		if (!unpack_nameX(e, AA_STRUCTEND, NULL))
857 			goto fail;
858 		if (aa_compat_map_policy(&profile->policy, e->version)) {
859 			info = "failed to remap policydb permission table";
860 			goto fail;
861 		}
862 	} else
863 		profile->policy.dfa = aa_get_dfa(nulldfa);
864 
865 	/* get file rules */
866 	profile->file.dfa = unpack_dfa(e);
867 	if (IS_ERR(profile->file.dfa)) {
868 		error = PTR_ERR(profile->file.dfa);
869 		profile->file.dfa = NULL;
870 		info = "failed to unpack profile file rules";
871 		goto fail;
872 	} else if (profile->file.dfa) {
873 		if (!unpack_u32(e, &profile->file.start[AA_CLASS_FILE],
874 				"dfa_start"))
875 			/* default start state */
876 			profile->file.start[AA_CLASS_FILE] = DFA_START;
877 		if (aa_compat_map_file(&profile->file)) {
878 			info = "failed to remap file permission table";
879 			goto fail;
880 		}
881 		if (!unpack_trans_table(e, profile)) {
882 			info = "failed to unpack profile transition table";
883 			goto fail;
884 		}
885 	} else if (profile->policy.dfa &&
886 		   profile->policy.start[AA_CLASS_FILE]) {
887 		profile->file.dfa = aa_get_dfa(profile->policy.dfa);
888 		profile->file.start[AA_CLASS_FILE] = profile->policy.start[AA_CLASS_FILE];
889 	} else
890 		profile->file.dfa = aa_get_dfa(nulldfa);
891 
892 	if (unpack_nameX(e, AA_STRUCT, "data")) {
893 		info = "out of memory";
894 		profile->data = kzalloc(sizeof(*profile->data), GFP_KERNEL);
895 		if (!profile->data)
896 			goto fail;
897 
898 		params.nelem_hint = 3;
899 		params.key_len = sizeof(void *);
900 		params.key_offset = offsetof(struct aa_data, key);
901 		params.head_offset = offsetof(struct aa_data, head);
902 		params.hashfn = strhash;
903 		params.obj_cmpfn = datacmp;
904 
905 		if (rhashtable_init(profile->data, &params)) {
906 			info = "failed to init key, value hash table";
907 			goto fail;
908 		}
909 
910 		while (unpack_strdup(e, &key, NULL)) {
911 			data = kzalloc(sizeof(*data), GFP_KERNEL);
912 			if (!data) {
913 				kfree_sensitive(key);
914 				goto fail;
915 			}
916 
917 			data->key = key;
918 			data->size = unpack_blob(e, &data->data, NULL);
919 			data->data = kvmemdup(data->data, data->size);
920 			if (data->size && !data->data) {
921 				kfree_sensitive(data->key);
922 				kfree_sensitive(data);
923 				goto fail;
924 			}
925 
926 			rhashtable_insert_fast(profile->data, &data->head,
927 					       profile->data->p);
928 		}
929 
930 		if (!unpack_nameX(e, AA_STRUCTEND, NULL)) {
931 			info = "failed to unpack end of key, value data table";
932 			goto fail;
933 		}
934 	}
935 
936 	if (!unpack_nameX(e, AA_STRUCTEND, NULL)) {
937 		info = "failed to unpack end of profile";
938 		goto fail;
939 	}
940 
941 	return profile;
942 
943 fail:
944 	if (profile)
945 		name = NULL;
946 	else if (!name)
947 		name = "unknown";
948 	audit_iface(profile, NULL, name, info, e, error);
949 	aa_free_profile(profile);
950 
951 	return ERR_PTR(error);
952 }
953 
954 /**
955  * verify_header - unpack serialized stream header
956  * @e: serialized data read head (NOT NULL)
957  * @required: whether the header is required or optional
958  * @ns: Returns - namespace if one is specified else NULL (NOT NULL)
959  *
960  * Returns: error or 0 if header is good
961  */
962 static int verify_header(struct aa_ext *e, int required, const char **ns)
963 {
964 	int error = -EPROTONOSUPPORT;
965 	const char *name = NULL;
966 	*ns = NULL;
967 
968 	/* get the interface version */
969 	if (!unpack_u32(e, &e->version, "version")) {
970 		if (required) {
971 			audit_iface(NULL, NULL, NULL, "invalid profile format",
972 				    e, error);
973 			return error;
974 		}
975 	}
976 
977 	/* Check that the interface version is currently supported.
978 	 * if not specified use previous version
979 	 * Mask off everything that is not kernel abi version
980 	 */
981 	if (VERSION_LT(e->version, v5) || VERSION_GT(e->version, v9)) {
982 		audit_iface(NULL, NULL, NULL, "unsupported interface version",
983 			    e, error);
984 		return error;
985 	}
986 
987 	/* read the namespace if present */
988 	if (unpack_str(e, &name, "namespace")) {
989 		if (*name == '\0') {
990 			audit_iface(NULL, NULL, NULL, "invalid namespace name",
991 				    e, error);
992 			return error;
993 		}
994 		if (*ns && strcmp(*ns, name)) {
995 			audit_iface(NULL, NULL, NULL, "invalid ns change", e,
996 				    error);
997 		} else if (!*ns) {
998 			*ns = kstrdup(name, GFP_KERNEL);
999 			if (!*ns)
1000 				return -ENOMEM;
1001 		}
1002 	}
1003 
1004 	return 0;
1005 }
1006 
1007 static bool verify_xindex(int xindex, int table_size)
1008 {
1009 	int index, xtype;
1010 	xtype = xindex & AA_X_TYPE_MASK;
1011 	index = xindex & AA_X_INDEX_MASK;
1012 	if (xtype == AA_X_TABLE && index >= table_size)
1013 		return false;
1014 	return true;
1015 }
1016 
1017 /* verify dfa xindexes are in range of transition tables */
1018 static bool verify_dfa_xindex(struct aa_dfa *dfa, int table_size)
1019 {
1020 	int i;
1021 	for (i = 0; i < dfa->tables[YYTD_ID_ACCEPT]->td_lolen; i++) {
1022 		if (!verify_xindex(ACCEPT_TABLE(dfa)[i], table_size))
1023 			return false;
1024 	}
1025 	return true;
1026 }
1027 
1028 /**
1029  * verify_profile - Do post unpack analysis to verify profile consistency
1030  * @profile: profile to verify (NOT NULL)
1031  *
1032  * Returns: 0 if passes verification else error
1033  *
1034  * This verification is post any unpack mapping or changes
1035  */
1036 static int verify_profile(struct aa_profile *profile)
1037 {
1038 	if ((profile->file.dfa &&
1039 	     !verify_dfa_xindex(profile->file.dfa,
1040 				profile->file.trans.size)) ||
1041 	    (profile->policy.dfa &&
1042 	     !verify_dfa_xindex(profile->policy.dfa,
1043 				profile->policy.trans.size))) {
1044 		audit_iface(profile, NULL, NULL,
1045 			    "Unpack: Invalid named transition", NULL, -EPROTO);
1046 		return -EPROTO;
1047 	}
1048 
1049 	return 0;
1050 }
1051 
1052 void aa_load_ent_free(struct aa_load_ent *ent)
1053 {
1054 	if (ent) {
1055 		aa_put_profile(ent->rename);
1056 		aa_put_profile(ent->old);
1057 		aa_put_profile(ent->new);
1058 		kfree(ent->ns_name);
1059 		kfree_sensitive(ent);
1060 	}
1061 }
1062 
1063 struct aa_load_ent *aa_load_ent_alloc(void)
1064 {
1065 	struct aa_load_ent *ent = kzalloc(sizeof(*ent), GFP_KERNEL);
1066 	if (ent)
1067 		INIT_LIST_HEAD(&ent->list);
1068 	return ent;
1069 }
1070 
1071 static int compress_zstd(const char *src, size_t slen, char **dst, size_t *dlen)
1072 {
1073 #ifdef CONFIG_SECURITY_APPARMOR_EXPORT_BINARY
1074 	const zstd_parameters params =
1075 		zstd_get_params(aa_g_rawdata_compression_level, slen);
1076 	const size_t wksp_len = zstd_cctx_workspace_bound(&params.cParams);
1077 	void *wksp = NULL;
1078 	zstd_cctx *ctx = NULL;
1079 	size_t out_len = zstd_compress_bound(slen);
1080 	void *out = NULL;
1081 	int ret = 0;
1082 
1083 	out = kvzalloc(out_len, GFP_KERNEL);
1084 	if (!out) {
1085 		ret = -ENOMEM;
1086 		goto cleanup;
1087 	}
1088 
1089 	wksp = kvzalloc(wksp_len, GFP_KERNEL);
1090 	if (!wksp) {
1091 		ret = -ENOMEM;
1092 		goto cleanup;
1093 	}
1094 
1095 	ctx = zstd_init_cctx(wksp, wksp_len);
1096 	if (!ctx) {
1097 		ret = -EINVAL;
1098 		goto cleanup;
1099 	}
1100 
1101 	out_len = zstd_compress_cctx(ctx, out, out_len, src, slen, &params);
1102 	if (zstd_is_error(out_len)) {
1103 		ret = -EINVAL;
1104 		goto cleanup;
1105 	}
1106 
1107 	if (is_vmalloc_addr(out)) {
1108 		*dst = kvzalloc(out_len, GFP_KERNEL);
1109 		if (*dst) {
1110 			memcpy(*dst, out, out_len);
1111 			kvfree(out);
1112 			out = NULL;
1113 		}
1114 	} else {
1115 		/*
1116 		 * If the staging buffer was kmalloc'd, then using krealloc is
1117 		 * probably going to be faster. The destination buffer will
1118 		 * always be smaller, so it's just shrunk, avoiding a memcpy
1119 		 */
1120 		*dst = krealloc(out, out_len, GFP_KERNEL);
1121 	}
1122 
1123 	if (!*dst) {
1124 		ret = -ENOMEM;
1125 		goto cleanup;
1126 	}
1127 
1128 	*dlen = out_len;
1129 
1130 cleanup:
1131 	if (ret) {
1132 		kvfree(out);
1133 		*dst = NULL;
1134 	}
1135 
1136 	kvfree(wksp);
1137 	return ret;
1138 #else
1139 	*dlen = slen;
1140 	return 0;
1141 #endif
1142 }
1143 
1144 static int compress_loaddata(struct aa_loaddata *data)
1145 {
1146 	AA_BUG(data->compressed_size > 0);
1147 
1148 	/*
1149 	 * Shortcut the no compression case, else we increase the amount of
1150 	 * storage required by a small amount
1151 	 */
1152 	if (aa_g_rawdata_compression_level != 0) {
1153 		void *udata = data->data;
1154 		int error = compress_zstd(udata, data->size, &data->data,
1155 					  &data->compressed_size);
1156 		if (error)
1157 			return error;
1158 
1159 		if (udata != data->data)
1160 			kvfree(udata);
1161 	} else
1162 		data->compressed_size = data->size;
1163 
1164 	return 0;
1165 }
1166 
1167 /**
1168  * aa_unpack - unpack packed binary profile(s) data loaded from user space
1169  * @udata: user data copied to kmem  (NOT NULL)
1170  * @lh: list to place unpacked profiles in a aa_repl_ws
1171  * @ns: Returns namespace profile is in if specified else NULL (NOT NULL)
1172  *
1173  * Unpack user data and return refcounted allocated profile(s) stored in
1174  * @lh in order of discovery, with the list chain stored in base.list
1175  * or error
1176  *
1177  * Returns: profile(s) on @lh else error pointer if fails to unpack
1178  */
1179 int aa_unpack(struct aa_loaddata *udata, struct list_head *lh,
1180 	      const char **ns)
1181 {
1182 	struct aa_load_ent *tmp, *ent;
1183 	struct aa_profile *profile = NULL;
1184 	int error;
1185 	struct aa_ext e = {
1186 		.start = udata->data,
1187 		.end = udata->data + udata->size,
1188 		.pos = udata->data,
1189 	};
1190 
1191 	*ns = NULL;
1192 	while (e.pos < e.end) {
1193 		char *ns_name = NULL;
1194 		void *start;
1195 		error = verify_header(&e, e.pos == e.start, ns);
1196 		if (error)
1197 			goto fail;
1198 
1199 		start = e.pos;
1200 		profile = unpack_profile(&e, &ns_name);
1201 		if (IS_ERR(profile)) {
1202 			error = PTR_ERR(profile);
1203 			goto fail;
1204 		}
1205 
1206 		error = verify_profile(profile);
1207 		if (error)
1208 			goto fail_profile;
1209 
1210 		if (aa_g_hash_policy)
1211 			error = aa_calc_profile_hash(profile, e.version, start,
1212 						     e.pos - start);
1213 		if (error)
1214 			goto fail_profile;
1215 
1216 		ent = aa_load_ent_alloc();
1217 		if (!ent) {
1218 			error = -ENOMEM;
1219 			goto fail_profile;
1220 		}
1221 
1222 		ent->new = profile;
1223 		ent->ns_name = ns_name;
1224 		list_add_tail(&ent->list, lh);
1225 	}
1226 	udata->abi = e.version & K_ABI_MASK;
1227 	if (aa_g_hash_policy) {
1228 		udata->hash = aa_calc_hash(udata->data, udata->size);
1229 		if (IS_ERR(udata->hash)) {
1230 			error = PTR_ERR(udata->hash);
1231 			udata->hash = NULL;
1232 			goto fail;
1233 		}
1234 	}
1235 
1236 	if (aa_g_export_binary) {
1237 		error = compress_loaddata(udata);
1238 		if (error)
1239 			goto fail;
1240 	}
1241 	return 0;
1242 
1243 fail_profile:
1244 	aa_put_profile(profile);
1245 
1246 fail:
1247 	list_for_each_entry_safe(ent, tmp, lh, list) {
1248 		list_del_init(&ent->list);
1249 		aa_load_ent_free(ent);
1250 	}
1251 
1252 	return error;
1253 }
1254 
1255 #ifdef CONFIG_SECURITY_APPARMOR_KUNIT_TEST
1256 #include "policy_unpack_test.c"
1257 #endif /* CONFIG_SECURITY_APPARMOR_KUNIT_TEST */
1258