Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * AppArmor security module
0004  *
0005  * This file contains AppArmor functions for unpacking policy loaded from
0006  * userspace.
0007  *
0008  * Copyright (C) 1998-2008 Novell/SUSE
0009  * Copyright 2009-2010 Canonical Ltd.
0010  *
0011  * AppArmor uses a serialized binary format for loading policy. To find
0012  * policy format documentation see Documentation/admin-guide/LSM/apparmor.rst
0013  * All policy is validated before it is used.
0014  */
0015 
0016 #include <asm/unaligned.h>
0017 #include <linux/ctype.h>
0018 #include <linux/errno.h>
0019 #include <linux/zlib.h>
0020 
0021 #include "include/apparmor.h"
0022 #include "include/audit.h"
0023 #include "include/cred.h"
0024 #include "include/crypto.h"
0025 #include "include/match.h"
0026 #include "include/path.h"
0027 #include "include/policy.h"
0028 #include "include/policy_unpack.h"
0029 
0030 #define K_ABI_MASK 0x3ff
0031 #define FORCE_COMPLAIN_FLAG 0x800
0032 #define VERSION_LT(X, Y) (((X) & K_ABI_MASK) < ((Y) & K_ABI_MASK))
0033 #define VERSION_GT(X, Y) (((X) & K_ABI_MASK) > ((Y) & K_ABI_MASK))
0034 
0035 #define v5  5   /* base version */
0036 #define v6  6   /* per entry policydb mediation check */
0037 #define v7  7
0038 #define v8  8   /* full network masking */
0039 
0040 /*
0041  * The AppArmor interface treats data as a type byte followed by the
0042  * actual data.  The interface has the notion of a named entry
0043  * which has a name (AA_NAME typecode followed by name string) followed by
0044  * the entries typecode and data.  Named types allow for optional
0045  * elements and extensions to be added and tested for without breaking
0046  * backwards compatibility.
0047  */
0048 
0049 enum aa_code {
0050     AA_U8,
0051     AA_U16,
0052     AA_U32,
0053     AA_U64,
0054     AA_NAME,        /* same as string except it is items name */
0055     AA_STRING,
0056     AA_BLOB,
0057     AA_STRUCT,
0058     AA_STRUCTEND,
0059     AA_LIST,
0060     AA_LISTEND,
0061     AA_ARRAY,
0062     AA_ARRAYEND,
0063 };
0064 
0065 /*
0066  * aa_ext is the read of the buffer containing the serialized profile.  The
0067  * data is copied into a kernel buffer in apparmorfs and then handed off to
0068  * the unpack routines.
0069  */
0070 struct aa_ext {
0071     void *start;
0072     void *end;
0073     void *pos;      /* pointer to current position in the buffer */
0074     u32 version;
0075 };
0076 
0077 /* audit callback for unpack fields */
0078 static void audit_cb(struct audit_buffer *ab, void *va)
0079 {
0080     struct common_audit_data *sa = va;
0081 
0082     if (aad(sa)->iface.ns) {
0083         audit_log_format(ab, " ns=");
0084         audit_log_untrustedstring(ab, aad(sa)->iface.ns);
0085     }
0086     if (aad(sa)->name) {
0087         audit_log_format(ab, " name=");
0088         audit_log_untrustedstring(ab, aad(sa)->name);
0089     }
0090     if (aad(sa)->iface.pos)
0091         audit_log_format(ab, " offset=%ld", aad(sa)->iface.pos);
0092 }
0093 
0094 /**
0095  * audit_iface - do audit message for policy unpacking/load/replace/remove
0096  * @new: profile if it has been allocated (MAYBE NULL)
0097  * @ns_name: name of the ns the profile is to be loaded to (MAY BE NULL)
0098  * @name: name of the profile being manipulated (MAYBE NULL)
0099  * @info: any extra info about the failure (MAYBE NULL)
0100  * @e: buffer position info
0101  * @error: error code
0102  *
0103  * Returns: %0 or error
0104  */
0105 static int audit_iface(struct aa_profile *new, const char *ns_name,
0106                const char *name, const char *info, struct aa_ext *e,
0107                int error)
0108 {
0109     struct aa_profile *profile = labels_profile(aa_current_raw_label());
0110     DEFINE_AUDIT_DATA(sa, LSM_AUDIT_DATA_NONE, NULL);
0111     if (e)
0112         aad(&sa)->iface.pos = e->pos - e->start;
0113     aad(&sa)->iface.ns = ns_name;
0114     if (new)
0115         aad(&sa)->name = new->base.hname;
0116     else
0117         aad(&sa)->name = name;
0118     aad(&sa)->info = info;
0119     aad(&sa)->error = error;
0120 
0121     return aa_audit(AUDIT_APPARMOR_STATUS, profile, &sa, audit_cb);
0122 }
0123 
0124 void __aa_loaddata_update(struct aa_loaddata *data, long revision)
0125 {
0126     AA_BUG(!data);
0127     AA_BUG(!data->ns);
0128     AA_BUG(!mutex_is_locked(&data->ns->lock));
0129     AA_BUG(data->revision > revision);
0130 
0131     data->revision = revision;
0132     if ((data->dents[AAFS_LOADDATA_REVISION])) {
0133         d_inode(data->dents[AAFS_LOADDATA_DIR])->i_mtime =
0134             current_time(d_inode(data->dents[AAFS_LOADDATA_DIR]));
0135         d_inode(data->dents[AAFS_LOADDATA_REVISION])->i_mtime =
0136             current_time(d_inode(data->dents[AAFS_LOADDATA_REVISION]));
0137     }
0138 }
0139 
0140 bool aa_rawdata_eq(struct aa_loaddata *l, struct aa_loaddata *r)
0141 {
0142     if (l->size != r->size)
0143         return false;
0144     if (l->compressed_size != r->compressed_size)
0145         return false;
0146     if (aa_g_hash_policy && memcmp(l->hash, r->hash, aa_hash_size()) != 0)
0147         return false;
0148     return memcmp(l->data, r->data, r->compressed_size ?: r->size) == 0;
0149 }
0150 
0151 /*
0152  * need to take the ns mutex lock which is NOT safe most places that
0153  * put_loaddata is called, so we have to delay freeing it
0154  */
0155 static void do_loaddata_free(struct work_struct *work)
0156 {
0157     struct aa_loaddata *d = container_of(work, struct aa_loaddata, work);
0158     struct aa_ns *ns = aa_get_ns(d->ns);
0159 
0160     if (ns) {
0161         mutex_lock_nested(&ns->lock, ns->level);
0162         __aa_fs_remove_rawdata(d);
0163         mutex_unlock(&ns->lock);
0164         aa_put_ns(ns);
0165     }
0166 
0167     kfree_sensitive(d->hash);
0168     kfree_sensitive(d->name);
0169     kvfree(d->data);
0170     kfree_sensitive(d);
0171 }
0172 
0173 void aa_loaddata_kref(struct kref *kref)
0174 {
0175     struct aa_loaddata *d = container_of(kref, struct aa_loaddata, count);
0176 
0177     if (d) {
0178         INIT_WORK(&d->work, do_loaddata_free);
0179         schedule_work(&d->work);
0180     }
0181 }
0182 
0183 struct aa_loaddata *aa_loaddata_alloc(size_t size)
0184 {
0185     struct aa_loaddata *d;
0186 
0187     d = kzalloc(sizeof(*d), GFP_KERNEL);
0188     if (d == NULL)
0189         return ERR_PTR(-ENOMEM);
0190     d->data = kvzalloc(size, GFP_KERNEL);
0191     if (!d->data) {
0192         kfree(d);
0193         return ERR_PTR(-ENOMEM);
0194     }
0195     kref_init(&d->count);
0196     INIT_LIST_HEAD(&d->list);
0197 
0198     return d;
0199 }
0200 
0201 /* test if read will be in packed data bounds */
0202 static bool inbounds(struct aa_ext *e, size_t size)
0203 {
0204     return (size <= e->end - e->pos);
0205 }
0206 
0207 static void *kvmemdup(const void *src, size_t len)
0208 {
0209     void *p = kvmalloc(len, GFP_KERNEL);
0210 
0211     if (p)
0212         memcpy(p, src, len);
0213     return p;
0214 }
0215 
0216 /**
0217  * unpack_u16_chunk - test and do bounds checking for a u16 size based chunk
0218  * @e: serialized data read head (NOT NULL)
0219  * @chunk: start address for chunk of data (NOT NULL)
0220  *
0221  * Returns: the size of chunk found with the read head at the end of the chunk.
0222  */
0223 static size_t unpack_u16_chunk(struct aa_ext *e, char **chunk)
0224 {
0225     size_t size = 0;
0226     void *pos = e->pos;
0227 
0228     if (!inbounds(e, sizeof(u16)))
0229         goto fail;
0230     size = le16_to_cpu(get_unaligned((__le16 *) e->pos));
0231     e->pos += sizeof(__le16);
0232     if (!inbounds(e, size))
0233         goto fail;
0234     *chunk = e->pos;
0235     e->pos += size;
0236     return size;
0237 
0238 fail:
0239     e->pos = pos;
0240     return 0;
0241 }
0242 
0243 /* unpack control byte */
0244 static bool unpack_X(struct aa_ext *e, enum aa_code code)
0245 {
0246     if (!inbounds(e, 1))
0247         return false;
0248     if (*(u8 *) e->pos != code)
0249         return false;
0250     e->pos++;
0251     return true;
0252 }
0253 
0254 /**
0255  * unpack_nameX - check is the next element is of type X with a name of @name
0256  * @e: serialized data extent information  (NOT NULL)
0257  * @code: type code
0258  * @name: name to match to the serialized element.  (MAYBE NULL)
0259  *
0260  * check that the next serialized data element is of type X and has a tag
0261  * name @name.  If @name is specified then there must be a matching
0262  * name element in the stream.  If @name is NULL any name element will be
0263  * skipped and only the typecode will be tested.
0264  *
0265  * Returns true on success (both type code and name tests match) and the read
0266  * head is advanced past the headers
0267  *
0268  * Returns: false if either match fails, the read head does not move
0269  */
0270 static bool unpack_nameX(struct aa_ext *e, enum aa_code code, const char *name)
0271 {
0272     /*
0273      * May need to reset pos if name or type doesn't match
0274      */
0275     void *pos = e->pos;
0276     /*
0277      * Check for presence of a tagname, and if present name size
0278      * AA_NAME tag value is a u16.
0279      */
0280     if (unpack_X(e, AA_NAME)) {
0281         char *tag = NULL;
0282         size_t size = unpack_u16_chunk(e, &tag);
0283         /* if a name is specified it must match. otherwise skip tag */
0284         if (name && (!size || tag[size-1] != '\0' || strcmp(name, tag)))
0285             goto fail;
0286     } else if (name) {
0287         /* if a name is specified and there is no name tag fail */
0288         goto fail;
0289     }
0290 
0291     /* now check if type code matches */
0292     if (unpack_X(e, code))
0293         return true;
0294 
0295 fail:
0296     e->pos = pos;
0297     return false;
0298 }
0299 
0300 static bool unpack_u8(struct aa_ext *e, u8 *data, const char *name)
0301 {
0302     void *pos = e->pos;
0303 
0304     if (unpack_nameX(e, AA_U8, name)) {
0305         if (!inbounds(e, sizeof(u8)))
0306             goto fail;
0307         if (data)
0308             *data = *((u8 *)e->pos);
0309         e->pos += sizeof(u8);
0310         return true;
0311     }
0312 
0313 fail:
0314     e->pos = pos;
0315     return false;
0316 }
0317 
0318 static bool unpack_u32(struct aa_ext *e, u32 *data, const char *name)
0319 {
0320     void *pos = e->pos;
0321 
0322     if (unpack_nameX(e, AA_U32, name)) {
0323         if (!inbounds(e, sizeof(u32)))
0324             goto fail;
0325         if (data)
0326             *data = le32_to_cpu(get_unaligned((__le32 *) e->pos));
0327         e->pos += sizeof(u32);
0328         return true;
0329     }
0330 
0331 fail:
0332     e->pos = pos;
0333     return false;
0334 }
0335 
0336 static bool unpack_u64(struct aa_ext *e, u64 *data, const char *name)
0337 {
0338     void *pos = e->pos;
0339 
0340     if (unpack_nameX(e, AA_U64, name)) {
0341         if (!inbounds(e, sizeof(u64)))
0342             goto fail;
0343         if (data)
0344             *data = le64_to_cpu(get_unaligned((__le64 *) e->pos));
0345         e->pos += sizeof(u64);
0346         return true;
0347     }
0348 
0349 fail:
0350     e->pos = pos;
0351     return false;
0352 }
0353 
0354 static size_t unpack_array(struct aa_ext *e, const char *name)
0355 {
0356     void *pos = e->pos;
0357 
0358     if (unpack_nameX(e, AA_ARRAY, name)) {
0359         int size;
0360         if (!inbounds(e, sizeof(u16)))
0361             goto fail;
0362         size = (int)le16_to_cpu(get_unaligned((__le16 *) e->pos));
0363         e->pos += sizeof(u16);
0364         return size;
0365     }
0366 
0367 fail:
0368     e->pos = pos;
0369     return 0;
0370 }
0371 
0372 static size_t unpack_blob(struct aa_ext *e, char **blob, const char *name)
0373 {
0374     void *pos = e->pos;
0375 
0376     if (unpack_nameX(e, AA_BLOB, name)) {
0377         u32 size;
0378         if (!inbounds(e, sizeof(u32)))
0379             goto fail;
0380         size = le32_to_cpu(get_unaligned((__le32 *) e->pos));
0381         e->pos += sizeof(u32);
0382         if (inbounds(e, (size_t) size)) {
0383             *blob = e->pos;
0384             e->pos += size;
0385             return size;
0386         }
0387     }
0388 
0389 fail:
0390     e->pos = pos;
0391     return 0;
0392 }
0393 
0394 static int unpack_str(struct aa_ext *e, const char **string, const char *name)
0395 {
0396     char *src_str;
0397     size_t size = 0;
0398     void *pos = e->pos;
0399     *string = NULL;
0400     if (unpack_nameX(e, AA_STRING, name)) {
0401         size = unpack_u16_chunk(e, &src_str);
0402         if (size) {
0403             /* strings are null terminated, length is size - 1 */
0404             if (src_str[size - 1] != 0)
0405                 goto fail;
0406             *string = src_str;
0407 
0408             return size;
0409         }
0410     }
0411 
0412 fail:
0413     e->pos = pos;
0414     return 0;
0415 }
0416 
0417 static int unpack_strdup(struct aa_ext *e, char **string, const char *name)
0418 {
0419     const char *tmp;
0420     void *pos = e->pos;
0421     int res = unpack_str(e, &tmp, name);
0422     *string = NULL;
0423 
0424     if (!res)
0425         return 0;
0426 
0427     *string = kmemdup(tmp, res, GFP_KERNEL);
0428     if (!*string) {
0429         e->pos = pos;
0430         return 0;
0431     }
0432 
0433     return res;
0434 }
0435 
0436 
0437 /**
0438  * unpack_dfa - unpack a file rule dfa
0439  * @e: serialized data extent information (NOT NULL)
0440  *
0441  * returns dfa or ERR_PTR or NULL if no dfa
0442  */
0443 static struct aa_dfa *unpack_dfa(struct aa_ext *e)
0444 {
0445     char *blob = NULL;
0446     size_t size;
0447     struct aa_dfa *dfa = NULL;
0448 
0449     size = unpack_blob(e, &blob, "aadfa");
0450     if (size) {
0451         /*
0452          * The dfa is aligned with in the blob to 8 bytes
0453          * from the beginning of the stream.
0454          * alignment adjust needed by dfa unpack
0455          */
0456         size_t sz = blob - (char *) e->start -
0457             ((e->pos - e->start) & 7);
0458         size_t pad = ALIGN(sz, 8) - sz;
0459         int flags = TO_ACCEPT1_FLAG(YYTD_DATA32) |
0460             TO_ACCEPT2_FLAG(YYTD_DATA32);
0461         if (aa_g_paranoid_load)
0462             flags |= DFA_FLAG_VERIFY_STATES;
0463         dfa = aa_dfa_unpack(blob + pad, size - pad, flags);
0464 
0465         if (IS_ERR(dfa))
0466             return dfa;
0467 
0468     }
0469 
0470     return dfa;
0471 }
0472 
0473 /**
0474  * unpack_trans_table - unpack a profile transition table
0475  * @e: serialized data extent information  (NOT NULL)
0476  * @profile: profile to add the accept table to (NOT NULL)
0477  *
0478  * Returns: true if table successfully unpacked
0479  */
0480 static bool unpack_trans_table(struct aa_ext *e, struct aa_profile *profile)
0481 {
0482     void *saved_pos = e->pos;
0483 
0484     /* exec table is optional */
0485     if (unpack_nameX(e, AA_STRUCT, "xtable")) {
0486         int i, size;
0487 
0488         size = unpack_array(e, NULL);
0489         /* currently 4 exec bits and entries 0-3 are reserved iupcx */
0490         if (size > 16 - 4)
0491             goto fail;
0492         profile->file.trans.table = kcalloc(size, sizeof(char *),
0493                             GFP_KERNEL);
0494         if (!profile->file.trans.table)
0495             goto fail;
0496 
0497         profile->file.trans.size = size;
0498         for (i = 0; i < size; i++) {
0499             char *str;
0500             int c, j, pos, size2 = unpack_strdup(e, &str, NULL);
0501             /* unpack_strdup verifies that the last character is
0502              * null termination byte.
0503              */
0504             if (!size2)
0505                 goto fail;
0506             profile->file.trans.table[i] = str;
0507             /* verify that name doesn't start with space */
0508             if (isspace(*str))
0509                 goto fail;
0510 
0511             /* count internal #  of internal \0 */
0512             for (c = j = 0; j < size2 - 1; j++) {
0513                 if (!str[j]) {
0514                     pos = j;
0515                     c++;
0516                 }
0517             }
0518             if (*str == ':') {
0519                 /* first character after : must be valid */
0520                 if (!str[1])
0521                     goto fail;
0522                 /* beginning with : requires an embedded \0,
0523                  * verify that exactly 1 internal \0 exists
0524                  * trailing \0 already verified by unpack_strdup
0525                  *
0526                  * convert \0 back to : for label_parse
0527                  */
0528                 if (c == 1)
0529                     str[pos] = ':';
0530                 else if (c > 1)
0531                     goto fail;
0532             } else if (c)
0533                 /* fail - all other cases with embedded \0 */
0534                 goto fail;
0535         }
0536         if (!unpack_nameX(e, AA_ARRAYEND, NULL))
0537             goto fail;
0538         if (!unpack_nameX(e, AA_STRUCTEND, NULL))
0539             goto fail;
0540     }
0541     return true;
0542 
0543 fail:
0544     aa_free_domain_entries(&profile->file.trans);
0545     e->pos = saved_pos;
0546     return false;
0547 }
0548 
0549 static bool unpack_xattrs(struct aa_ext *e, struct aa_profile *profile)
0550 {
0551     void *pos = e->pos;
0552 
0553     if (unpack_nameX(e, AA_STRUCT, "xattrs")) {
0554         int i, size;
0555 
0556         size = unpack_array(e, NULL);
0557         profile->xattr_count = size;
0558         profile->xattrs = kcalloc(size, sizeof(char *), GFP_KERNEL);
0559         if (!profile->xattrs)
0560             goto fail;
0561         for (i = 0; i < size; i++) {
0562             if (!unpack_strdup(e, &profile->xattrs[i], NULL))
0563                 goto fail;
0564         }
0565         if (!unpack_nameX(e, AA_ARRAYEND, NULL))
0566             goto fail;
0567         if (!unpack_nameX(e, AA_STRUCTEND, NULL))
0568             goto fail;
0569     }
0570 
0571     return true;
0572 
0573 fail:
0574     e->pos = pos;
0575     return false;
0576 }
0577 
0578 static bool unpack_secmark(struct aa_ext *e, struct aa_profile *profile)
0579 {
0580     void *pos = e->pos;
0581     int i, size;
0582 
0583     if (unpack_nameX(e, AA_STRUCT, "secmark")) {
0584         size = unpack_array(e, NULL);
0585 
0586         profile->secmark = kcalloc(size, sizeof(struct aa_secmark),
0587                        GFP_KERNEL);
0588         if (!profile->secmark)
0589             goto fail;
0590 
0591         profile->secmark_count = size;
0592 
0593         for (i = 0; i < size; i++) {
0594             if (!unpack_u8(e, &profile->secmark[i].audit, NULL))
0595                 goto fail;
0596             if (!unpack_u8(e, &profile->secmark[i].deny, NULL))
0597                 goto fail;
0598             if (!unpack_strdup(e, &profile->secmark[i].label, NULL))
0599                 goto fail;
0600         }
0601         if (!unpack_nameX(e, AA_ARRAYEND, NULL))
0602             goto fail;
0603         if (!unpack_nameX(e, AA_STRUCTEND, NULL))
0604             goto fail;
0605     }
0606 
0607     return true;
0608 
0609 fail:
0610     if (profile->secmark) {
0611         for (i = 0; i < size; i++)
0612             kfree(profile->secmark[i].label);
0613         kfree(profile->secmark);
0614         profile->secmark_count = 0;
0615         profile->secmark = NULL;
0616     }
0617 
0618     e->pos = pos;
0619     return false;
0620 }
0621 
0622 static bool unpack_rlimits(struct aa_ext *e, struct aa_profile *profile)
0623 {
0624     void *pos = e->pos;
0625 
0626     /* rlimits are optional */
0627     if (unpack_nameX(e, AA_STRUCT, "rlimits")) {
0628         int i, size;
0629         u32 tmp = 0;
0630         if (!unpack_u32(e, &tmp, NULL))
0631             goto fail;
0632         profile->rlimits.mask = tmp;
0633 
0634         size = unpack_array(e, NULL);
0635         if (size > RLIM_NLIMITS)
0636             goto fail;
0637         for (i = 0; i < size; i++) {
0638             u64 tmp2 = 0;
0639             int a = aa_map_resource(i);
0640             if (!unpack_u64(e, &tmp2, NULL))
0641                 goto fail;
0642             profile->rlimits.limits[a].rlim_max = tmp2;
0643         }
0644         if (!unpack_nameX(e, AA_ARRAYEND, NULL))
0645             goto fail;
0646         if (!unpack_nameX(e, AA_STRUCTEND, NULL))
0647             goto fail;
0648     }
0649     return true;
0650 
0651 fail:
0652     e->pos = pos;
0653     return false;
0654 }
0655 
0656 static u32 strhash(const void *data, u32 len, u32 seed)
0657 {
0658     const char * const *key = data;
0659 
0660     return jhash(*key, strlen(*key), seed);
0661 }
0662 
0663 static int datacmp(struct rhashtable_compare_arg *arg, const void *obj)
0664 {
0665     const struct aa_data *data = obj;
0666     const char * const *key = arg->key;
0667 
0668     return strcmp(data->key, *key);
0669 }
0670 
0671 /**
0672  * unpack_profile - unpack a serialized profile
0673  * @e: serialized data extent information (NOT NULL)
0674  * @ns_name: pointer of newly allocated copy of %NULL in case of error
0675  *
0676  * NOTE: unpack profile sets audit struct if there is a failure
0677  */
0678 static struct aa_profile *unpack_profile(struct aa_ext *e, char **ns_name)
0679 {
0680     struct aa_profile *profile = NULL;
0681     const char *tmpname, *tmpns = NULL, *name = NULL;
0682     const char *info = "failed to unpack profile";
0683     size_t ns_len;
0684     struct rhashtable_params params = { 0 };
0685     char *key = NULL;
0686     struct aa_data *data;
0687     int i, error = -EPROTO;
0688     kernel_cap_t tmpcap;
0689     u32 tmp;
0690 
0691     *ns_name = NULL;
0692 
0693     /* check that we have the right struct being passed */
0694     if (!unpack_nameX(e, AA_STRUCT, "profile"))
0695         goto fail;
0696     if (!unpack_str(e, &name, NULL))
0697         goto fail;
0698     if (*name == '\0')
0699         goto fail;
0700 
0701     tmpname = aa_splitn_fqname(name, strlen(name), &tmpns, &ns_len);
0702     if (tmpns) {
0703         *ns_name = kstrndup(tmpns, ns_len, GFP_KERNEL);
0704         if (!*ns_name) {
0705             info = "out of memory";
0706             goto fail;
0707         }
0708         name = tmpname;
0709     }
0710 
0711     profile = aa_alloc_profile(name, NULL, GFP_KERNEL);
0712     if (!profile)
0713         return ERR_PTR(-ENOMEM);
0714 
0715     /* profile renaming is optional */
0716     (void) unpack_str(e, &profile->rename, "rename");
0717 
0718     /* attachment string is optional */
0719     (void) unpack_str(e, &profile->attach, "attach");
0720 
0721     /* xmatch is optional and may be NULL */
0722     profile->xmatch = unpack_dfa(e);
0723     if (IS_ERR(profile->xmatch)) {
0724         error = PTR_ERR(profile->xmatch);
0725         profile->xmatch = NULL;
0726         info = "bad xmatch";
0727         goto fail;
0728     }
0729     /* xmatch_len is not optional if xmatch is set */
0730     if (profile->xmatch) {
0731         if (!unpack_u32(e, &tmp, NULL)) {
0732             info = "missing xmatch len";
0733             goto fail;
0734         }
0735         profile->xmatch_len = tmp;
0736     }
0737 
0738     /* disconnected attachment string is optional */
0739     (void) unpack_str(e, &profile->disconnected, "disconnected");
0740 
0741     /* per profile debug flags (complain, audit) */
0742     if (!unpack_nameX(e, AA_STRUCT, "flags")) {
0743         info = "profile missing flags";
0744         goto fail;
0745     }
0746     info = "failed to unpack profile flags";
0747     if (!unpack_u32(e, &tmp, NULL))
0748         goto fail;
0749     if (tmp & PACKED_FLAG_HAT)
0750         profile->label.flags |= FLAG_HAT;
0751     if (tmp & PACKED_FLAG_DEBUG1)
0752         profile->label.flags |= FLAG_DEBUG1;
0753     if (tmp & PACKED_FLAG_DEBUG2)
0754         profile->label.flags |= FLAG_DEBUG2;
0755     if (!unpack_u32(e, &tmp, NULL))
0756         goto fail;
0757     if (tmp == PACKED_MODE_COMPLAIN || (e->version & FORCE_COMPLAIN_FLAG)) {
0758         profile->mode = APPARMOR_COMPLAIN;
0759     } else if (tmp == PACKED_MODE_ENFORCE) {
0760         profile->mode = APPARMOR_ENFORCE;
0761     } else if (tmp == PACKED_MODE_KILL) {
0762         profile->mode = APPARMOR_KILL;
0763     } else if (tmp == PACKED_MODE_UNCONFINED) {
0764         profile->mode = APPARMOR_UNCONFINED;
0765         profile->label.flags |= FLAG_UNCONFINED;
0766     } else {
0767         goto fail;
0768     }
0769     if (!unpack_u32(e, &tmp, NULL))
0770         goto fail;
0771     if (tmp)
0772         profile->audit = AUDIT_ALL;
0773 
0774     if (!unpack_nameX(e, AA_STRUCTEND, NULL))
0775         goto fail;
0776 
0777     /* path_flags is optional */
0778     if (unpack_u32(e, &profile->path_flags, "path_flags"))
0779         profile->path_flags |= profile->label.flags &
0780             PATH_MEDIATE_DELETED;
0781     else
0782         /* set a default value if path_flags field is not present */
0783         profile->path_flags = PATH_MEDIATE_DELETED;
0784 
0785     info = "failed to unpack profile capabilities";
0786     if (!unpack_u32(e, &(profile->caps.allow.cap[0]), NULL))
0787         goto fail;
0788     if (!unpack_u32(e, &(profile->caps.audit.cap[0]), NULL))
0789         goto fail;
0790     if (!unpack_u32(e, &(profile->caps.quiet.cap[0]), NULL))
0791         goto fail;
0792     if (!unpack_u32(e, &tmpcap.cap[0], NULL))
0793         goto fail;
0794 
0795     info = "failed to unpack upper profile capabilities";
0796     if (unpack_nameX(e, AA_STRUCT, "caps64")) {
0797         /* optional upper half of 64 bit caps */
0798         if (!unpack_u32(e, &(profile->caps.allow.cap[1]), NULL))
0799             goto fail;
0800         if (!unpack_u32(e, &(profile->caps.audit.cap[1]), NULL))
0801             goto fail;
0802         if (!unpack_u32(e, &(profile->caps.quiet.cap[1]), NULL))
0803             goto fail;
0804         if (!unpack_u32(e, &(tmpcap.cap[1]), NULL))
0805             goto fail;
0806         if (!unpack_nameX(e, AA_STRUCTEND, NULL))
0807             goto fail;
0808     }
0809 
0810     info = "failed to unpack extended profile capabilities";
0811     if (unpack_nameX(e, AA_STRUCT, "capsx")) {
0812         /* optional extended caps mediation mask */
0813         if (!unpack_u32(e, &(profile->caps.extended.cap[0]), NULL))
0814             goto fail;
0815         if (!unpack_u32(e, &(profile->caps.extended.cap[1]), NULL))
0816             goto fail;
0817         if (!unpack_nameX(e, AA_STRUCTEND, NULL))
0818             goto fail;
0819     }
0820 
0821     if (!unpack_xattrs(e, profile)) {
0822         info = "failed to unpack profile xattrs";
0823         goto fail;
0824     }
0825 
0826     if (!unpack_rlimits(e, profile)) {
0827         info = "failed to unpack profile rlimits";
0828         goto fail;
0829     }
0830 
0831     if (!unpack_secmark(e, profile)) {
0832         info = "failed to unpack profile secmark rules";
0833         goto fail;
0834     }
0835 
0836     if (unpack_nameX(e, AA_STRUCT, "policydb")) {
0837         /* generic policy dfa - optional and may be NULL */
0838         info = "failed to unpack policydb";
0839         profile->policy.dfa = unpack_dfa(e);
0840         if (IS_ERR(profile->policy.dfa)) {
0841             error = PTR_ERR(profile->policy.dfa);
0842             profile->policy.dfa = NULL;
0843             goto fail;
0844         } else if (!profile->policy.dfa) {
0845             error = -EPROTO;
0846             goto fail;
0847         }
0848         if (!unpack_u32(e, &profile->policy.start[0], "start"))
0849             /* default start state */
0850             profile->policy.start[0] = DFA_START;
0851         /* setup class index */
0852         for (i = AA_CLASS_FILE; i <= AA_CLASS_LAST; i++) {
0853             profile->policy.start[i] =
0854                 aa_dfa_next(profile->policy.dfa,
0855                         profile->policy.start[0],
0856                         i);
0857         }
0858         if (!unpack_nameX(e, AA_STRUCTEND, NULL))
0859             goto fail;
0860     } else
0861         profile->policy.dfa = aa_get_dfa(nulldfa);
0862 
0863     /* get file rules */
0864     profile->file.dfa = unpack_dfa(e);
0865     if (IS_ERR(profile->file.dfa)) {
0866         error = PTR_ERR(profile->file.dfa);
0867         profile->file.dfa = NULL;
0868         info = "failed to unpack profile file rules";
0869         goto fail;
0870     } else if (profile->file.dfa) {
0871         if (!unpack_u32(e, &profile->file.start, "dfa_start"))
0872             /* default start state */
0873             profile->file.start = DFA_START;
0874     } else if (profile->policy.dfa &&
0875            profile->policy.start[AA_CLASS_FILE]) {
0876         profile->file.dfa = aa_get_dfa(profile->policy.dfa);
0877         profile->file.start = profile->policy.start[AA_CLASS_FILE];
0878     } else
0879         profile->file.dfa = aa_get_dfa(nulldfa);
0880 
0881     if (!unpack_trans_table(e, profile)) {
0882         info = "failed to unpack profile transition table";
0883         goto fail;
0884     }
0885 
0886     if (unpack_nameX(e, AA_STRUCT, "data")) {
0887         info = "out of memory";
0888         profile->data = kzalloc(sizeof(*profile->data), GFP_KERNEL);
0889         if (!profile->data)
0890             goto fail;
0891 
0892         params.nelem_hint = 3;
0893         params.key_len = sizeof(void *);
0894         params.key_offset = offsetof(struct aa_data, key);
0895         params.head_offset = offsetof(struct aa_data, head);
0896         params.hashfn = strhash;
0897         params.obj_cmpfn = datacmp;
0898 
0899         if (rhashtable_init(profile->data, &params)) {
0900             info = "failed to init key, value hash table";
0901             goto fail;
0902         }
0903 
0904         while (unpack_strdup(e, &key, NULL)) {
0905             data = kzalloc(sizeof(*data), GFP_KERNEL);
0906             if (!data) {
0907                 kfree_sensitive(key);
0908                 goto fail;
0909             }
0910 
0911             data->key = key;
0912             data->size = unpack_blob(e, &data->data, NULL);
0913             data->data = kvmemdup(data->data, data->size);
0914             if (data->size && !data->data) {
0915                 kfree_sensitive(data->key);
0916                 kfree_sensitive(data);
0917                 goto fail;
0918             }
0919 
0920             rhashtable_insert_fast(profile->data, &data->head,
0921                            profile->data->p);
0922         }
0923 
0924         if (!unpack_nameX(e, AA_STRUCTEND, NULL)) {
0925             info = "failed to unpack end of key, value data table";
0926             goto fail;
0927         }
0928     }
0929 
0930     if (!unpack_nameX(e, AA_STRUCTEND, NULL)) {
0931         info = "failed to unpack end of profile";
0932         goto fail;
0933     }
0934 
0935     return profile;
0936 
0937 fail:
0938     if (profile)
0939         name = NULL;
0940     else if (!name)
0941         name = "unknown";
0942     audit_iface(profile, NULL, name, info, e, error);
0943     aa_free_profile(profile);
0944 
0945     return ERR_PTR(error);
0946 }
0947 
0948 /**
0949  * verify_header - unpack serialized stream header
0950  * @e: serialized data read head (NOT NULL)
0951  * @required: whether the header is required or optional
0952  * @ns: Returns - namespace if one is specified else NULL (NOT NULL)
0953  *
0954  * Returns: error or 0 if header is good
0955  */
0956 static int verify_header(struct aa_ext *e, int required, const char **ns)
0957 {
0958     int error = -EPROTONOSUPPORT;
0959     const char *name = NULL;
0960     *ns = NULL;
0961 
0962     /* get the interface version */
0963     if (!unpack_u32(e, &e->version, "version")) {
0964         if (required) {
0965             audit_iface(NULL, NULL, NULL, "invalid profile format",
0966                     e, error);
0967             return error;
0968         }
0969     }
0970 
0971     /* Check that the interface version is currently supported.
0972      * if not specified use previous version
0973      * Mask off everything that is not kernel abi version
0974      */
0975     if (VERSION_LT(e->version, v5) || VERSION_GT(e->version, v7)) {
0976         audit_iface(NULL, NULL, NULL, "unsupported interface version",
0977                 e, error);
0978         return error;
0979     }
0980 
0981     /* read the namespace if present */
0982     if (unpack_str(e, &name, "namespace")) {
0983         if (*name == '\0') {
0984             audit_iface(NULL, NULL, NULL, "invalid namespace name",
0985                     e, error);
0986             return error;
0987         }
0988         if (*ns && strcmp(*ns, name)) {
0989             audit_iface(NULL, NULL, NULL, "invalid ns change", e,
0990                     error);
0991         } else if (!*ns) {
0992             *ns = kstrdup(name, GFP_KERNEL);
0993             if (!*ns)
0994                 return -ENOMEM;
0995         }
0996     }
0997 
0998     return 0;
0999 }
1000 
1001 static bool verify_xindex(int xindex, int table_size)
1002 {
1003     int index, xtype;
1004     xtype = xindex & AA_X_TYPE_MASK;
1005     index = xindex & AA_X_INDEX_MASK;
1006     if (xtype == AA_X_TABLE && index >= table_size)
1007         return false;
1008     return true;
1009 }
1010 
1011 /* verify dfa xindexes are in range of transition tables */
1012 static bool verify_dfa_xindex(struct aa_dfa *dfa, int table_size)
1013 {
1014     int i;
1015     for (i = 0; i < dfa->tables[YYTD_ID_ACCEPT]->td_lolen; i++) {
1016         if (!verify_xindex(dfa_user_xindex(dfa, i), table_size))
1017             return false;
1018         if (!verify_xindex(dfa_other_xindex(dfa, i), table_size))
1019             return false;
1020     }
1021     return true;
1022 }
1023 
1024 /**
1025  * verify_profile - Do post unpack analysis to verify profile consistency
1026  * @profile: profile to verify (NOT NULL)
1027  *
1028  * Returns: 0 if passes verification else error
1029  */
1030 static int verify_profile(struct aa_profile *profile)
1031 {
1032     if (profile->file.dfa &&
1033         !verify_dfa_xindex(profile->file.dfa,
1034                    profile->file.trans.size)) {
1035         audit_iface(profile, NULL, NULL, "Invalid named transition",
1036                 NULL, -EPROTO);
1037         return -EPROTO;
1038     }
1039 
1040     return 0;
1041 }
1042 
1043 void aa_load_ent_free(struct aa_load_ent *ent)
1044 {
1045     if (ent) {
1046         aa_put_profile(ent->rename);
1047         aa_put_profile(ent->old);
1048         aa_put_profile(ent->new);
1049         kfree(ent->ns_name);
1050         kfree_sensitive(ent);
1051     }
1052 }
1053 
1054 struct aa_load_ent *aa_load_ent_alloc(void)
1055 {
1056     struct aa_load_ent *ent = kzalloc(sizeof(*ent), GFP_KERNEL);
1057     if (ent)
1058         INIT_LIST_HEAD(&ent->list);
1059     return ent;
1060 }
1061 
1062 static int deflate_compress(const char *src, size_t slen, char **dst,
1063                 size_t *dlen)
1064 {
1065 #ifdef CONFIG_SECURITY_APPARMOR_EXPORT_BINARY
1066     int error;
1067     struct z_stream_s strm;
1068     void *stgbuf, *dstbuf;
1069     size_t stglen = deflateBound(slen);
1070 
1071     memset(&strm, 0, sizeof(strm));
1072 
1073     if (stglen < slen)
1074         return -EFBIG;
1075 
1076     strm.workspace = kvzalloc(zlib_deflate_workspacesize(MAX_WBITS,
1077                                  MAX_MEM_LEVEL),
1078                   GFP_KERNEL);
1079     if (!strm.workspace)
1080         return -ENOMEM;
1081 
1082     error = zlib_deflateInit(&strm, aa_g_rawdata_compression_level);
1083     if (error != Z_OK) {
1084         error = -ENOMEM;
1085         goto fail_deflate_init;
1086     }
1087 
1088     stgbuf = kvzalloc(stglen, GFP_KERNEL);
1089     if (!stgbuf) {
1090         error = -ENOMEM;
1091         goto fail_stg_alloc;
1092     }
1093 
1094     strm.next_in = src;
1095     strm.avail_in = slen;
1096     strm.next_out = stgbuf;
1097     strm.avail_out = stglen;
1098 
1099     error = zlib_deflate(&strm, Z_FINISH);
1100     if (error != Z_STREAM_END) {
1101         error = -EINVAL;
1102         goto fail_deflate;
1103     }
1104     error = 0;
1105 
1106     if (is_vmalloc_addr(stgbuf)) {
1107         dstbuf = kvzalloc(strm.total_out, GFP_KERNEL);
1108         if (dstbuf) {
1109             memcpy(dstbuf, stgbuf, strm.total_out);
1110             kvfree(stgbuf);
1111         }
1112     } else
1113         /*
1114          * If the staging buffer was kmalloc'd, then using krealloc is
1115          * probably going to be faster. The destination buffer will
1116          * always be smaller, so it's just shrunk, avoiding a memcpy
1117          */
1118         dstbuf = krealloc(stgbuf, strm.total_out, GFP_KERNEL);
1119 
1120     if (!dstbuf) {
1121         error = -ENOMEM;
1122         goto fail_deflate;
1123     }
1124 
1125     *dst = dstbuf;
1126     *dlen = strm.total_out;
1127 
1128 fail_stg_alloc:
1129     zlib_deflateEnd(&strm);
1130 fail_deflate_init:
1131     kvfree(strm.workspace);
1132     return error;
1133 
1134 fail_deflate:
1135     kvfree(stgbuf);
1136     goto fail_stg_alloc;
1137 #else
1138     *dlen = slen;
1139     return 0;
1140 #endif
1141 }
1142 
1143 static int compress_loaddata(struct aa_loaddata *data)
1144 {
1145 
1146     AA_BUG(data->compressed_size > 0);
1147 
1148     /*
1149      * Shortcut the no compression case, else we increase the amount of
1150      * storage required by a small amount
1151      */
1152     if (aa_g_rawdata_compression_level != 0) {
1153         void *udata = data->data;
1154         int error = deflate_compress(udata, data->size, &data->data,
1155                          &data->compressed_size);
1156         if (error)
1157             return error;
1158 
1159         if (udata != data->data)
1160             kvfree(udata);
1161     } else
1162         data->compressed_size = data->size;
1163 
1164     return 0;
1165 }
1166 
1167 /**
1168  * aa_unpack - unpack packed binary profile(s) data loaded from user space
1169  * @udata: user data copied to kmem  (NOT NULL)
1170  * @lh: list to place unpacked profiles in a aa_repl_ws
1171  * @ns: Returns namespace profile is in if specified else NULL (NOT NULL)
1172  *
1173  * Unpack user data and return refcounted allocated profile(s) stored in
1174  * @lh in order of discovery, with the list chain stored in base.list
1175  * or error
1176  *
1177  * Returns: profile(s) on @lh else error pointer if fails to unpack
1178  */
1179 int aa_unpack(struct aa_loaddata *udata, struct list_head *lh,
1180           const char **ns)
1181 {
1182     struct aa_load_ent *tmp, *ent;
1183     struct aa_profile *profile = NULL;
1184     int error;
1185     struct aa_ext e = {
1186         .start = udata->data,
1187         .end = udata->data + udata->size,
1188         .pos = udata->data,
1189     };
1190 
1191     *ns = NULL;
1192     while (e.pos < e.end) {
1193         char *ns_name = NULL;
1194         void *start;
1195         error = verify_header(&e, e.pos == e.start, ns);
1196         if (error)
1197             goto fail;
1198 
1199         start = e.pos;
1200         profile = unpack_profile(&e, &ns_name);
1201         if (IS_ERR(profile)) {
1202             error = PTR_ERR(profile);
1203             goto fail;
1204         }
1205 
1206         error = verify_profile(profile);
1207         if (error)
1208             goto fail_profile;
1209 
1210         if (aa_g_hash_policy)
1211             error = aa_calc_profile_hash(profile, e.version, start,
1212                              e.pos - start);
1213         if (error)
1214             goto fail_profile;
1215 
1216         ent = aa_load_ent_alloc();
1217         if (!ent) {
1218             error = -ENOMEM;
1219             goto fail_profile;
1220         }
1221 
1222         ent->new = profile;
1223         ent->ns_name = ns_name;
1224         list_add_tail(&ent->list, lh);
1225     }
1226     udata->abi = e.version & K_ABI_MASK;
1227     if (aa_g_hash_policy) {
1228         udata->hash = aa_calc_hash(udata->data, udata->size);
1229         if (IS_ERR(udata->hash)) {
1230             error = PTR_ERR(udata->hash);
1231             udata->hash = NULL;
1232             goto fail;
1233         }
1234     }
1235 
1236     if (aa_g_export_binary) {
1237         error = compress_loaddata(udata);
1238         if (error)
1239             goto fail;
1240     }
1241     return 0;
1242 
1243 fail_profile:
1244     aa_put_profile(profile);
1245 
1246 fail:
1247     list_for_each_entry_safe(ent, tmp, lh, list) {
1248         list_del_init(&ent->list);
1249         aa_load_ent_free(ent);
1250     }
1251 
1252     return error;
1253 }
1254 
1255 #ifdef CONFIG_SECURITY_APPARMOR_KUNIT_TEST
1256 #include "policy_unpack_test.c"
1257 #endif /* CONFIG_SECURITY_APPARMOR_KUNIT_TEST */