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