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