Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Copyright (C) 2008 IBM Corporation
0004  * Author: Mimi Zohar <zohar@us.ibm.com>
0005  *
0006  * ima_policy.c
0007  *  - initialize default measure policy rules
0008  */
0009 
0010 #include <linux/init.h>
0011 #include <linux/list.h>
0012 #include <linux/kernel_read_file.h>
0013 #include <linux/fs.h>
0014 #include <linux/security.h>
0015 #include <linux/magic.h>
0016 #include <linux/parser.h>
0017 #include <linux/slab.h>
0018 #include <linux/rculist.h>
0019 #include <linux/seq_file.h>
0020 #include <linux/ima.h>
0021 
0022 #include "ima.h"
0023 
0024 /* flags definitions */
0025 #define IMA_FUNC    0x0001
0026 #define IMA_MASK    0x0002
0027 #define IMA_FSMAGIC 0x0004
0028 #define IMA_UID     0x0008
0029 #define IMA_FOWNER  0x0010
0030 #define IMA_FSUUID  0x0020
0031 #define IMA_INMASK  0x0040
0032 #define IMA_EUID    0x0080
0033 #define IMA_PCR     0x0100
0034 #define IMA_FSNAME  0x0200
0035 #define IMA_KEYRINGS    0x0400
0036 #define IMA_LABEL   0x0800
0037 #define IMA_VALIDATE_ALGOS  0x1000
0038 #define IMA_GID     0x2000
0039 #define IMA_EGID    0x4000
0040 #define IMA_FGROUP  0x8000
0041 
0042 #define UNKNOWN     0
0043 #define MEASURE     0x0001  /* same as IMA_MEASURE */
0044 #define DONT_MEASURE    0x0002
0045 #define APPRAISE    0x0004  /* same as IMA_APPRAISE */
0046 #define DONT_APPRAISE   0x0008
0047 #define AUDIT       0x0040
0048 #define HASH        0x0100
0049 #define DONT_HASH   0x0200
0050 
0051 #define INVALID_PCR(a) (((a) < 0) || \
0052     (a) >= (sizeof_field(struct integrity_iint_cache, measured_pcrs) * 8))
0053 
0054 int ima_policy_flag;
0055 static int temp_ima_appraise;
0056 static int build_ima_appraise __ro_after_init;
0057 
0058 atomic_t ima_setxattr_allowed_hash_algorithms;
0059 
0060 #define MAX_LSM_RULES 6
0061 enum lsm_rule_types { LSM_OBJ_USER, LSM_OBJ_ROLE, LSM_OBJ_TYPE,
0062     LSM_SUBJ_USER, LSM_SUBJ_ROLE, LSM_SUBJ_TYPE
0063 };
0064 
0065 enum policy_types { ORIGINAL_TCB = 1, DEFAULT_TCB };
0066 
0067 enum policy_rule_list { IMA_DEFAULT_POLICY = 1, IMA_CUSTOM_POLICY };
0068 
0069 struct ima_rule_opt_list {
0070     size_t count;
0071     char *items[];
0072 };
0073 
0074 struct ima_rule_entry {
0075     struct list_head list;
0076     int action;
0077     unsigned int flags;
0078     enum ima_hooks func;
0079     int mask;
0080     unsigned long fsmagic;
0081     uuid_t fsuuid;
0082     kuid_t uid;
0083     kgid_t gid;
0084     kuid_t fowner;
0085     kgid_t fgroup;
0086     bool (*uid_op)(kuid_t cred_uid, kuid_t rule_uid);    /* Handlers for operators       */
0087     bool (*gid_op)(kgid_t cred_gid, kgid_t rule_gid);
0088     bool (*fowner_op)(kuid_t cred_uid, kuid_t rule_uid); /* uid_eq(), uid_gt(), uid_lt() */
0089     bool (*fgroup_op)(kgid_t cred_gid, kgid_t rule_gid); /* gid_eq(), gid_gt(), gid_lt() */
0090     int pcr;
0091     unsigned int allowed_algos; /* bitfield of allowed hash algorithms */
0092     struct {
0093         void *rule; /* LSM file metadata specific */
0094         char *args_p;   /* audit value */
0095         int type;   /* audit type */
0096     } lsm[MAX_LSM_RULES];
0097     char *fsname;
0098     struct ima_rule_opt_list *keyrings; /* Measure keys added to these keyrings */
0099     struct ima_rule_opt_list *label; /* Measure data grouped under this label */
0100     struct ima_template_desc *template;
0101 };
0102 
0103 /*
0104  * sanity check in case the kernels gains more hash algorithms that can
0105  * fit in an unsigned int
0106  */
0107 static_assert(
0108     8 * sizeof(unsigned int) >= HASH_ALGO__LAST,
0109     "The bitfield allowed_algos in ima_rule_entry is too small to contain all the supported hash algorithms, consider using a bigger type");
0110 
0111 /*
0112  * Without LSM specific knowledge, the default policy can only be
0113  * written in terms of .action, .func, .mask, .fsmagic, .uid, .gid,
0114  * .fowner, and .fgroup
0115  */
0116 
0117 /*
0118  * The minimum rule set to allow for full TCB coverage.  Measures all files
0119  * opened or mmap for exec and everything read by root.  Dangerous because
0120  * normal users can easily run the machine out of memory simply building
0121  * and running executables.
0122  */
0123 static struct ima_rule_entry dont_measure_rules[] __ro_after_init = {
0124     {.action = DONT_MEASURE, .fsmagic = PROC_SUPER_MAGIC, .flags = IMA_FSMAGIC},
0125     {.action = DONT_MEASURE, .fsmagic = SYSFS_MAGIC, .flags = IMA_FSMAGIC},
0126     {.action = DONT_MEASURE, .fsmagic = DEBUGFS_MAGIC, .flags = IMA_FSMAGIC},
0127     {.action = DONT_MEASURE, .fsmagic = TMPFS_MAGIC, .flags = IMA_FSMAGIC},
0128     {.action = DONT_MEASURE, .fsmagic = DEVPTS_SUPER_MAGIC, .flags = IMA_FSMAGIC},
0129     {.action = DONT_MEASURE, .fsmagic = BINFMTFS_MAGIC, .flags = IMA_FSMAGIC},
0130     {.action = DONT_MEASURE, .fsmagic = SECURITYFS_MAGIC, .flags = IMA_FSMAGIC},
0131     {.action = DONT_MEASURE, .fsmagic = SELINUX_MAGIC, .flags = IMA_FSMAGIC},
0132     {.action = DONT_MEASURE, .fsmagic = SMACK_MAGIC, .flags = IMA_FSMAGIC},
0133     {.action = DONT_MEASURE, .fsmagic = CGROUP_SUPER_MAGIC,
0134      .flags = IMA_FSMAGIC},
0135     {.action = DONT_MEASURE, .fsmagic = CGROUP2_SUPER_MAGIC,
0136      .flags = IMA_FSMAGIC},
0137     {.action = DONT_MEASURE, .fsmagic = NSFS_MAGIC, .flags = IMA_FSMAGIC},
0138     {.action = DONT_MEASURE, .fsmagic = EFIVARFS_MAGIC, .flags = IMA_FSMAGIC}
0139 };
0140 
0141 static struct ima_rule_entry original_measurement_rules[] __ro_after_init = {
0142     {.action = MEASURE, .func = MMAP_CHECK, .mask = MAY_EXEC,
0143      .flags = IMA_FUNC | IMA_MASK},
0144     {.action = MEASURE, .func = BPRM_CHECK, .mask = MAY_EXEC,
0145      .flags = IMA_FUNC | IMA_MASK},
0146     {.action = MEASURE, .func = FILE_CHECK, .mask = MAY_READ,
0147      .uid = GLOBAL_ROOT_UID, .uid_op = &uid_eq,
0148      .flags = IMA_FUNC | IMA_MASK | IMA_UID},
0149     {.action = MEASURE, .func = MODULE_CHECK, .flags = IMA_FUNC},
0150     {.action = MEASURE, .func = FIRMWARE_CHECK, .flags = IMA_FUNC},
0151 };
0152 
0153 static struct ima_rule_entry default_measurement_rules[] __ro_after_init = {
0154     {.action = MEASURE, .func = MMAP_CHECK, .mask = MAY_EXEC,
0155      .flags = IMA_FUNC | IMA_MASK},
0156     {.action = MEASURE, .func = BPRM_CHECK, .mask = MAY_EXEC,
0157      .flags = IMA_FUNC | IMA_MASK},
0158     {.action = MEASURE, .func = FILE_CHECK, .mask = MAY_READ,
0159      .uid = GLOBAL_ROOT_UID, .uid_op = &uid_eq,
0160      .flags = IMA_FUNC | IMA_INMASK | IMA_EUID},
0161     {.action = MEASURE, .func = FILE_CHECK, .mask = MAY_READ,
0162      .uid = GLOBAL_ROOT_UID, .uid_op = &uid_eq,
0163      .flags = IMA_FUNC | IMA_INMASK | IMA_UID},
0164     {.action = MEASURE, .func = MODULE_CHECK, .flags = IMA_FUNC},
0165     {.action = MEASURE, .func = FIRMWARE_CHECK, .flags = IMA_FUNC},
0166     {.action = MEASURE, .func = POLICY_CHECK, .flags = IMA_FUNC},
0167 };
0168 
0169 static struct ima_rule_entry default_appraise_rules[] __ro_after_init = {
0170     {.action = DONT_APPRAISE, .fsmagic = PROC_SUPER_MAGIC, .flags = IMA_FSMAGIC},
0171     {.action = DONT_APPRAISE, .fsmagic = SYSFS_MAGIC, .flags = IMA_FSMAGIC},
0172     {.action = DONT_APPRAISE, .fsmagic = DEBUGFS_MAGIC, .flags = IMA_FSMAGIC},
0173     {.action = DONT_APPRAISE, .fsmagic = TMPFS_MAGIC, .flags = IMA_FSMAGIC},
0174     {.action = DONT_APPRAISE, .fsmagic = RAMFS_MAGIC, .flags = IMA_FSMAGIC},
0175     {.action = DONT_APPRAISE, .fsmagic = DEVPTS_SUPER_MAGIC, .flags = IMA_FSMAGIC},
0176     {.action = DONT_APPRAISE, .fsmagic = BINFMTFS_MAGIC, .flags = IMA_FSMAGIC},
0177     {.action = DONT_APPRAISE, .fsmagic = SECURITYFS_MAGIC, .flags = IMA_FSMAGIC},
0178     {.action = DONT_APPRAISE, .fsmagic = SELINUX_MAGIC, .flags = IMA_FSMAGIC},
0179     {.action = DONT_APPRAISE, .fsmagic = SMACK_MAGIC, .flags = IMA_FSMAGIC},
0180     {.action = DONT_APPRAISE, .fsmagic = NSFS_MAGIC, .flags = IMA_FSMAGIC},
0181     {.action = DONT_APPRAISE, .fsmagic = EFIVARFS_MAGIC, .flags = IMA_FSMAGIC},
0182     {.action = DONT_APPRAISE, .fsmagic = CGROUP_SUPER_MAGIC, .flags = IMA_FSMAGIC},
0183     {.action = DONT_APPRAISE, .fsmagic = CGROUP2_SUPER_MAGIC, .flags = IMA_FSMAGIC},
0184 #ifdef CONFIG_IMA_WRITE_POLICY
0185     {.action = APPRAISE, .func = POLICY_CHECK,
0186     .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
0187 #endif
0188 #ifndef CONFIG_IMA_APPRAISE_SIGNED_INIT
0189     {.action = APPRAISE, .fowner = GLOBAL_ROOT_UID, .fowner_op = &uid_eq,
0190      .flags = IMA_FOWNER},
0191 #else
0192     /* force signature */
0193     {.action = APPRAISE, .fowner = GLOBAL_ROOT_UID, .fowner_op = &uid_eq,
0194      .flags = IMA_FOWNER | IMA_DIGSIG_REQUIRED},
0195 #endif
0196 };
0197 
0198 static struct ima_rule_entry build_appraise_rules[] __ro_after_init = {
0199 #ifdef CONFIG_IMA_APPRAISE_REQUIRE_MODULE_SIGS
0200     {.action = APPRAISE, .func = MODULE_CHECK,
0201      .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
0202 #endif
0203 #ifdef CONFIG_IMA_APPRAISE_REQUIRE_FIRMWARE_SIGS
0204     {.action = APPRAISE, .func = FIRMWARE_CHECK,
0205      .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
0206 #endif
0207 #ifdef CONFIG_IMA_APPRAISE_REQUIRE_KEXEC_SIGS
0208     {.action = APPRAISE, .func = KEXEC_KERNEL_CHECK,
0209      .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
0210 #endif
0211 #ifdef CONFIG_IMA_APPRAISE_REQUIRE_POLICY_SIGS
0212     {.action = APPRAISE, .func = POLICY_CHECK,
0213      .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
0214 #endif
0215 };
0216 
0217 static struct ima_rule_entry secure_boot_rules[] __ro_after_init = {
0218     {.action = APPRAISE, .func = MODULE_CHECK,
0219      .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
0220     {.action = APPRAISE, .func = FIRMWARE_CHECK,
0221      .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
0222     {.action = APPRAISE, .func = KEXEC_KERNEL_CHECK,
0223      .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
0224     {.action = APPRAISE, .func = POLICY_CHECK,
0225      .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
0226 };
0227 
0228 static struct ima_rule_entry critical_data_rules[] __ro_after_init = {
0229     {.action = MEASURE, .func = CRITICAL_DATA, .flags = IMA_FUNC},
0230 };
0231 
0232 /* An array of architecture specific rules */
0233 static struct ima_rule_entry *arch_policy_entry __ro_after_init;
0234 
0235 static LIST_HEAD(ima_default_rules);
0236 static LIST_HEAD(ima_policy_rules);
0237 static LIST_HEAD(ima_temp_rules);
0238 static struct list_head __rcu *ima_rules = (struct list_head __rcu *)(&ima_default_rules);
0239 
0240 static int ima_policy __initdata;
0241 
0242 static int __init default_measure_policy_setup(char *str)
0243 {
0244     if (ima_policy)
0245         return 1;
0246 
0247     ima_policy = ORIGINAL_TCB;
0248     return 1;
0249 }
0250 __setup("ima_tcb", default_measure_policy_setup);
0251 
0252 static bool ima_use_appraise_tcb __initdata;
0253 static bool ima_use_secure_boot __initdata;
0254 static bool ima_use_critical_data __initdata;
0255 static bool ima_fail_unverifiable_sigs __ro_after_init;
0256 static int __init policy_setup(char *str)
0257 {
0258     char *p;
0259 
0260     while ((p = strsep(&str, " |\n")) != NULL) {
0261         if (*p == ' ')
0262             continue;
0263         if ((strcmp(p, "tcb") == 0) && !ima_policy)
0264             ima_policy = DEFAULT_TCB;
0265         else if (strcmp(p, "appraise_tcb") == 0)
0266             ima_use_appraise_tcb = true;
0267         else if (strcmp(p, "secure_boot") == 0)
0268             ima_use_secure_boot = true;
0269         else if (strcmp(p, "critical_data") == 0)
0270             ima_use_critical_data = true;
0271         else if (strcmp(p, "fail_securely") == 0)
0272             ima_fail_unverifiable_sigs = true;
0273         else
0274             pr_err("policy \"%s\" not found", p);
0275     }
0276 
0277     return 1;
0278 }
0279 __setup("ima_policy=", policy_setup);
0280 
0281 static int __init default_appraise_policy_setup(char *str)
0282 {
0283     ima_use_appraise_tcb = true;
0284     return 1;
0285 }
0286 __setup("ima_appraise_tcb", default_appraise_policy_setup);
0287 
0288 static struct ima_rule_opt_list *ima_alloc_rule_opt_list(const substring_t *src)
0289 {
0290     struct ima_rule_opt_list *opt_list;
0291     size_t count = 0;
0292     char *src_copy;
0293     char *cur, *next;
0294     size_t i;
0295 
0296     src_copy = match_strdup(src);
0297     if (!src_copy)
0298         return ERR_PTR(-ENOMEM);
0299 
0300     next = src_copy;
0301     while ((cur = strsep(&next, "|"))) {
0302         /* Don't accept an empty list item */
0303         if (!(*cur)) {
0304             kfree(src_copy);
0305             return ERR_PTR(-EINVAL);
0306         }
0307         count++;
0308     }
0309 
0310     /* Don't accept an empty list */
0311     if (!count) {
0312         kfree(src_copy);
0313         return ERR_PTR(-EINVAL);
0314     }
0315 
0316     opt_list = kzalloc(struct_size(opt_list, items, count), GFP_KERNEL);
0317     if (!opt_list) {
0318         kfree(src_copy);
0319         return ERR_PTR(-ENOMEM);
0320     }
0321 
0322     /*
0323      * strsep() has already replaced all instances of '|' with '\0',
0324      * leaving a byte sequence of NUL-terminated strings. Reference each
0325      * string with the array of items.
0326      *
0327      * IMPORTANT: Ownership of the allocated buffer is transferred from
0328      * src_copy to the first element in the items array. To free the
0329      * buffer, kfree() must only be called on the first element of the
0330      * array.
0331      */
0332     for (i = 0, cur = src_copy; i < count; i++) {
0333         opt_list->items[i] = cur;
0334         cur = strchr(cur, '\0') + 1;
0335     }
0336     opt_list->count = count;
0337 
0338     return opt_list;
0339 }
0340 
0341 static void ima_free_rule_opt_list(struct ima_rule_opt_list *opt_list)
0342 {
0343     if (!opt_list)
0344         return;
0345 
0346     if (opt_list->count) {
0347         kfree(opt_list->items[0]);
0348         opt_list->count = 0;
0349     }
0350 
0351     kfree(opt_list);
0352 }
0353 
0354 static void ima_lsm_free_rule(struct ima_rule_entry *entry)
0355 {
0356     int i;
0357 
0358     for (i = 0; i < MAX_LSM_RULES; i++) {
0359         ima_filter_rule_free(entry->lsm[i].rule);
0360         kfree(entry->lsm[i].args_p);
0361     }
0362 }
0363 
0364 static void ima_free_rule(struct ima_rule_entry *entry)
0365 {
0366     if (!entry)
0367         return;
0368 
0369     /*
0370      * entry->template->fields may be allocated in ima_parse_rule() but that
0371      * reference is owned by the corresponding ima_template_desc element in
0372      * the defined_templates list and cannot be freed here
0373      */
0374     kfree(entry->fsname);
0375     ima_free_rule_opt_list(entry->keyrings);
0376     ima_lsm_free_rule(entry);
0377     kfree(entry);
0378 }
0379 
0380 static struct ima_rule_entry *ima_lsm_copy_rule(struct ima_rule_entry *entry)
0381 {
0382     struct ima_rule_entry *nentry;
0383     int i;
0384 
0385     /*
0386      * Immutable elements are copied over as pointers and data; only
0387      * lsm rules can change
0388      */
0389     nentry = kmemdup(entry, sizeof(*nentry), GFP_KERNEL);
0390     if (!nentry)
0391         return NULL;
0392 
0393     memset(nentry->lsm, 0, sizeof_field(struct ima_rule_entry, lsm));
0394 
0395     for (i = 0; i < MAX_LSM_RULES; i++) {
0396         if (!entry->lsm[i].args_p)
0397             continue;
0398 
0399         nentry->lsm[i].type = entry->lsm[i].type;
0400         nentry->lsm[i].args_p = entry->lsm[i].args_p;
0401         /*
0402          * Remove the reference from entry so that the associated
0403          * memory will not be freed during a later call to
0404          * ima_lsm_free_rule(entry).
0405          */
0406         entry->lsm[i].args_p = NULL;
0407 
0408         ima_filter_rule_init(nentry->lsm[i].type, Audit_equal,
0409                      nentry->lsm[i].args_p,
0410                      &nentry->lsm[i].rule);
0411         if (!nentry->lsm[i].rule)
0412             pr_warn("rule for LSM \'%s\' is undefined\n",
0413                 nentry->lsm[i].args_p);
0414     }
0415     return nentry;
0416 }
0417 
0418 static int ima_lsm_update_rule(struct ima_rule_entry *entry)
0419 {
0420     struct ima_rule_entry *nentry;
0421 
0422     nentry = ima_lsm_copy_rule(entry);
0423     if (!nentry)
0424         return -ENOMEM;
0425 
0426     list_replace_rcu(&entry->list, &nentry->list);
0427     synchronize_rcu();
0428     /*
0429      * ima_lsm_copy_rule() shallow copied all references, except for the
0430      * LSM references, from entry to nentry so we only want to free the LSM
0431      * references and the entry itself. All other memory references will now
0432      * be owned by nentry.
0433      */
0434     ima_lsm_free_rule(entry);
0435     kfree(entry);
0436 
0437     return 0;
0438 }
0439 
0440 static bool ima_rule_contains_lsm_cond(struct ima_rule_entry *entry)
0441 {
0442     int i;
0443 
0444     for (i = 0; i < MAX_LSM_RULES; i++)
0445         if (entry->lsm[i].args_p)
0446             return true;
0447 
0448     return false;
0449 }
0450 
0451 /*
0452  * The LSM policy can be reloaded, leaving the IMA LSM based rules referring
0453  * to the old, stale LSM policy.  Update the IMA LSM based rules to reflect
0454  * the reloaded LSM policy.
0455  */
0456 static void ima_lsm_update_rules(void)
0457 {
0458     struct ima_rule_entry *entry, *e;
0459     int result;
0460 
0461     list_for_each_entry_safe(entry, e, &ima_policy_rules, list) {
0462         if (!ima_rule_contains_lsm_cond(entry))
0463             continue;
0464 
0465         result = ima_lsm_update_rule(entry);
0466         if (result) {
0467             pr_err("lsm rule update error %d\n", result);
0468             return;
0469         }
0470     }
0471 }
0472 
0473 int ima_lsm_policy_change(struct notifier_block *nb, unsigned long event,
0474               void *lsm_data)
0475 {
0476     if (event != LSM_POLICY_CHANGE)
0477         return NOTIFY_DONE;
0478 
0479     ima_lsm_update_rules();
0480     return NOTIFY_OK;
0481 }
0482 
0483 /**
0484  * ima_match_rule_data - determine whether func_data matches the policy rule
0485  * @rule: a pointer to a rule
0486  * @func_data: data to match against the measure rule data
0487  * @cred: a pointer to a credentials structure for user validation
0488  *
0489  * Returns true if func_data matches one in the rule, false otherwise.
0490  */
0491 static bool ima_match_rule_data(struct ima_rule_entry *rule,
0492                 const char *func_data,
0493                 const struct cred *cred)
0494 {
0495     const struct ima_rule_opt_list *opt_list = NULL;
0496     bool matched = false;
0497     size_t i;
0498 
0499     if ((rule->flags & IMA_UID) && !rule->uid_op(cred->uid, rule->uid))
0500         return false;
0501 
0502     switch (rule->func) {
0503     case KEY_CHECK:
0504         if (!rule->keyrings)
0505             return true;
0506 
0507         opt_list = rule->keyrings;
0508         break;
0509     case CRITICAL_DATA:
0510         if (!rule->label)
0511             return true;
0512 
0513         opt_list = rule->label;
0514         break;
0515     default:
0516         return false;
0517     }
0518 
0519     if (!func_data)
0520         return false;
0521 
0522     for (i = 0; i < opt_list->count; i++) {
0523         if (!strcmp(opt_list->items[i], func_data)) {
0524             matched = true;
0525             break;
0526         }
0527     }
0528 
0529     return matched;
0530 }
0531 
0532 /**
0533  * ima_match_rules - determine whether an inode matches the policy rule.
0534  * @rule: a pointer to a rule
0535  * @mnt_userns: user namespace of the mount the inode was found from
0536  * @inode: a pointer to an inode
0537  * @cred: a pointer to a credentials structure for user validation
0538  * @secid: the secid of the task to be validated
0539  * @func: LIM hook identifier
0540  * @mask: requested action (MAY_READ | MAY_WRITE | MAY_APPEND | MAY_EXEC)
0541  * @func_data: func specific data, may be NULL
0542  *
0543  * Returns true on rule match, false on failure.
0544  */
0545 static bool ima_match_rules(struct ima_rule_entry *rule,
0546                 struct user_namespace *mnt_userns,
0547                 struct inode *inode, const struct cred *cred,
0548                 u32 secid, enum ima_hooks func, int mask,
0549                 const char *func_data)
0550 {
0551     int i;
0552 
0553     if ((rule->flags & IMA_FUNC) &&
0554         (rule->func != func && func != POST_SETATTR))
0555         return false;
0556 
0557     switch (func) {
0558     case KEY_CHECK:
0559     case CRITICAL_DATA:
0560         return ((rule->func == func) &&
0561             ima_match_rule_data(rule, func_data, cred));
0562     default:
0563         break;
0564     }
0565 
0566     if ((rule->flags & IMA_MASK) &&
0567         (rule->mask != mask && func != POST_SETATTR))
0568         return false;
0569     if ((rule->flags & IMA_INMASK) &&
0570         (!(rule->mask & mask) && func != POST_SETATTR))
0571         return false;
0572     if ((rule->flags & IMA_FSMAGIC)
0573         && rule->fsmagic != inode->i_sb->s_magic)
0574         return false;
0575     if ((rule->flags & IMA_FSNAME)
0576         && strcmp(rule->fsname, inode->i_sb->s_type->name))
0577         return false;
0578     if ((rule->flags & IMA_FSUUID) &&
0579         !uuid_equal(&rule->fsuuid, &inode->i_sb->s_uuid))
0580         return false;
0581     if ((rule->flags & IMA_UID) && !rule->uid_op(cred->uid, rule->uid))
0582         return false;
0583     if (rule->flags & IMA_EUID) {
0584         if (has_capability_noaudit(current, CAP_SETUID)) {
0585             if (!rule->uid_op(cred->euid, rule->uid)
0586                 && !rule->uid_op(cred->suid, rule->uid)
0587                 && !rule->uid_op(cred->uid, rule->uid))
0588                 return false;
0589         } else if (!rule->uid_op(cred->euid, rule->uid))
0590             return false;
0591     }
0592     if ((rule->flags & IMA_GID) && !rule->gid_op(cred->gid, rule->gid))
0593         return false;
0594     if (rule->flags & IMA_EGID) {
0595         if (has_capability_noaudit(current, CAP_SETGID)) {
0596             if (!rule->gid_op(cred->egid, rule->gid)
0597                 && !rule->gid_op(cred->sgid, rule->gid)
0598                 && !rule->gid_op(cred->gid, rule->gid))
0599                 return false;
0600         } else if (!rule->gid_op(cred->egid, rule->gid))
0601             return false;
0602     }
0603     if ((rule->flags & IMA_FOWNER) &&
0604         !rule->fowner_op(i_uid_into_mnt(mnt_userns, inode), rule->fowner))
0605         return false;
0606     if ((rule->flags & IMA_FGROUP) &&
0607         !rule->fgroup_op(i_gid_into_mnt(mnt_userns, inode), rule->fgroup))
0608         return false;
0609     for (i = 0; i < MAX_LSM_RULES; i++) {
0610         int rc = 0;
0611         u32 osid;
0612 
0613         if (!rule->lsm[i].rule) {
0614             if (!rule->lsm[i].args_p)
0615                 continue;
0616             else
0617                 return false;
0618         }
0619         switch (i) {
0620         case LSM_OBJ_USER:
0621         case LSM_OBJ_ROLE:
0622         case LSM_OBJ_TYPE:
0623             security_inode_getsecid(inode, &osid);
0624             rc = ima_filter_rule_match(osid, rule->lsm[i].type,
0625                            Audit_equal,
0626                            rule->lsm[i].rule);
0627             break;
0628         case LSM_SUBJ_USER:
0629         case LSM_SUBJ_ROLE:
0630         case LSM_SUBJ_TYPE:
0631             rc = ima_filter_rule_match(secid, rule->lsm[i].type,
0632                            Audit_equal,
0633                            rule->lsm[i].rule);
0634             break;
0635         default:
0636             break;
0637         }
0638         if (!rc)
0639             return false;
0640     }
0641     return true;
0642 }
0643 
0644 /*
0645  * In addition to knowing that we need to appraise the file in general,
0646  * we need to differentiate between calling hooks, for hook specific rules.
0647  */
0648 static int get_subaction(struct ima_rule_entry *rule, enum ima_hooks func)
0649 {
0650     if (!(rule->flags & IMA_FUNC))
0651         return IMA_FILE_APPRAISE;
0652 
0653     switch (func) {
0654     case MMAP_CHECK:
0655         return IMA_MMAP_APPRAISE;
0656     case BPRM_CHECK:
0657         return IMA_BPRM_APPRAISE;
0658     case CREDS_CHECK:
0659         return IMA_CREDS_APPRAISE;
0660     case FILE_CHECK:
0661     case POST_SETATTR:
0662         return IMA_FILE_APPRAISE;
0663     case MODULE_CHECK ... MAX_CHECK - 1:
0664     default:
0665         return IMA_READ_APPRAISE;
0666     }
0667 }
0668 
0669 /**
0670  * ima_match_policy - decision based on LSM and other conditions
0671  * @mnt_userns: user namespace of the mount the inode was found from
0672  * @inode: pointer to an inode for which the policy decision is being made
0673  * @cred: pointer to a credentials structure for which the policy decision is
0674  *        being made
0675  * @secid: LSM secid of the task to be validated
0676  * @func: IMA hook identifier
0677  * @mask: requested action (MAY_READ | MAY_WRITE | MAY_APPEND | MAY_EXEC)
0678  * @pcr: set the pcr to extend
0679  * @template_desc: the template that should be used for this rule
0680  * @func_data: func specific data, may be NULL
0681  * @allowed_algos: allowlist of hash algorithms for the IMA xattr
0682  *
0683  * Measure decision based on func/mask/fsmagic and LSM(subj/obj/type)
0684  * conditions.
0685  *
0686  * Since the IMA policy may be updated multiple times we need to lock the
0687  * list when walking it.  Reads are many orders of magnitude more numerous
0688  * than writes so ima_match_policy() is classical RCU candidate.
0689  */
0690 int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode,
0691              const struct cred *cred, u32 secid, enum ima_hooks func,
0692              int mask, int flags, int *pcr,
0693              struct ima_template_desc **template_desc,
0694              const char *func_data, unsigned int *allowed_algos)
0695 {
0696     struct ima_rule_entry *entry;
0697     int action = 0, actmask = flags | (flags << 1);
0698     struct list_head *ima_rules_tmp;
0699 
0700     if (template_desc && !*template_desc)
0701         *template_desc = ima_template_desc_current();
0702 
0703     rcu_read_lock();
0704     ima_rules_tmp = rcu_dereference(ima_rules);
0705     list_for_each_entry_rcu(entry, ima_rules_tmp, list) {
0706 
0707         if (!(entry->action & actmask))
0708             continue;
0709 
0710         if (!ima_match_rules(entry, mnt_userns, inode, cred, secid,
0711                      func, mask, func_data))
0712             continue;
0713 
0714         action |= entry->flags & IMA_NONACTION_FLAGS;
0715 
0716         action |= entry->action & IMA_DO_MASK;
0717         if (entry->action & IMA_APPRAISE) {
0718             action |= get_subaction(entry, func);
0719             action &= ~IMA_HASH;
0720             if (ima_fail_unverifiable_sigs)
0721                 action |= IMA_FAIL_UNVERIFIABLE_SIGS;
0722 
0723             if (allowed_algos &&
0724                 entry->flags & IMA_VALIDATE_ALGOS)
0725                 *allowed_algos = entry->allowed_algos;
0726         }
0727 
0728         if (entry->action & IMA_DO_MASK)
0729             actmask &= ~(entry->action | entry->action << 1);
0730         else
0731             actmask &= ~(entry->action | entry->action >> 1);
0732 
0733         if ((pcr) && (entry->flags & IMA_PCR))
0734             *pcr = entry->pcr;
0735 
0736         if (template_desc && entry->template)
0737             *template_desc = entry->template;
0738 
0739         if (!actmask)
0740             break;
0741     }
0742     rcu_read_unlock();
0743 
0744     return action;
0745 }
0746 
0747 /**
0748  * ima_update_policy_flags() - Update global IMA variables
0749  *
0750  * Update ima_policy_flag and ima_setxattr_allowed_hash_algorithms
0751  * based on the currently loaded policy.
0752  *
0753  * With ima_policy_flag, the decision to short circuit out of a function
0754  * or not call the function in the first place can be made earlier.
0755  *
0756  * With ima_setxattr_allowed_hash_algorithms, the policy can restrict the
0757  * set of hash algorithms accepted when updating the security.ima xattr of
0758  * a file.
0759  *
0760  * Context: called after a policy update and at system initialization.
0761  */
0762 void ima_update_policy_flags(void)
0763 {
0764     struct ima_rule_entry *entry;
0765     int new_policy_flag = 0;
0766     struct list_head *ima_rules_tmp;
0767 
0768     rcu_read_lock();
0769     ima_rules_tmp = rcu_dereference(ima_rules);
0770     list_for_each_entry_rcu(entry, ima_rules_tmp, list) {
0771         /*
0772          * SETXATTR_CHECK rules do not implement a full policy check
0773          * because rule checking would probably have an important
0774          * performance impact on setxattr(). As a consequence, only one
0775          * SETXATTR_CHECK can be active at a given time.
0776          * Because we want to preserve that property, we set out to use
0777          * atomic_cmpxchg. Either:
0778          * - the atomic was non-zero: a setxattr hash policy is
0779          *   already enforced, we do nothing
0780          * - the atomic was zero: no setxattr policy was set, enable
0781          *   the setxattr hash policy
0782          */
0783         if (entry->func == SETXATTR_CHECK) {
0784             atomic_cmpxchg(&ima_setxattr_allowed_hash_algorithms,
0785                        0, entry->allowed_algos);
0786             /* SETXATTR_CHECK doesn't impact ima_policy_flag */
0787             continue;
0788         }
0789 
0790         if (entry->action & IMA_DO_MASK)
0791             new_policy_flag |= entry->action;
0792     }
0793     rcu_read_unlock();
0794 
0795     ima_appraise |= (build_ima_appraise | temp_ima_appraise);
0796     if (!ima_appraise)
0797         new_policy_flag &= ~IMA_APPRAISE;
0798 
0799     ima_policy_flag = new_policy_flag;
0800 }
0801 
0802 static int ima_appraise_flag(enum ima_hooks func)
0803 {
0804     if (func == MODULE_CHECK)
0805         return IMA_APPRAISE_MODULES;
0806     else if (func == FIRMWARE_CHECK)
0807         return IMA_APPRAISE_FIRMWARE;
0808     else if (func == POLICY_CHECK)
0809         return IMA_APPRAISE_POLICY;
0810     else if (func == KEXEC_KERNEL_CHECK)
0811         return IMA_APPRAISE_KEXEC;
0812     return 0;
0813 }
0814 
0815 static void add_rules(struct ima_rule_entry *entries, int count,
0816               enum policy_rule_list policy_rule)
0817 {
0818     int i = 0;
0819 
0820     for (i = 0; i < count; i++) {
0821         struct ima_rule_entry *entry;
0822 
0823         if (policy_rule & IMA_DEFAULT_POLICY)
0824             list_add_tail(&entries[i].list, &ima_default_rules);
0825 
0826         if (policy_rule & IMA_CUSTOM_POLICY) {
0827             entry = kmemdup(&entries[i], sizeof(*entry),
0828                     GFP_KERNEL);
0829             if (!entry)
0830                 continue;
0831 
0832             list_add_tail(&entry->list, &ima_policy_rules);
0833         }
0834         if (entries[i].action == APPRAISE) {
0835             if (entries != build_appraise_rules)
0836                 temp_ima_appraise |=
0837                     ima_appraise_flag(entries[i].func);
0838             else
0839                 build_ima_appraise |=
0840                     ima_appraise_flag(entries[i].func);
0841         }
0842     }
0843 }
0844 
0845 static int ima_parse_rule(char *rule, struct ima_rule_entry *entry);
0846 
0847 static int __init ima_init_arch_policy(void)
0848 {
0849     const char * const *arch_rules;
0850     const char * const *rules;
0851     int arch_entries = 0;
0852     int i = 0;
0853 
0854     arch_rules = arch_get_ima_policy();
0855     if (!arch_rules)
0856         return arch_entries;
0857 
0858     /* Get number of rules */
0859     for (rules = arch_rules; *rules != NULL; rules++)
0860         arch_entries++;
0861 
0862     arch_policy_entry = kcalloc(arch_entries + 1,
0863                     sizeof(*arch_policy_entry), GFP_KERNEL);
0864     if (!arch_policy_entry)
0865         return 0;
0866 
0867     /* Convert each policy string rules to struct ima_rule_entry format */
0868     for (rules = arch_rules, i = 0; *rules != NULL; rules++) {
0869         char rule[255];
0870         int result;
0871 
0872         result = strscpy(rule, *rules, sizeof(rule));
0873 
0874         INIT_LIST_HEAD(&arch_policy_entry[i].list);
0875         result = ima_parse_rule(rule, &arch_policy_entry[i]);
0876         if (result) {
0877             pr_warn("Skipping unknown architecture policy rule: %s\n",
0878                 rule);
0879             memset(&arch_policy_entry[i], 0,
0880                    sizeof(*arch_policy_entry));
0881             continue;
0882         }
0883         i++;
0884     }
0885     return i;
0886 }
0887 
0888 /**
0889  * ima_init_policy - initialize the default measure rules.
0890  *
0891  * ima_rules points to either the ima_default_rules or the new ima_policy_rules.
0892  */
0893 void __init ima_init_policy(void)
0894 {
0895     int build_appraise_entries, arch_entries;
0896 
0897     /* if !ima_policy, we load NO default rules */
0898     if (ima_policy)
0899         add_rules(dont_measure_rules, ARRAY_SIZE(dont_measure_rules),
0900               IMA_DEFAULT_POLICY);
0901 
0902     switch (ima_policy) {
0903     case ORIGINAL_TCB:
0904         add_rules(original_measurement_rules,
0905               ARRAY_SIZE(original_measurement_rules),
0906               IMA_DEFAULT_POLICY);
0907         break;
0908     case DEFAULT_TCB:
0909         add_rules(default_measurement_rules,
0910               ARRAY_SIZE(default_measurement_rules),
0911               IMA_DEFAULT_POLICY);
0912         break;
0913     default:
0914         break;
0915     }
0916 
0917     /*
0918      * Based on runtime secure boot flags, insert arch specific measurement
0919      * and appraise rules requiring file signatures for both the initial
0920      * and custom policies, prior to other appraise rules.
0921      * (Highest priority)
0922      */
0923     arch_entries = ima_init_arch_policy();
0924     if (!arch_entries)
0925         pr_info("No architecture policies found\n");
0926     else
0927         add_rules(arch_policy_entry, arch_entries,
0928               IMA_DEFAULT_POLICY | IMA_CUSTOM_POLICY);
0929 
0930     /*
0931      * Insert the builtin "secure_boot" policy rules requiring file
0932      * signatures, prior to other appraise rules.
0933      */
0934     if (ima_use_secure_boot)
0935         add_rules(secure_boot_rules, ARRAY_SIZE(secure_boot_rules),
0936               IMA_DEFAULT_POLICY);
0937 
0938     /*
0939      * Insert the build time appraise rules requiring file signatures
0940      * for both the initial and custom policies, prior to other appraise
0941      * rules. As the secure boot rules includes all of the build time
0942      * rules, include either one or the other set of rules, but not both.
0943      */
0944     build_appraise_entries = ARRAY_SIZE(build_appraise_rules);
0945     if (build_appraise_entries) {
0946         if (ima_use_secure_boot)
0947             add_rules(build_appraise_rules, build_appraise_entries,
0948                   IMA_CUSTOM_POLICY);
0949         else
0950             add_rules(build_appraise_rules, build_appraise_entries,
0951                   IMA_DEFAULT_POLICY | IMA_CUSTOM_POLICY);
0952     }
0953 
0954     if (ima_use_appraise_tcb)
0955         add_rules(default_appraise_rules,
0956               ARRAY_SIZE(default_appraise_rules),
0957               IMA_DEFAULT_POLICY);
0958 
0959     if (ima_use_critical_data)
0960         add_rules(critical_data_rules,
0961               ARRAY_SIZE(critical_data_rules),
0962               IMA_DEFAULT_POLICY);
0963 
0964     atomic_set(&ima_setxattr_allowed_hash_algorithms, 0);
0965 
0966     ima_update_policy_flags();
0967 }
0968 
0969 /* Make sure we have a valid policy, at least containing some rules. */
0970 int ima_check_policy(void)
0971 {
0972     if (list_empty(&ima_temp_rules))
0973         return -EINVAL;
0974     return 0;
0975 }
0976 
0977 /**
0978  * ima_update_policy - update default_rules with new measure rules
0979  *
0980  * Called on file .release to update the default rules with a complete new
0981  * policy.  What we do here is to splice ima_policy_rules and ima_temp_rules so
0982  * they make a queue.  The policy may be updated multiple times and this is the
0983  * RCU updater.
0984  *
0985  * Policy rules are never deleted so ima_policy_flag gets zeroed only once when
0986  * we switch from the default policy to user defined.
0987  */
0988 void ima_update_policy(void)
0989 {
0990     struct list_head *policy = &ima_policy_rules;
0991 
0992     list_splice_tail_init_rcu(&ima_temp_rules, policy, synchronize_rcu);
0993 
0994     if (ima_rules != (struct list_head __rcu *)policy) {
0995         ima_policy_flag = 0;
0996 
0997         rcu_assign_pointer(ima_rules, policy);
0998         /*
0999          * IMA architecture specific policy rules are specified
1000          * as strings and converted to an array of ima_entry_rules
1001          * on boot.  After loading a custom policy, free the
1002          * architecture specific rules stored as an array.
1003          */
1004         kfree(arch_policy_entry);
1005     }
1006     ima_update_policy_flags();
1007 
1008     /* Custom IMA policy has been loaded */
1009     ima_process_queued_keys();
1010 }
1011 
1012 /* Keep the enumeration in sync with the policy_tokens! */
1013 enum policy_opt {
1014     Opt_measure, Opt_dont_measure,
1015     Opt_appraise, Opt_dont_appraise,
1016     Opt_audit, Opt_hash, Opt_dont_hash,
1017     Opt_obj_user, Opt_obj_role, Opt_obj_type,
1018     Opt_subj_user, Opt_subj_role, Opt_subj_type,
1019     Opt_func, Opt_mask, Opt_fsmagic, Opt_fsname, Opt_fsuuid,
1020     Opt_uid_eq, Opt_euid_eq, Opt_gid_eq, Opt_egid_eq,
1021     Opt_fowner_eq, Opt_fgroup_eq,
1022     Opt_uid_gt, Opt_euid_gt, Opt_gid_gt, Opt_egid_gt,
1023     Opt_fowner_gt, Opt_fgroup_gt,
1024     Opt_uid_lt, Opt_euid_lt, Opt_gid_lt, Opt_egid_lt,
1025     Opt_fowner_lt, Opt_fgroup_lt,
1026     Opt_digest_type,
1027     Opt_appraise_type, Opt_appraise_flag, Opt_appraise_algos,
1028     Opt_permit_directio, Opt_pcr, Opt_template, Opt_keyrings,
1029     Opt_label, Opt_err
1030 };
1031 
1032 static const match_table_t policy_tokens = {
1033     {Opt_measure, "measure"},
1034     {Opt_dont_measure, "dont_measure"},
1035     {Opt_appraise, "appraise"},
1036     {Opt_dont_appraise, "dont_appraise"},
1037     {Opt_audit, "audit"},
1038     {Opt_hash, "hash"},
1039     {Opt_dont_hash, "dont_hash"},
1040     {Opt_obj_user, "obj_user=%s"},
1041     {Opt_obj_role, "obj_role=%s"},
1042     {Opt_obj_type, "obj_type=%s"},
1043     {Opt_subj_user, "subj_user=%s"},
1044     {Opt_subj_role, "subj_role=%s"},
1045     {Opt_subj_type, "subj_type=%s"},
1046     {Opt_func, "func=%s"},
1047     {Opt_mask, "mask=%s"},
1048     {Opt_fsmagic, "fsmagic=%s"},
1049     {Opt_fsname, "fsname=%s"},
1050     {Opt_fsuuid, "fsuuid=%s"},
1051     {Opt_uid_eq, "uid=%s"},
1052     {Opt_euid_eq, "euid=%s"},
1053     {Opt_gid_eq, "gid=%s"},
1054     {Opt_egid_eq, "egid=%s"},
1055     {Opt_fowner_eq, "fowner=%s"},
1056     {Opt_fgroup_eq, "fgroup=%s"},
1057     {Opt_uid_gt, "uid>%s"},
1058     {Opt_euid_gt, "euid>%s"},
1059     {Opt_gid_gt, "gid>%s"},
1060     {Opt_egid_gt, "egid>%s"},
1061     {Opt_fowner_gt, "fowner>%s"},
1062     {Opt_fgroup_gt, "fgroup>%s"},
1063     {Opt_uid_lt, "uid<%s"},
1064     {Opt_euid_lt, "euid<%s"},
1065     {Opt_gid_lt, "gid<%s"},
1066     {Opt_egid_lt, "egid<%s"},
1067     {Opt_fowner_lt, "fowner<%s"},
1068     {Opt_fgroup_lt, "fgroup<%s"},
1069     {Opt_digest_type, "digest_type=%s"},
1070     {Opt_appraise_type, "appraise_type=%s"},
1071     {Opt_appraise_flag, "appraise_flag=%s"},
1072     {Opt_appraise_algos, "appraise_algos=%s"},
1073     {Opt_permit_directio, "permit_directio"},
1074     {Opt_pcr, "pcr=%s"},
1075     {Opt_template, "template=%s"},
1076     {Opt_keyrings, "keyrings=%s"},
1077     {Opt_label, "label=%s"},
1078     {Opt_err, NULL}
1079 };
1080 
1081 static int ima_lsm_rule_init(struct ima_rule_entry *entry,
1082                  substring_t *args, int lsm_rule, int audit_type)
1083 {
1084     int result;
1085 
1086     if (entry->lsm[lsm_rule].rule)
1087         return -EINVAL;
1088 
1089     entry->lsm[lsm_rule].args_p = match_strdup(args);
1090     if (!entry->lsm[lsm_rule].args_p)
1091         return -ENOMEM;
1092 
1093     entry->lsm[lsm_rule].type = audit_type;
1094     result = ima_filter_rule_init(entry->lsm[lsm_rule].type, Audit_equal,
1095                       entry->lsm[lsm_rule].args_p,
1096                       &entry->lsm[lsm_rule].rule);
1097     if (!entry->lsm[lsm_rule].rule) {
1098         pr_warn("rule for LSM \'%s\' is undefined\n",
1099             entry->lsm[lsm_rule].args_p);
1100 
1101         if (ima_rules == (struct list_head __rcu *)(&ima_default_rules)) {
1102             kfree(entry->lsm[lsm_rule].args_p);
1103             entry->lsm[lsm_rule].args_p = NULL;
1104             result = -EINVAL;
1105         } else
1106             result = 0;
1107     }
1108 
1109     return result;
1110 }
1111 
1112 static void ima_log_string_op(struct audit_buffer *ab, char *key, char *value,
1113                   enum policy_opt rule_operator)
1114 {
1115     if (!ab)
1116         return;
1117 
1118     switch (rule_operator) {
1119     case Opt_uid_gt:
1120     case Opt_euid_gt:
1121     case Opt_gid_gt:
1122     case Opt_egid_gt:
1123     case Opt_fowner_gt:
1124     case Opt_fgroup_gt:
1125         audit_log_format(ab, "%s>", key);
1126         break;
1127     case Opt_uid_lt:
1128     case Opt_euid_lt:
1129     case Opt_gid_lt:
1130     case Opt_egid_lt:
1131     case Opt_fowner_lt:
1132     case Opt_fgroup_lt:
1133         audit_log_format(ab, "%s<", key);
1134         break;
1135     default:
1136         audit_log_format(ab, "%s=", key);
1137     }
1138     audit_log_format(ab, "%s ", value);
1139 }
1140 static void ima_log_string(struct audit_buffer *ab, char *key, char *value)
1141 {
1142     ima_log_string_op(ab, key, value, Opt_err);
1143 }
1144 
1145 /*
1146  * Validating the appended signature included in the measurement list requires
1147  * the file hash calculated without the appended signature (i.e., the 'd-modsig'
1148  * field). Therefore, notify the user if they have the 'modsig' field but not
1149  * the 'd-modsig' field in the template.
1150  */
1151 static void check_template_modsig(const struct ima_template_desc *template)
1152 {
1153 #define MSG "template with 'modsig' field also needs 'd-modsig' field\n"
1154     bool has_modsig, has_dmodsig;
1155     static bool checked;
1156     int i;
1157 
1158     /* We only need to notify the user once. */
1159     if (checked)
1160         return;
1161 
1162     has_modsig = has_dmodsig = false;
1163     for (i = 0; i < template->num_fields; i++) {
1164         if (!strcmp(template->fields[i]->field_id, "modsig"))
1165             has_modsig = true;
1166         else if (!strcmp(template->fields[i]->field_id, "d-modsig"))
1167             has_dmodsig = true;
1168     }
1169 
1170     if (has_modsig && !has_dmodsig)
1171         pr_notice(MSG);
1172 
1173     checked = true;
1174 #undef MSG
1175 }
1176 
1177 /*
1178  * Warn if the template does not contain the given field.
1179  */
1180 static void check_template_field(const struct ima_template_desc *template,
1181                  const char *field, const char *msg)
1182 {
1183     int i;
1184 
1185     for (i = 0; i < template->num_fields; i++)
1186         if (!strcmp(template->fields[i]->field_id, field))
1187             return;
1188 
1189     pr_notice_once("%s", msg);
1190 }
1191 
1192 static bool ima_validate_rule(struct ima_rule_entry *entry)
1193 {
1194     /* Ensure that the action is set and is compatible with the flags */
1195     if (entry->action == UNKNOWN)
1196         return false;
1197 
1198     if (entry->action != MEASURE && entry->flags & IMA_PCR)
1199         return false;
1200 
1201     if (entry->action != APPRAISE &&
1202         entry->flags & (IMA_DIGSIG_REQUIRED | IMA_MODSIG_ALLOWED |
1203                 IMA_CHECK_BLACKLIST | IMA_VALIDATE_ALGOS))
1204         return false;
1205 
1206     /*
1207      * The IMA_FUNC bit must be set if and only if there's a valid hook
1208      * function specified, and vice versa. Enforcing this property allows
1209      * for the NONE case below to validate a rule without an explicit hook
1210      * function.
1211      */
1212     if (((entry->flags & IMA_FUNC) && entry->func == NONE) ||
1213         (!(entry->flags & IMA_FUNC) && entry->func != NONE))
1214         return false;
1215 
1216     /*
1217      * Ensure that the hook function is compatible with the other
1218      * components of the rule
1219      */
1220     switch (entry->func) {
1221     case NONE:
1222     case FILE_CHECK:
1223     case MMAP_CHECK:
1224     case BPRM_CHECK:
1225     case CREDS_CHECK:
1226     case POST_SETATTR:
1227     case FIRMWARE_CHECK:
1228     case POLICY_CHECK:
1229         if (entry->flags & ~(IMA_FUNC | IMA_MASK | IMA_FSMAGIC |
1230                      IMA_UID | IMA_FOWNER | IMA_FSUUID |
1231                      IMA_INMASK | IMA_EUID | IMA_PCR |
1232                      IMA_FSNAME | IMA_GID | IMA_EGID |
1233                      IMA_FGROUP | IMA_DIGSIG_REQUIRED |
1234                      IMA_PERMIT_DIRECTIO | IMA_VALIDATE_ALGOS |
1235                      IMA_VERITY_REQUIRED))
1236             return false;
1237 
1238         break;
1239     case MODULE_CHECK:
1240     case KEXEC_KERNEL_CHECK:
1241     case KEXEC_INITRAMFS_CHECK:
1242         if (entry->flags & ~(IMA_FUNC | IMA_MASK | IMA_FSMAGIC |
1243                      IMA_UID | IMA_FOWNER | IMA_FSUUID |
1244                      IMA_INMASK | IMA_EUID | IMA_PCR |
1245                      IMA_FSNAME | IMA_GID | IMA_EGID |
1246                      IMA_FGROUP | IMA_DIGSIG_REQUIRED |
1247                      IMA_PERMIT_DIRECTIO | IMA_MODSIG_ALLOWED |
1248                      IMA_CHECK_BLACKLIST | IMA_VALIDATE_ALGOS))
1249             return false;
1250 
1251         break;
1252     case KEXEC_CMDLINE:
1253         if (entry->action & ~(MEASURE | DONT_MEASURE))
1254             return false;
1255 
1256         if (entry->flags & ~(IMA_FUNC | IMA_FSMAGIC | IMA_UID |
1257                      IMA_FOWNER | IMA_FSUUID | IMA_EUID |
1258                      IMA_PCR | IMA_FSNAME | IMA_GID | IMA_EGID |
1259                      IMA_FGROUP))
1260             return false;
1261 
1262         break;
1263     case KEY_CHECK:
1264         if (entry->action & ~(MEASURE | DONT_MEASURE))
1265             return false;
1266 
1267         if (entry->flags & ~(IMA_FUNC | IMA_UID | IMA_GID | IMA_PCR |
1268                      IMA_KEYRINGS))
1269             return false;
1270 
1271         if (ima_rule_contains_lsm_cond(entry))
1272             return false;
1273 
1274         break;
1275     case CRITICAL_DATA:
1276         if (entry->action & ~(MEASURE | DONT_MEASURE))
1277             return false;
1278 
1279         if (entry->flags & ~(IMA_FUNC | IMA_UID | IMA_GID | IMA_PCR |
1280                      IMA_LABEL))
1281             return false;
1282 
1283         if (ima_rule_contains_lsm_cond(entry))
1284             return false;
1285 
1286         break;
1287     case SETXATTR_CHECK:
1288         /* any action other than APPRAISE is unsupported */
1289         if (entry->action != APPRAISE)
1290             return false;
1291 
1292         /* SETXATTR_CHECK requires an appraise_algos parameter */
1293         if (!(entry->flags & IMA_VALIDATE_ALGOS))
1294             return false;
1295 
1296         /*
1297          * full policies are not supported, they would have too
1298          * much of a performance impact
1299          */
1300         if (entry->flags & ~(IMA_FUNC | IMA_VALIDATE_ALGOS))
1301             return false;
1302 
1303         break;
1304     default:
1305         return false;
1306     }
1307 
1308     /* Ensure that combinations of flags are compatible with each other */
1309     if (entry->flags & IMA_CHECK_BLACKLIST &&
1310         !(entry->flags & IMA_MODSIG_ALLOWED))
1311         return false;
1312 
1313     /*
1314      * Unlike for regular IMA 'appraise' policy rules where security.ima
1315      * xattr may contain either a file hash or signature, the security.ima
1316      * xattr for fsverity must contain a file signature (sigv3).  Ensure
1317      * that 'appraise' rules for fsverity require file signatures by
1318      * checking the IMA_DIGSIG_REQUIRED flag is set.
1319      */
1320     if (entry->action == APPRAISE &&
1321         (entry->flags & IMA_VERITY_REQUIRED) &&
1322         !(entry->flags & IMA_DIGSIG_REQUIRED))
1323         return false;
1324 
1325     return true;
1326 }
1327 
1328 static unsigned int ima_parse_appraise_algos(char *arg)
1329 {
1330     unsigned int res = 0;
1331     int idx;
1332     char *token;
1333 
1334     while ((token = strsep(&arg, ",")) != NULL) {
1335         idx = match_string(hash_algo_name, HASH_ALGO__LAST, token);
1336 
1337         if (idx < 0) {
1338             pr_err("unknown hash algorithm \"%s\"",
1339                    token);
1340             return 0;
1341         }
1342 
1343         if (!crypto_has_alg(hash_algo_name[idx], 0, 0)) {
1344             pr_err("unavailable hash algorithm \"%s\", check your kernel configuration",
1345                    token);
1346             return 0;
1347         }
1348 
1349         /* Add the hash algorithm to the 'allowed' bitfield */
1350         res |= (1U << idx);
1351     }
1352 
1353     return res;
1354 }
1355 
1356 static int ima_parse_rule(char *rule, struct ima_rule_entry *entry)
1357 {
1358     struct audit_buffer *ab;
1359     char *from;
1360     char *p;
1361     bool eid_token; /* either euid or egid */
1362     struct ima_template_desc *template_desc;
1363     int result = 0;
1364 
1365     ab = integrity_audit_log_start(audit_context(), GFP_KERNEL,
1366                        AUDIT_INTEGRITY_POLICY_RULE);
1367 
1368     entry->uid = INVALID_UID;
1369     entry->gid = INVALID_GID;
1370     entry->fowner = INVALID_UID;
1371     entry->fgroup = INVALID_GID;
1372     entry->uid_op = &uid_eq;
1373     entry->gid_op = &gid_eq;
1374     entry->fowner_op = &uid_eq;
1375     entry->fgroup_op = &gid_eq;
1376     entry->action = UNKNOWN;
1377     while ((p = strsep(&rule, " \t")) != NULL) {
1378         substring_t args[MAX_OPT_ARGS];
1379         int token;
1380         unsigned long lnum;
1381 
1382         if (result < 0)
1383             break;
1384         if ((*p == '\0') || (*p == ' ') || (*p == '\t'))
1385             continue;
1386         token = match_token(p, policy_tokens, args);
1387         switch (token) {
1388         case Opt_measure:
1389             ima_log_string(ab, "action", "measure");
1390 
1391             if (entry->action != UNKNOWN)
1392                 result = -EINVAL;
1393 
1394             entry->action = MEASURE;
1395             break;
1396         case Opt_dont_measure:
1397             ima_log_string(ab, "action", "dont_measure");
1398 
1399             if (entry->action != UNKNOWN)
1400                 result = -EINVAL;
1401 
1402             entry->action = DONT_MEASURE;
1403             break;
1404         case Opt_appraise:
1405             ima_log_string(ab, "action", "appraise");
1406 
1407             if (entry->action != UNKNOWN)
1408                 result = -EINVAL;
1409 
1410             entry->action = APPRAISE;
1411             break;
1412         case Opt_dont_appraise:
1413             ima_log_string(ab, "action", "dont_appraise");
1414 
1415             if (entry->action != UNKNOWN)
1416                 result = -EINVAL;
1417 
1418             entry->action = DONT_APPRAISE;
1419             break;
1420         case Opt_audit:
1421             ima_log_string(ab, "action", "audit");
1422 
1423             if (entry->action != UNKNOWN)
1424                 result = -EINVAL;
1425 
1426             entry->action = AUDIT;
1427             break;
1428         case Opt_hash:
1429             ima_log_string(ab, "action", "hash");
1430 
1431             if (entry->action != UNKNOWN)
1432                 result = -EINVAL;
1433 
1434             entry->action = HASH;
1435             break;
1436         case Opt_dont_hash:
1437             ima_log_string(ab, "action", "dont_hash");
1438 
1439             if (entry->action != UNKNOWN)
1440                 result = -EINVAL;
1441 
1442             entry->action = DONT_HASH;
1443             break;
1444         case Opt_func:
1445             ima_log_string(ab, "func", args[0].from);
1446 
1447             if (entry->func)
1448                 result = -EINVAL;
1449 
1450             if (strcmp(args[0].from, "FILE_CHECK") == 0)
1451                 entry->func = FILE_CHECK;
1452             /* PATH_CHECK is for backwards compat */
1453             else if (strcmp(args[0].from, "PATH_CHECK") == 0)
1454                 entry->func = FILE_CHECK;
1455             else if (strcmp(args[0].from, "MODULE_CHECK") == 0)
1456                 entry->func = MODULE_CHECK;
1457             else if (strcmp(args[0].from, "FIRMWARE_CHECK") == 0)
1458                 entry->func = FIRMWARE_CHECK;
1459             else if ((strcmp(args[0].from, "FILE_MMAP") == 0)
1460                 || (strcmp(args[0].from, "MMAP_CHECK") == 0))
1461                 entry->func = MMAP_CHECK;
1462             else if (strcmp(args[0].from, "BPRM_CHECK") == 0)
1463                 entry->func = BPRM_CHECK;
1464             else if (strcmp(args[0].from, "CREDS_CHECK") == 0)
1465                 entry->func = CREDS_CHECK;
1466             else if (strcmp(args[0].from, "KEXEC_KERNEL_CHECK") ==
1467                  0)
1468                 entry->func = KEXEC_KERNEL_CHECK;
1469             else if (strcmp(args[0].from, "KEXEC_INITRAMFS_CHECK")
1470                  == 0)
1471                 entry->func = KEXEC_INITRAMFS_CHECK;
1472             else if (strcmp(args[0].from, "POLICY_CHECK") == 0)
1473                 entry->func = POLICY_CHECK;
1474             else if (strcmp(args[0].from, "KEXEC_CMDLINE") == 0)
1475                 entry->func = KEXEC_CMDLINE;
1476             else if (IS_ENABLED(CONFIG_IMA_MEASURE_ASYMMETRIC_KEYS) &&
1477                  strcmp(args[0].from, "KEY_CHECK") == 0)
1478                 entry->func = KEY_CHECK;
1479             else if (strcmp(args[0].from, "CRITICAL_DATA") == 0)
1480                 entry->func = CRITICAL_DATA;
1481             else if (strcmp(args[0].from, "SETXATTR_CHECK") == 0)
1482                 entry->func = SETXATTR_CHECK;
1483             else
1484                 result = -EINVAL;
1485             if (!result)
1486                 entry->flags |= IMA_FUNC;
1487             break;
1488         case Opt_mask:
1489             ima_log_string(ab, "mask", args[0].from);
1490 
1491             if (entry->mask)
1492                 result = -EINVAL;
1493 
1494             from = args[0].from;
1495             if (*from == '^')
1496                 from++;
1497 
1498             if ((strcmp(from, "MAY_EXEC")) == 0)
1499                 entry->mask = MAY_EXEC;
1500             else if (strcmp(from, "MAY_WRITE") == 0)
1501                 entry->mask = MAY_WRITE;
1502             else if (strcmp(from, "MAY_READ") == 0)
1503                 entry->mask = MAY_READ;
1504             else if (strcmp(from, "MAY_APPEND") == 0)
1505                 entry->mask = MAY_APPEND;
1506             else
1507                 result = -EINVAL;
1508             if (!result)
1509                 entry->flags |= (*args[0].from == '^')
1510                      ? IMA_INMASK : IMA_MASK;
1511             break;
1512         case Opt_fsmagic:
1513             ima_log_string(ab, "fsmagic", args[0].from);
1514 
1515             if (entry->fsmagic) {
1516                 result = -EINVAL;
1517                 break;
1518             }
1519 
1520             result = kstrtoul(args[0].from, 16, &entry->fsmagic);
1521             if (!result)
1522                 entry->flags |= IMA_FSMAGIC;
1523             break;
1524         case Opt_fsname:
1525             ima_log_string(ab, "fsname", args[0].from);
1526 
1527             entry->fsname = kstrdup(args[0].from, GFP_KERNEL);
1528             if (!entry->fsname) {
1529                 result = -ENOMEM;
1530                 break;
1531             }
1532             result = 0;
1533             entry->flags |= IMA_FSNAME;
1534             break;
1535         case Opt_keyrings:
1536             ima_log_string(ab, "keyrings", args[0].from);
1537 
1538             if (!IS_ENABLED(CONFIG_IMA_MEASURE_ASYMMETRIC_KEYS) ||
1539                 entry->keyrings) {
1540                 result = -EINVAL;
1541                 break;
1542             }
1543 
1544             entry->keyrings = ima_alloc_rule_opt_list(args);
1545             if (IS_ERR(entry->keyrings)) {
1546                 result = PTR_ERR(entry->keyrings);
1547                 entry->keyrings = NULL;
1548                 break;
1549             }
1550 
1551             entry->flags |= IMA_KEYRINGS;
1552             break;
1553         case Opt_label:
1554             ima_log_string(ab, "label", args[0].from);
1555 
1556             if (entry->label) {
1557                 result = -EINVAL;
1558                 break;
1559             }
1560 
1561             entry->label = ima_alloc_rule_opt_list(args);
1562             if (IS_ERR(entry->label)) {
1563                 result = PTR_ERR(entry->label);
1564                 entry->label = NULL;
1565                 break;
1566             }
1567 
1568             entry->flags |= IMA_LABEL;
1569             break;
1570         case Opt_fsuuid:
1571             ima_log_string(ab, "fsuuid", args[0].from);
1572 
1573             if (!uuid_is_null(&entry->fsuuid)) {
1574                 result = -EINVAL;
1575                 break;
1576             }
1577 
1578             result = uuid_parse(args[0].from, &entry->fsuuid);
1579             if (!result)
1580                 entry->flags |= IMA_FSUUID;
1581             break;
1582         case Opt_uid_gt:
1583         case Opt_euid_gt:
1584             entry->uid_op = &uid_gt;
1585             fallthrough;
1586         case Opt_uid_lt:
1587         case Opt_euid_lt:
1588             if ((token == Opt_uid_lt) || (token == Opt_euid_lt))
1589                 entry->uid_op = &uid_lt;
1590             fallthrough;
1591         case Opt_uid_eq:
1592         case Opt_euid_eq:
1593             eid_token = (token == Opt_euid_eq) ||
1594                     (token == Opt_euid_gt) ||
1595                     (token == Opt_euid_lt);
1596 
1597             ima_log_string_op(ab, eid_token ? "euid" : "uid",
1598                       args[0].from, token);
1599 
1600             if (uid_valid(entry->uid)) {
1601                 result = -EINVAL;
1602                 break;
1603             }
1604 
1605             result = kstrtoul(args[0].from, 10, &lnum);
1606             if (!result) {
1607                 entry->uid = make_kuid(current_user_ns(),
1608                                (uid_t) lnum);
1609                 if (!uid_valid(entry->uid) ||
1610                     (uid_t)lnum != lnum)
1611                     result = -EINVAL;
1612                 else
1613                     entry->flags |= eid_token
1614                         ? IMA_EUID : IMA_UID;
1615             }
1616             break;
1617         case Opt_gid_gt:
1618         case Opt_egid_gt:
1619             entry->gid_op = &gid_gt;
1620             fallthrough;
1621         case Opt_gid_lt:
1622         case Opt_egid_lt:
1623             if ((token == Opt_gid_lt) || (token == Opt_egid_lt))
1624                 entry->gid_op = &gid_lt;
1625             fallthrough;
1626         case Opt_gid_eq:
1627         case Opt_egid_eq:
1628             eid_token = (token == Opt_egid_eq) ||
1629                     (token == Opt_egid_gt) ||
1630                     (token == Opt_egid_lt);
1631 
1632             ima_log_string_op(ab, eid_token ? "egid" : "gid",
1633                       args[0].from, token);
1634 
1635             if (gid_valid(entry->gid)) {
1636                 result = -EINVAL;
1637                 break;
1638             }
1639 
1640             result = kstrtoul(args[0].from, 10, &lnum);
1641             if (!result) {
1642                 entry->gid = make_kgid(current_user_ns(),
1643                                (gid_t)lnum);
1644                 if (!gid_valid(entry->gid) ||
1645                     (((gid_t)lnum) != lnum))
1646                     result = -EINVAL;
1647                 else
1648                     entry->flags |= eid_token
1649                         ? IMA_EGID : IMA_GID;
1650             }
1651             break;
1652         case Opt_fowner_gt:
1653             entry->fowner_op = &uid_gt;
1654             fallthrough;
1655         case Opt_fowner_lt:
1656             if (token == Opt_fowner_lt)
1657                 entry->fowner_op = &uid_lt;
1658             fallthrough;
1659         case Opt_fowner_eq:
1660             ima_log_string_op(ab, "fowner", args[0].from, token);
1661 
1662             if (uid_valid(entry->fowner)) {
1663                 result = -EINVAL;
1664                 break;
1665             }
1666 
1667             result = kstrtoul(args[0].from, 10, &lnum);
1668             if (!result) {
1669                 entry->fowner = make_kuid(current_user_ns(),
1670                               (uid_t)lnum);
1671                 if (!uid_valid(entry->fowner) ||
1672                     (((uid_t)lnum) != lnum))
1673                     result = -EINVAL;
1674                 else
1675                     entry->flags |= IMA_FOWNER;
1676             }
1677             break;
1678         case Opt_fgroup_gt:
1679             entry->fgroup_op = &gid_gt;
1680             fallthrough;
1681         case Opt_fgroup_lt:
1682             if (token == Opt_fgroup_lt)
1683                 entry->fgroup_op = &gid_lt;
1684             fallthrough;
1685         case Opt_fgroup_eq:
1686             ima_log_string_op(ab, "fgroup", args[0].from, token);
1687 
1688             if (gid_valid(entry->fgroup)) {
1689                 result = -EINVAL;
1690                 break;
1691             }
1692 
1693             result = kstrtoul(args[0].from, 10, &lnum);
1694             if (!result) {
1695                 entry->fgroup = make_kgid(current_user_ns(),
1696                               (gid_t)lnum);
1697                 if (!gid_valid(entry->fgroup) ||
1698                     (((gid_t)lnum) != lnum))
1699                     result = -EINVAL;
1700                 else
1701                     entry->flags |= IMA_FGROUP;
1702             }
1703             break;
1704         case Opt_obj_user:
1705             ima_log_string(ab, "obj_user", args[0].from);
1706             result = ima_lsm_rule_init(entry, args,
1707                            LSM_OBJ_USER,
1708                            AUDIT_OBJ_USER);
1709             break;
1710         case Opt_obj_role:
1711             ima_log_string(ab, "obj_role", args[0].from);
1712             result = ima_lsm_rule_init(entry, args,
1713                            LSM_OBJ_ROLE,
1714                            AUDIT_OBJ_ROLE);
1715             break;
1716         case Opt_obj_type:
1717             ima_log_string(ab, "obj_type", args[0].from);
1718             result = ima_lsm_rule_init(entry, args,
1719                            LSM_OBJ_TYPE,
1720                            AUDIT_OBJ_TYPE);
1721             break;
1722         case Opt_subj_user:
1723             ima_log_string(ab, "subj_user", args[0].from);
1724             result = ima_lsm_rule_init(entry, args,
1725                            LSM_SUBJ_USER,
1726                            AUDIT_SUBJ_USER);
1727             break;
1728         case Opt_subj_role:
1729             ima_log_string(ab, "subj_role", args[0].from);
1730             result = ima_lsm_rule_init(entry, args,
1731                            LSM_SUBJ_ROLE,
1732                            AUDIT_SUBJ_ROLE);
1733             break;
1734         case Opt_subj_type:
1735             ima_log_string(ab, "subj_type", args[0].from);
1736             result = ima_lsm_rule_init(entry, args,
1737                            LSM_SUBJ_TYPE,
1738                            AUDIT_SUBJ_TYPE);
1739             break;
1740         case Opt_digest_type:
1741             ima_log_string(ab, "digest_type", args[0].from);
1742             if (entry->flags & IMA_DIGSIG_REQUIRED)
1743                 result = -EINVAL;
1744             else if ((strcmp(args[0].from, "verity")) == 0)
1745                 entry->flags |= IMA_VERITY_REQUIRED;
1746             else
1747                 result = -EINVAL;
1748             break;
1749         case Opt_appraise_type:
1750             ima_log_string(ab, "appraise_type", args[0].from);
1751 
1752             if ((strcmp(args[0].from, "imasig")) == 0) {
1753                 if (entry->flags & IMA_VERITY_REQUIRED)
1754                     result = -EINVAL;
1755                 else
1756                     entry->flags |= IMA_DIGSIG_REQUIRED;
1757             } else if (strcmp(args[0].from, "sigv3") == 0) {
1758                 /* Only fsverity supports sigv3 for now */
1759                 if (entry->flags & IMA_VERITY_REQUIRED)
1760                     entry->flags |= IMA_DIGSIG_REQUIRED;
1761                 else
1762                     result = -EINVAL;
1763             } else if (IS_ENABLED(CONFIG_IMA_APPRAISE_MODSIG) &&
1764                  strcmp(args[0].from, "imasig|modsig") == 0) {
1765                 if (entry->flags & IMA_VERITY_REQUIRED)
1766                     result = -EINVAL;
1767                 else
1768                     entry->flags |= IMA_DIGSIG_REQUIRED |
1769                         IMA_MODSIG_ALLOWED;
1770             } else {
1771                 result = -EINVAL;
1772             }
1773             break;
1774         case Opt_appraise_flag:
1775             ima_log_string(ab, "appraise_flag", args[0].from);
1776             if (IS_ENABLED(CONFIG_IMA_APPRAISE_MODSIG) &&
1777                 strstr(args[0].from, "blacklist"))
1778                 entry->flags |= IMA_CHECK_BLACKLIST;
1779             else
1780                 result = -EINVAL;
1781             break;
1782         case Opt_appraise_algos:
1783             ima_log_string(ab, "appraise_algos", args[0].from);
1784 
1785             if (entry->allowed_algos) {
1786                 result = -EINVAL;
1787                 break;
1788             }
1789 
1790             entry->allowed_algos =
1791                 ima_parse_appraise_algos(args[0].from);
1792             /* invalid or empty list of algorithms */
1793             if (!entry->allowed_algos) {
1794                 result = -EINVAL;
1795                 break;
1796             }
1797 
1798             entry->flags |= IMA_VALIDATE_ALGOS;
1799 
1800             break;
1801         case Opt_permit_directio:
1802             entry->flags |= IMA_PERMIT_DIRECTIO;
1803             break;
1804         case Opt_pcr:
1805             ima_log_string(ab, "pcr", args[0].from);
1806 
1807             result = kstrtoint(args[0].from, 10, &entry->pcr);
1808             if (result || INVALID_PCR(entry->pcr))
1809                 result = -EINVAL;
1810             else
1811                 entry->flags |= IMA_PCR;
1812 
1813             break;
1814         case Opt_template:
1815             ima_log_string(ab, "template", args[0].from);
1816             if (entry->action != MEASURE) {
1817                 result = -EINVAL;
1818                 break;
1819             }
1820             template_desc = lookup_template_desc(args[0].from);
1821             if (!template_desc || entry->template) {
1822                 result = -EINVAL;
1823                 break;
1824             }
1825 
1826             /*
1827              * template_desc_init_fields() does nothing if
1828              * the template is already initialised, so
1829              * it's safe to do this unconditionally
1830              */
1831             template_desc_init_fields(template_desc->fmt,
1832                          &(template_desc->fields),
1833                          &(template_desc->num_fields));
1834             entry->template = template_desc;
1835             break;
1836         case Opt_err:
1837             ima_log_string(ab, "UNKNOWN", p);
1838             result = -EINVAL;
1839             break;
1840         }
1841     }
1842     if (!result && !ima_validate_rule(entry))
1843         result = -EINVAL;
1844     else if (entry->action == APPRAISE)
1845         temp_ima_appraise |= ima_appraise_flag(entry->func);
1846 
1847     if (!result && entry->flags & IMA_MODSIG_ALLOWED) {
1848         template_desc = entry->template ? entry->template :
1849                           ima_template_desc_current();
1850         check_template_modsig(template_desc);
1851     }
1852 
1853     /* d-ngv2 template field recommended for unsigned fs-verity digests */
1854     if (!result && entry->action == MEASURE &&
1855         entry->flags & IMA_VERITY_REQUIRED) {
1856         template_desc = entry->template ? entry->template :
1857                           ima_template_desc_current();
1858         check_template_field(template_desc, "d-ngv2",
1859                      "verity rules should include d-ngv2");
1860     }
1861 
1862     audit_log_format(ab, "res=%d", !result);
1863     audit_log_end(ab);
1864     return result;
1865 }
1866 
1867 /**
1868  * ima_parse_add_rule - add a rule to ima_policy_rules
1869  * @rule - ima measurement policy rule
1870  *
1871  * Avoid locking by allowing just one writer at a time in ima_write_policy()
1872  * Returns the length of the rule parsed, an error code on failure
1873  */
1874 ssize_t ima_parse_add_rule(char *rule)
1875 {
1876     static const char op[] = "update_policy";
1877     char *p;
1878     struct ima_rule_entry *entry;
1879     ssize_t result, len;
1880     int audit_info = 0;
1881 
1882     p = strsep(&rule, "\n");
1883     len = strlen(p) + 1;
1884     p += strspn(p, " \t");
1885 
1886     if (*p == '#' || *p == '\0')
1887         return len;
1888 
1889     entry = kzalloc(sizeof(*entry), GFP_KERNEL);
1890     if (!entry) {
1891         integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
1892                     NULL, op, "-ENOMEM", -ENOMEM, audit_info);
1893         return -ENOMEM;
1894     }
1895 
1896     INIT_LIST_HEAD(&entry->list);
1897 
1898     result = ima_parse_rule(p, entry);
1899     if (result) {
1900         ima_free_rule(entry);
1901         integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
1902                     NULL, op, "invalid-policy", result,
1903                     audit_info);
1904         return result;
1905     }
1906 
1907     list_add_tail(&entry->list, &ima_temp_rules);
1908 
1909     return len;
1910 }
1911 
1912 /**
1913  * ima_delete_rules() called to cleanup invalid in-flight policy.
1914  * We don't need locking as we operate on the temp list, which is
1915  * different from the active one.  There is also only one user of
1916  * ima_delete_rules() at a time.
1917  */
1918 void ima_delete_rules(void)
1919 {
1920     struct ima_rule_entry *entry, *tmp;
1921 
1922     temp_ima_appraise = 0;
1923     list_for_each_entry_safe(entry, tmp, &ima_temp_rules, list) {
1924         list_del(&entry->list);
1925         ima_free_rule(entry);
1926     }
1927 }
1928 
1929 #define __ima_hook_stringify(func, str) (#func),
1930 
1931 const char *const func_tokens[] = {
1932     __ima_hooks(__ima_hook_stringify)
1933 };
1934 
1935 #ifdef  CONFIG_IMA_READ_POLICY
1936 enum {
1937     mask_exec = 0, mask_write, mask_read, mask_append
1938 };
1939 
1940 static const char *const mask_tokens[] = {
1941     "^MAY_EXEC",
1942     "^MAY_WRITE",
1943     "^MAY_READ",
1944     "^MAY_APPEND"
1945 };
1946 
1947 void *ima_policy_start(struct seq_file *m, loff_t *pos)
1948 {
1949     loff_t l = *pos;
1950     struct ima_rule_entry *entry;
1951     struct list_head *ima_rules_tmp;
1952 
1953     rcu_read_lock();
1954     ima_rules_tmp = rcu_dereference(ima_rules);
1955     list_for_each_entry_rcu(entry, ima_rules_tmp, list) {
1956         if (!l--) {
1957             rcu_read_unlock();
1958             return entry;
1959         }
1960     }
1961     rcu_read_unlock();
1962     return NULL;
1963 }
1964 
1965 void *ima_policy_next(struct seq_file *m, void *v, loff_t *pos)
1966 {
1967     struct ima_rule_entry *entry = v;
1968 
1969     rcu_read_lock();
1970     entry = list_entry_rcu(entry->list.next, struct ima_rule_entry, list);
1971     rcu_read_unlock();
1972     (*pos)++;
1973 
1974     return (&entry->list == &ima_default_rules ||
1975         &entry->list == &ima_policy_rules) ? NULL : entry;
1976 }
1977 
1978 void ima_policy_stop(struct seq_file *m, void *v)
1979 {
1980 }
1981 
1982 #define pt(token)   policy_tokens[token].pattern
1983 #define mt(token)   mask_tokens[token]
1984 
1985 /*
1986  * policy_func_show - display the ima_hooks policy rule
1987  */
1988 static void policy_func_show(struct seq_file *m, enum ima_hooks func)
1989 {
1990     if (func > 0 && func < MAX_CHECK)
1991         seq_printf(m, "func=%s ", func_tokens[func]);
1992     else
1993         seq_printf(m, "func=%d ", func);
1994 }
1995 
1996 static void ima_show_rule_opt_list(struct seq_file *m,
1997                    const struct ima_rule_opt_list *opt_list)
1998 {
1999     size_t i;
2000 
2001     for (i = 0; i < opt_list->count; i++)
2002         seq_printf(m, "%s%s", i ? "|" : "", opt_list->items[i]);
2003 }
2004 
2005 static void ima_policy_show_appraise_algos(struct seq_file *m,
2006                        unsigned int allowed_hashes)
2007 {
2008     int idx, list_size = 0;
2009 
2010     for (idx = 0; idx < HASH_ALGO__LAST; idx++) {
2011         if (!(allowed_hashes & (1U << idx)))
2012             continue;
2013 
2014         /* only add commas if the list contains multiple entries */
2015         if (list_size++)
2016             seq_puts(m, ",");
2017 
2018         seq_puts(m, hash_algo_name[idx]);
2019     }
2020 }
2021 
2022 int ima_policy_show(struct seq_file *m, void *v)
2023 {
2024     struct ima_rule_entry *entry = v;
2025     int i;
2026     char tbuf[64] = {0,};
2027     int offset = 0;
2028 
2029     rcu_read_lock();
2030 
2031     /* Do not print rules with inactive LSM labels */
2032     for (i = 0; i < MAX_LSM_RULES; i++) {
2033         if (entry->lsm[i].args_p && !entry->lsm[i].rule) {
2034             rcu_read_unlock();
2035             return 0;
2036         }
2037     }
2038 
2039     if (entry->action & MEASURE)
2040         seq_puts(m, pt(Opt_measure));
2041     if (entry->action & DONT_MEASURE)
2042         seq_puts(m, pt(Opt_dont_measure));
2043     if (entry->action & APPRAISE)
2044         seq_puts(m, pt(Opt_appraise));
2045     if (entry->action & DONT_APPRAISE)
2046         seq_puts(m, pt(Opt_dont_appraise));
2047     if (entry->action & AUDIT)
2048         seq_puts(m, pt(Opt_audit));
2049     if (entry->action & HASH)
2050         seq_puts(m, pt(Opt_hash));
2051     if (entry->action & DONT_HASH)
2052         seq_puts(m, pt(Opt_dont_hash));
2053 
2054     seq_puts(m, " ");
2055 
2056     if (entry->flags & IMA_FUNC)
2057         policy_func_show(m, entry->func);
2058 
2059     if ((entry->flags & IMA_MASK) || (entry->flags & IMA_INMASK)) {
2060         if (entry->flags & IMA_MASK)
2061             offset = 1;
2062         if (entry->mask & MAY_EXEC)
2063             seq_printf(m, pt(Opt_mask), mt(mask_exec) + offset);
2064         if (entry->mask & MAY_WRITE)
2065             seq_printf(m, pt(Opt_mask), mt(mask_write) + offset);
2066         if (entry->mask & MAY_READ)
2067             seq_printf(m, pt(Opt_mask), mt(mask_read) + offset);
2068         if (entry->mask & MAY_APPEND)
2069             seq_printf(m, pt(Opt_mask), mt(mask_append) + offset);
2070         seq_puts(m, " ");
2071     }
2072 
2073     if (entry->flags & IMA_FSMAGIC) {
2074         snprintf(tbuf, sizeof(tbuf), "0x%lx", entry->fsmagic);
2075         seq_printf(m, pt(Opt_fsmagic), tbuf);
2076         seq_puts(m, " ");
2077     }
2078 
2079     if (entry->flags & IMA_FSNAME) {
2080         snprintf(tbuf, sizeof(tbuf), "%s", entry->fsname);
2081         seq_printf(m, pt(Opt_fsname), tbuf);
2082         seq_puts(m, " ");
2083     }
2084 
2085     if (entry->flags & IMA_KEYRINGS) {
2086         seq_puts(m, "keyrings=");
2087         ima_show_rule_opt_list(m, entry->keyrings);
2088         seq_puts(m, " ");
2089     }
2090 
2091     if (entry->flags & IMA_LABEL) {
2092         seq_puts(m, "label=");
2093         ima_show_rule_opt_list(m, entry->label);
2094         seq_puts(m, " ");
2095     }
2096 
2097     if (entry->flags & IMA_PCR) {
2098         snprintf(tbuf, sizeof(tbuf), "%d", entry->pcr);
2099         seq_printf(m, pt(Opt_pcr), tbuf);
2100         seq_puts(m, " ");
2101     }
2102 
2103     if (entry->flags & IMA_FSUUID) {
2104         seq_printf(m, "fsuuid=%pU", &entry->fsuuid);
2105         seq_puts(m, " ");
2106     }
2107 
2108     if (entry->flags & IMA_UID) {
2109         snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->uid));
2110         if (entry->uid_op == &uid_gt)
2111             seq_printf(m, pt(Opt_uid_gt), tbuf);
2112         else if (entry->uid_op == &uid_lt)
2113             seq_printf(m, pt(Opt_uid_lt), tbuf);
2114         else
2115             seq_printf(m, pt(Opt_uid_eq), tbuf);
2116         seq_puts(m, " ");
2117     }
2118 
2119     if (entry->flags & IMA_EUID) {
2120         snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->uid));
2121         if (entry->uid_op == &uid_gt)
2122             seq_printf(m, pt(Opt_euid_gt), tbuf);
2123         else if (entry->uid_op == &uid_lt)
2124             seq_printf(m, pt(Opt_euid_lt), tbuf);
2125         else
2126             seq_printf(m, pt(Opt_euid_eq), tbuf);
2127         seq_puts(m, " ");
2128     }
2129 
2130     if (entry->flags & IMA_GID) {
2131         snprintf(tbuf, sizeof(tbuf), "%d", __kgid_val(entry->gid));
2132         if (entry->gid_op == &gid_gt)
2133             seq_printf(m, pt(Opt_gid_gt), tbuf);
2134         else if (entry->gid_op == &gid_lt)
2135             seq_printf(m, pt(Opt_gid_lt), tbuf);
2136         else
2137             seq_printf(m, pt(Opt_gid_eq), tbuf);
2138         seq_puts(m, " ");
2139     }
2140 
2141     if (entry->flags & IMA_EGID) {
2142         snprintf(tbuf, sizeof(tbuf), "%d", __kgid_val(entry->gid));
2143         if (entry->gid_op == &gid_gt)
2144             seq_printf(m, pt(Opt_egid_gt), tbuf);
2145         else if (entry->gid_op == &gid_lt)
2146             seq_printf(m, pt(Opt_egid_lt), tbuf);
2147         else
2148             seq_printf(m, pt(Opt_egid_eq), tbuf);
2149         seq_puts(m, " ");
2150     }
2151 
2152     if (entry->flags & IMA_FOWNER) {
2153         snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->fowner));
2154         if (entry->fowner_op == &uid_gt)
2155             seq_printf(m, pt(Opt_fowner_gt), tbuf);
2156         else if (entry->fowner_op == &uid_lt)
2157             seq_printf(m, pt(Opt_fowner_lt), tbuf);
2158         else
2159             seq_printf(m, pt(Opt_fowner_eq), tbuf);
2160         seq_puts(m, " ");
2161     }
2162 
2163     if (entry->flags & IMA_FGROUP) {
2164         snprintf(tbuf, sizeof(tbuf), "%d", __kgid_val(entry->fgroup));
2165         if (entry->fgroup_op == &gid_gt)
2166             seq_printf(m, pt(Opt_fgroup_gt), tbuf);
2167         else if (entry->fgroup_op == &gid_lt)
2168             seq_printf(m, pt(Opt_fgroup_lt), tbuf);
2169         else
2170             seq_printf(m, pt(Opt_fgroup_eq), tbuf);
2171         seq_puts(m, " ");
2172     }
2173 
2174     if (entry->flags & IMA_VALIDATE_ALGOS) {
2175         seq_puts(m, "appraise_algos=");
2176         ima_policy_show_appraise_algos(m, entry->allowed_algos);
2177         seq_puts(m, " ");
2178     }
2179 
2180     for (i = 0; i < MAX_LSM_RULES; i++) {
2181         if (entry->lsm[i].rule) {
2182             switch (i) {
2183             case LSM_OBJ_USER:
2184                 seq_printf(m, pt(Opt_obj_user),
2185                        entry->lsm[i].args_p);
2186                 break;
2187             case LSM_OBJ_ROLE:
2188                 seq_printf(m, pt(Opt_obj_role),
2189                        entry->lsm[i].args_p);
2190                 break;
2191             case LSM_OBJ_TYPE:
2192                 seq_printf(m, pt(Opt_obj_type),
2193                        entry->lsm[i].args_p);
2194                 break;
2195             case LSM_SUBJ_USER:
2196                 seq_printf(m, pt(Opt_subj_user),
2197                        entry->lsm[i].args_p);
2198                 break;
2199             case LSM_SUBJ_ROLE:
2200                 seq_printf(m, pt(Opt_subj_role),
2201                        entry->lsm[i].args_p);
2202                 break;
2203             case LSM_SUBJ_TYPE:
2204                 seq_printf(m, pt(Opt_subj_type),
2205                        entry->lsm[i].args_p);
2206                 break;
2207             }
2208             seq_puts(m, " ");
2209         }
2210     }
2211     if (entry->template)
2212         seq_printf(m, "template=%s ", entry->template->name);
2213     if (entry->flags & IMA_DIGSIG_REQUIRED) {
2214         if (entry->flags & IMA_VERITY_REQUIRED)
2215             seq_puts(m, "appraise_type=sigv3 ");
2216         else if (entry->flags & IMA_MODSIG_ALLOWED)
2217             seq_puts(m, "appraise_type=imasig|modsig ");
2218         else
2219             seq_puts(m, "appraise_type=imasig ");
2220     }
2221     if (entry->flags & IMA_VERITY_REQUIRED)
2222         seq_puts(m, "digest_type=verity ");
2223     if (entry->flags & IMA_CHECK_BLACKLIST)
2224         seq_puts(m, "appraise_flag=check_blacklist ");
2225     if (entry->flags & IMA_PERMIT_DIRECTIO)
2226         seq_puts(m, "permit_directio ");
2227     rcu_read_unlock();
2228     seq_puts(m, "\n");
2229     return 0;
2230 }
2231 #endif  /* CONFIG_IMA_READ_POLICY */
2232 
2233 #if defined(CONFIG_IMA_APPRAISE) && defined(CONFIG_INTEGRITY_TRUSTED_KEYRING)
2234 /*
2235  * ima_appraise_signature: whether IMA will appraise a given function using
2236  * an IMA digital signature. This is restricted to cases where the kernel
2237  * has a set of built-in trusted keys in order to avoid an attacker simply
2238  * loading additional keys.
2239  */
2240 bool ima_appraise_signature(enum kernel_read_file_id id)
2241 {
2242     struct ima_rule_entry *entry;
2243     bool found = false;
2244     enum ima_hooks func;
2245     struct list_head *ima_rules_tmp;
2246 
2247     if (id >= READING_MAX_ID)
2248         return false;
2249 
2250     if (id == READING_KEXEC_IMAGE && !(ima_appraise & IMA_APPRAISE_ENFORCE)
2251         && security_locked_down(LOCKDOWN_KEXEC))
2252         return false;
2253 
2254     func = read_idmap[id] ?: FILE_CHECK;
2255 
2256     rcu_read_lock();
2257     ima_rules_tmp = rcu_dereference(ima_rules);
2258     list_for_each_entry_rcu(entry, ima_rules_tmp, list) {
2259         if (entry->action != APPRAISE)
2260             continue;
2261 
2262         /*
2263          * A generic entry will match, but otherwise require that it
2264          * match the func we're looking for
2265          */
2266         if (entry->func && entry->func != func)
2267             continue;
2268 
2269         /*
2270          * We require this to be a digital signature, not a raw IMA
2271          * hash.
2272          */
2273         if (entry->flags & IMA_DIGSIG_REQUIRED)
2274             found = true;
2275 
2276         /*
2277          * We've found a rule that matches, so break now even if it
2278          * didn't require a digital signature - a later rule that does
2279          * won't override it, so would be a false positive.
2280          */
2281         break;
2282     }
2283 
2284     rcu_read_unlock();
2285     return found;
2286 }
2287 #endif /* CONFIG_IMA_APPRAISE && CONFIG_INTEGRITY_TRUSTED_KEYRING */