ARM: s3c64xx: bring back notes from removed debug-macro.S
[linux-2.6-microblaze.git] / security / integrity / ima / ima_policy.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2008 IBM Corporation
4  * Author: Mimi Zohar <zohar@us.ibm.com>
5  *
6  * ima_policy.c
7  *      - initialize default measure policy rules
8  */
9
10 #include <linux/init.h>
11 #include <linux/list.h>
12 #include <linux/fs.h>
13 #include <linux/security.h>
14 #include <linux/magic.h>
15 #include <linux/parser.h>
16 #include <linux/slab.h>
17 #include <linux/rculist.h>
18 #include <linux/genhd.h>
19 #include <linux/seq_file.h>
20 #include <linux/ima.h>
21
22 #include "ima.h"
23
24 /* flags definitions */
25 #define IMA_FUNC        0x0001
26 #define IMA_MASK        0x0002
27 #define IMA_FSMAGIC     0x0004
28 #define IMA_UID         0x0008
29 #define IMA_FOWNER      0x0010
30 #define IMA_FSUUID      0x0020
31 #define IMA_INMASK      0x0040
32 #define IMA_EUID        0x0080
33 #define IMA_PCR         0x0100
34 #define IMA_FSNAME      0x0200
35 #define IMA_KEYRINGS    0x0400
36
37 #define UNKNOWN         0
38 #define MEASURE         0x0001  /* same as IMA_MEASURE */
39 #define DONT_MEASURE    0x0002
40 #define APPRAISE        0x0004  /* same as IMA_APPRAISE */
41 #define DONT_APPRAISE   0x0008
42 #define AUDIT           0x0040
43 #define HASH            0x0100
44 #define DONT_HASH       0x0200
45
46 #define INVALID_PCR(a) (((a) < 0) || \
47         (a) >= (sizeof_field(struct integrity_iint_cache, measured_pcrs) * 8))
48
49 int ima_policy_flag;
50 static int temp_ima_appraise;
51 static int build_ima_appraise __ro_after_init;
52
53 #define MAX_LSM_RULES 6
54 enum lsm_rule_types { LSM_OBJ_USER, LSM_OBJ_ROLE, LSM_OBJ_TYPE,
55         LSM_SUBJ_USER, LSM_SUBJ_ROLE, LSM_SUBJ_TYPE
56 };
57
58 enum policy_types { ORIGINAL_TCB = 1, DEFAULT_TCB };
59
60 enum policy_rule_list { IMA_DEFAULT_POLICY = 1, IMA_CUSTOM_POLICY };
61
62 struct ima_rule_entry {
63         struct list_head list;
64         int action;
65         unsigned int flags;
66         enum ima_hooks func;
67         int mask;
68         unsigned long fsmagic;
69         uuid_t fsuuid;
70         kuid_t uid;
71         kuid_t fowner;
72         bool (*uid_op)(kuid_t, kuid_t);    /* Handlers for operators       */
73         bool (*fowner_op)(kuid_t, kuid_t); /* uid_eq(), uid_gt(), uid_lt() */
74         int pcr;
75         struct {
76                 void *rule;     /* LSM file metadata specific */
77                 char *args_p;   /* audit value */
78                 int type;       /* audit type */
79         } lsm[MAX_LSM_RULES];
80         char *fsname;
81         char *keyrings; /* Measure keys added to these keyrings */
82         struct ima_template_desc *template;
83 };
84
85 /*
86  * Without LSM specific knowledge, the default policy can only be
87  * written in terms of .action, .func, .mask, .fsmagic, .uid, and .fowner
88  */
89
90 /*
91  * The minimum rule set to allow for full TCB coverage.  Measures all files
92  * opened or mmap for exec and everything read by root.  Dangerous because
93  * normal users can easily run the machine out of memory simply building
94  * and running executables.
95  */
96 static struct ima_rule_entry dont_measure_rules[] __ro_after_init = {
97         {.action = DONT_MEASURE, .fsmagic = PROC_SUPER_MAGIC, .flags = IMA_FSMAGIC},
98         {.action = DONT_MEASURE, .fsmagic = SYSFS_MAGIC, .flags = IMA_FSMAGIC},
99         {.action = DONT_MEASURE, .fsmagic = DEBUGFS_MAGIC, .flags = IMA_FSMAGIC},
100         {.action = DONT_MEASURE, .fsmagic = TMPFS_MAGIC, .flags = IMA_FSMAGIC},
101         {.action = DONT_MEASURE, .fsmagic = DEVPTS_SUPER_MAGIC, .flags = IMA_FSMAGIC},
102         {.action = DONT_MEASURE, .fsmagic = BINFMTFS_MAGIC, .flags = IMA_FSMAGIC},
103         {.action = DONT_MEASURE, .fsmagic = SECURITYFS_MAGIC, .flags = IMA_FSMAGIC},
104         {.action = DONT_MEASURE, .fsmagic = SELINUX_MAGIC, .flags = IMA_FSMAGIC},
105         {.action = DONT_MEASURE, .fsmagic = SMACK_MAGIC, .flags = IMA_FSMAGIC},
106         {.action = DONT_MEASURE, .fsmagic = CGROUP_SUPER_MAGIC,
107          .flags = IMA_FSMAGIC},
108         {.action = DONT_MEASURE, .fsmagic = CGROUP2_SUPER_MAGIC,
109          .flags = IMA_FSMAGIC},
110         {.action = DONT_MEASURE, .fsmagic = NSFS_MAGIC, .flags = IMA_FSMAGIC},
111         {.action = DONT_MEASURE, .fsmagic = EFIVARFS_MAGIC, .flags = IMA_FSMAGIC}
112 };
113
114 static struct ima_rule_entry original_measurement_rules[] __ro_after_init = {
115         {.action = MEASURE, .func = MMAP_CHECK, .mask = MAY_EXEC,
116          .flags = IMA_FUNC | IMA_MASK},
117         {.action = MEASURE, .func = BPRM_CHECK, .mask = MAY_EXEC,
118          .flags = IMA_FUNC | IMA_MASK},
119         {.action = MEASURE, .func = FILE_CHECK, .mask = MAY_READ,
120          .uid = GLOBAL_ROOT_UID, .uid_op = &uid_eq,
121          .flags = IMA_FUNC | IMA_MASK | IMA_UID},
122         {.action = MEASURE, .func = MODULE_CHECK, .flags = IMA_FUNC},
123         {.action = MEASURE, .func = FIRMWARE_CHECK, .flags = IMA_FUNC},
124 };
125
126 static struct ima_rule_entry default_measurement_rules[] __ro_after_init = {
127         {.action = MEASURE, .func = MMAP_CHECK, .mask = MAY_EXEC,
128          .flags = IMA_FUNC | IMA_MASK},
129         {.action = MEASURE, .func = BPRM_CHECK, .mask = MAY_EXEC,
130          .flags = IMA_FUNC | IMA_MASK},
131         {.action = MEASURE, .func = FILE_CHECK, .mask = MAY_READ,
132          .uid = GLOBAL_ROOT_UID, .uid_op = &uid_eq,
133          .flags = IMA_FUNC | IMA_INMASK | IMA_EUID},
134         {.action = MEASURE, .func = FILE_CHECK, .mask = MAY_READ,
135          .uid = GLOBAL_ROOT_UID, .uid_op = &uid_eq,
136          .flags = IMA_FUNC | IMA_INMASK | IMA_UID},
137         {.action = MEASURE, .func = MODULE_CHECK, .flags = IMA_FUNC},
138         {.action = MEASURE, .func = FIRMWARE_CHECK, .flags = IMA_FUNC},
139         {.action = MEASURE, .func = POLICY_CHECK, .flags = IMA_FUNC},
140 };
141
142 static struct ima_rule_entry default_appraise_rules[] __ro_after_init = {
143         {.action = DONT_APPRAISE, .fsmagic = PROC_SUPER_MAGIC, .flags = IMA_FSMAGIC},
144         {.action = DONT_APPRAISE, .fsmagic = SYSFS_MAGIC, .flags = IMA_FSMAGIC},
145         {.action = DONT_APPRAISE, .fsmagic = DEBUGFS_MAGIC, .flags = IMA_FSMAGIC},
146         {.action = DONT_APPRAISE, .fsmagic = TMPFS_MAGIC, .flags = IMA_FSMAGIC},
147         {.action = DONT_APPRAISE, .fsmagic = RAMFS_MAGIC, .flags = IMA_FSMAGIC},
148         {.action = DONT_APPRAISE, .fsmagic = DEVPTS_SUPER_MAGIC, .flags = IMA_FSMAGIC},
149         {.action = DONT_APPRAISE, .fsmagic = BINFMTFS_MAGIC, .flags = IMA_FSMAGIC},
150         {.action = DONT_APPRAISE, .fsmagic = SECURITYFS_MAGIC, .flags = IMA_FSMAGIC},
151         {.action = DONT_APPRAISE, .fsmagic = SELINUX_MAGIC, .flags = IMA_FSMAGIC},
152         {.action = DONT_APPRAISE, .fsmagic = SMACK_MAGIC, .flags = IMA_FSMAGIC},
153         {.action = DONT_APPRAISE, .fsmagic = NSFS_MAGIC, .flags = IMA_FSMAGIC},
154         {.action = DONT_APPRAISE, .fsmagic = EFIVARFS_MAGIC, .flags = IMA_FSMAGIC},
155         {.action = DONT_APPRAISE, .fsmagic = CGROUP_SUPER_MAGIC, .flags = IMA_FSMAGIC},
156         {.action = DONT_APPRAISE, .fsmagic = CGROUP2_SUPER_MAGIC, .flags = IMA_FSMAGIC},
157 #ifdef CONFIG_IMA_WRITE_POLICY
158         {.action = APPRAISE, .func = POLICY_CHECK,
159         .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
160 #endif
161 #ifndef CONFIG_IMA_APPRAISE_SIGNED_INIT
162         {.action = APPRAISE, .fowner = GLOBAL_ROOT_UID, .fowner_op = &uid_eq,
163          .flags = IMA_FOWNER},
164 #else
165         /* force signature */
166         {.action = APPRAISE, .fowner = GLOBAL_ROOT_UID, .fowner_op = &uid_eq,
167          .flags = IMA_FOWNER | IMA_DIGSIG_REQUIRED},
168 #endif
169 };
170
171 static struct ima_rule_entry build_appraise_rules[] __ro_after_init = {
172 #ifdef CONFIG_IMA_APPRAISE_REQUIRE_MODULE_SIGS
173         {.action = APPRAISE, .func = MODULE_CHECK,
174          .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
175 #endif
176 #ifdef CONFIG_IMA_APPRAISE_REQUIRE_FIRMWARE_SIGS
177         {.action = APPRAISE, .func = FIRMWARE_CHECK,
178          .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
179 #endif
180 #ifdef CONFIG_IMA_APPRAISE_REQUIRE_KEXEC_SIGS
181         {.action = APPRAISE, .func = KEXEC_KERNEL_CHECK,
182          .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
183 #endif
184 #ifdef CONFIG_IMA_APPRAISE_REQUIRE_POLICY_SIGS
185         {.action = APPRAISE, .func = POLICY_CHECK,
186          .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
187 #endif
188 };
189
190 static struct ima_rule_entry secure_boot_rules[] __ro_after_init = {
191         {.action = APPRAISE, .func = MODULE_CHECK,
192          .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
193         {.action = APPRAISE, .func = FIRMWARE_CHECK,
194          .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
195         {.action = APPRAISE, .func = KEXEC_KERNEL_CHECK,
196          .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
197         {.action = APPRAISE, .func = POLICY_CHECK,
198          .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
199 };
200
201 /* An array of architecture specific rules */
202 static struct ima_rule_entry *arch_policy_entry __ro_after_init;
203
204 static LIST_HEAD(ima_default_rules);
205 static LIST_HEAD(ima_policy_rules);
206 static LIST_HEAD(ima_temp_rules);
207 static struct list_head *ima_rules = &ima_default_rules;
208
209 /* Pre-allocated buffer used for matching keyrings. */
210 static char *ima_keyrings;
211 static size_t ima_keyrings_len;
212
213 static int ima_policy __initdata;
214
215 static int __init default_measure_policy_setup(char *str)
216 {
217         if (ima_policy)
218                 return 1;
219
220         ima_policy = ORIGINAL_TCB;
221         return 1;
222 }
223 __setup("ima_tcb", default_measure_policy_setup);
224
225 static bool ima_use_appraise_tcb __initdata;
226 static bool ima_use_secure_boot __initdata;
227 static bool ima_fail_unverifiable_sigs __ro_after_init;
228 static int __init policy_setup(char *str)
229 {
230         char *p;
231
232         while ((p = strsep(&str, " |\n")) != NULL) {
233                 if (*p == ' ')
234                         continue;
235                 if ((strcmp(p, "tcb") == 0) && !ima_policy)
236                         ima_policy = DEFAULT_TCB;
237                 else if (strcmp(p, "appraise_tcb") == 0)
238                         ima_use_appraise_tcb = true;
239                 else if (strcmp(p, "secure_boot") == 0)
240                         ima_use_secure_boot = true;
241                 else if (strcmp(p, "fail_securely") == 0)
242                         ima_fail_unverifiable_sigs = true;
243         }
244
245         return 1;
246 }
247 __setup("ima_policy=", policy_setup);
248
249 static int __init default_appraise_policy_setup(char *str)
250 {
251         ima_use_appraise_tcb = true;
252         return 1;
253 }
254 __setup("ima_appraise_tcb", default_appraise_policy_setup);
255
256 static void ima_lsm_free_rule(struct ima_rule_entry *entry)
257 {
258         int i;
259
260         for (i = 0; i < MAX_LSM_RULES; i++) {
261                 ima_filter_rule_free(entry->lsm[i].rule);
262                 kfree(entry->lsm[i].args_p);
263         }
264 }
265
266 static void ima_free_rule(struct ima_rule_entry *entry)
267 {
268         if (!entry)
269                 return;
270
271         /*
272          * entry->template->fields may be allocated in ima_parse_rule() but that
273          * reference is owned by the corresponding ima_template_desc element in
274          * the defined_templates list and cannot be freed here
275          */
276         kfree(entry->fsname);
277         kfree(entry->keyrings);
278         ima_lsm_free_rule(entry);
279         kfree(entry);
280 }
281
282 static struct ima_rule_entry *ima_lsm_copy_rule(struct ima_rule_entry *entry)
283 {
284         struct ima_rule_entry *nentry;
285         int i;
286
287         nentry = kmalloc(sizeof(*nentry), GFP_KERNEL);
288         if (!nentry)
289                 return NULL;
290
291         /*
292          * Immutable elements are copied over as pointers and data; only
293          * lsm rules can change
294          */
295         memcpy(nentry, entry, sizeof(*nentry));
296         memset(nentry->lsm, 0, sizeof_field(struct ima_rule_entry, lsm));
297
298         for (i = 0; i < MAX_LSM_RULES; i++) {
299                 if (!entry->lsm[i].args_p)
300                         continue;
301
302                 nentry->lsm[i].type = entry->lsm[i].type;
303                 nentry->lsm[i].args_p = entry->lsm[i].args_p;
304                 /*
305                  * Remove the reference from entry so that the associated
306                  * memory will not be freed during a later call to
307                  * ima_lsm_free_rule(entry).
308                  */
309                 entry->lsm[i].args_p = NULL;
310
311                 ima_filter_rule_init(nentry->lsm[i].type, Audit_equal,
312                                      nentry->lsm[i].args_p,
313                                      &nentry->lsm[i].rule);
314                 if (!nentry->lsm[i].rule)
315                         pr_warn("rule for LSM \'%s\' is undefined\n",
316                                 nentry->lsm[i].args_p);
317         }
318         return nentry;
319 }
320
321 static int ima_lsm_update_rule(struct ima_rule_entry *entry)
322 {
323         struct ima_rule_entry *nentry;
324
325         nentry = ima_lsm_copy_rule(entry);
326         if (!nentry)
327                 return -ENOMEM;
328
329         list_replace_rcu(&entry->list, &nentry->list);
330         synchronize_rcu();
331         /*
332          * ima_lsm_copy_rule() shallow copied all references, except for the
333          * LSM references, from entry to nentry so we only want to free the LSM
334          * references and the entry itself. All other memory refrences will now
335          * be owned by nentry.
336          */
337         ima_lsm_free_rule(entry);
338         kfree(entry);
339
340         return 0;
341 }
342
343 static bool ima_rule_contains_lsm_cond(struct ima_rule_entry *entry)
344 {
345         int i;
346
347         for (i = 0; i < MAX_LSM_RULES; i++)
348                 if (entry->lsm[i].args_p)
349                         return true;
350
351         return false;
352 }
353
354 /*
355  * The LSM policy can be reloaded, leaving the IMA LSM based rules referring
356  * to the old, stale LSM policy.  Update the IMA LSM based rules to reflect
357  * the reloaded LSM policy.
358  */
359 static void ima_lsm_update_rules(void)
360 {
361         struct ima_rule_entry *entry, *e;
362         int result;
363
364         list_for_each_entry_safe(entry, e, &ima_policy_rules, list) {
365                 if (!ima_rule_contains_lsm_cond(entry))
366                         continue;
367
368                 result = ima_lsm_update_rule(entry);
369                 if (result) {
370                         pr_err("lsm rule update error %d\n", result);
371                         return;
372                 }
373         }
374 }
375
376 int ima_lsm_policy_change(struct notifier_block *nb, unsigned long event,
377                           void *lsm_data)
378 {
379         if (event != LSM_POLICY_CHANGE)
380                 return NOTIFY_DONE;
381
382         ima_lsm_update_rules();
383         return NOTIFY_OK;
384 }
385
386 /**
387  * ima_match_keyring - determine whether the keyring matches the measure rule
388  * @rule: a pointer to a rule
389  * @keyring: name of the keyring to match against the measure rule
390  * @cred: a pointer to a credentials structure for user validation
391  *
392  * Returns true if keyring matches one in the rule, false otherwise.
393  */
394 static bool ima_match_keyring(struct ima_rule_entry *rule,
395                               const char *keyring, const struct cred *cred)
396 {
397         char *next_keyring, *keyrings_ptr;
398         bool matched = false;
399
400         if ((rule->flags & IMA_UID) && !rule->uid_op(cred->uid, rule->uid))
401                 return false;
402
403         if (!rule->keyrings)
404                 return true;
405
406         if (!keyring)
407                 return false;
408
409         strcpy(ima_keyrings, rule->keyrings);
410
411         /*
412          * "keyrings=" is specified in the policy in the format below:
413          * keyrings=.builtin_trusted_keys|.ima|.evm
414          */
415         keyrings_ptr = ima_keyrings;
416         while ((next_keyring = strsep(&keyrings_ptr, "|")) != NULL) {
417                 if (!strcmp(next_keyring, keyring)) {
418                         matched = true;
419                         break;
420                 }
421         }
422
423         return matched;
424 }
425
426 /**
427  * ima_match_rules - determine whether an inode matches the policy rule.
428  * @rule: a pointer to a rule
429  * @inode: a pointer to an inode
430  * @cred: a pointer to a credentials structure for user validation
431  * @secid: the secid of the task to be validated
432  * @func: LIM hook identifier
433  * @mask: requested action (MAY_READ | MAY_WRITE | MAY_APPEND | MAY_EXEC)
434  * @keyring: keyring name to check in policy for KEY_CHECK func
435  *
436  * Returns true on rule match, false on failure.
437  */
438 static bool ima_match_rules(struct ima_rule_entry *rule, struct inode *inode,
439                             const struct cred *cred, u32 secid,
440                             enum ima_hooks func, int mask,
441                             const char *keyring)
442 {
443         int i;
444
445         if (func == KEY_CHECK) {
446                 return (rule->flags & IMA_FUNC) && (rule->func == func) &&
447                        ima_match_keyring(rule, keyring, cred);
448         }
449         if ((rule->flags & IMA_FUNC) &&
450             (rule->func != func && func != POST_SETATTR))
451                 return false;
452         if ((rule->flags & IMA_MASK) &&
453             (rule->mask != mask && func != POST_SETATTR))
454                 return false;
455         if ((rule->flags & IMA_INMASK) &&
456             (!(rule->mask & mask) && func != POST_SETATTR))
457                 return false;
458         if ((rule->flags & IMA_FSMAGIC)
459             && rule->fsmagic != inode->i_sb->s_magic)
460                 return false;
461         if ((rule->flags & IMA_FSNAME)
462             && strcmp(rule->fsname, inode->i_sb->s_type->name))
463                 return false;
464         if ((rule->flags & IMA_FSUUID) &&
465             !uuid_equal(&rule->fsuuid, &inode->i_sb->s_uuid))
466                 return false;
467         if ((rule->flags & IMA_UID) && !rule->uid_op(cred->uid, rule->uid))
468                 return false;
469         if (rule->flags & IMA_EUID) {
470                 if (has_capability_noaudit(current, CAP_SETUID)) {
471                         if (!rule->uid_op(cred->euid, rule->uid)
472                             && !rule->uid_op(cred->suid, rule->uid)
473                             && !rule->uid_op(cred->uid, rule->uid))
474                                 return false;
475                 } else if (!rule->uid_op(cred->euid, rule->uid))
476                         return false;
477         }
478
479         if ((rule->flags & IMA_FOWNER) &&
480             !rule->fowner_op(inode->i_uid, rule->fowner))
481                 return false;
482         for (i = 0; i < MAX_LSM_RULES; i++) {
483                 int rc = 0;
484                 u32 osid;
485
486                 if (!rule->lsm[i].rule) {
487                         if (!rule->lsm[i].args_p)
488                                 continue;
489                         else
490                                 return false;
491                 }
492                 switch (i) {
493                 case LSM_OBJ_USER:
494                 case LSM_OBJ_ROLE:
495                 case LSM_OBJ_TYPE:
496                         security_inode_getsecid(inode, &osid);
497                         rc = ima_filter_rule_match(osid, rule->lsm[i].type,
498                                                    Audit_equal,
499                                                    rule->lsm[i].rule);
500                         break;
501                 case LSM_SUBJ_USER:
502                 case LSM_SUBJ_ROLE:
503                 case LSM_SUBJ_TYPE:
504                         rc = ima_filter_rule_match(secid, rule->lsm[i].type,
505                                                    Audit_equal,
506                                                    rule->lsm[i].rule);
507                 default:
508                         break;
509                 }
510                 if (!rc)
511                         return false;
512         }
513         return true;
514 }
515
516 /*
517  * In addition to knowing that we need to appraise the file in general,
518  * we need to differentiate between calling hooks, for hook specific rules.
519  */
520 static int get_subaction(struct ima_rule_entry *rule, enum ima_hooks func)
521 {
522         if (!(rule->flags & IMA_FUNC))
523                 return IMA_FILE_APPRAISE;
524
525         switch (func) {
526         case MMAP_CHECK:
527                 return IMA_MMAP_APPRAISE;
528         case BPRM_CHECK:
529                 return IMA_BPRM_APPRAISE;
530         case CREDS_CHECK:
531                 return IMA_CREDS_APPRAISE;
532         case FILE_CHECK:
533         case POST_SETATTR:
534                 return IMA_FILE_APPRAISE;
535         case MODULE_CHECK ... MAX_CHECK - 1:
536         default:
537                 return IMA_READ_APPRAISE;
538         }
539 }
540
541 /**
542  * ima_match_policy - decision based on LSM and other conditions
543  * @inode: pointer to an inode for which the policy decision is being made
544  * @cred: pointer to a credentials structure for which the policy decision is
545  *        being made
546  * @secid: LSM secid of the task to be validated
547  * @func: IMA hook identifier
548  * @mask: requested action (MAY_READ | MAY_WRITE | MAY_APPEND | MAY_EXEC)
549  * @pcr: set the pcr to extend
550  * @template_desc: the template that should be used for this rule
551  * @keyring: the keyring name, if given, to be used to check in the policy.
552  *           keyring can be NULL if func is anything other than KEY_CHECK.
553  *
554  * Measure decision based on func/mask/fsmagic and LSM(subj/obj/type)
555  * conditions.
556  *
557  * Since the IMA policy may be updated multiple times we need to lock the
558  * list when walking it.  Reads are many orders of magnitude more numerous
559  * than writes so ima_match_policy() is classical RCU candidate.
560  */
561 int ima_match_policy(struct inode *inode, const struct cred *cred, u32 secid,
562                      enum ima_hooks func, int mask, int flags, int *pcr,
563                      struct ima_template_desc **template_desc,
564                      const char *keyring)
565 {
566         struct ima_rule_entry *entry;
567         int action = 0, actmask = flags | (flags << 1);
568
569         if (template_desc)
570                 *template_desc = ima_template_desc_current();
571
572         rcu_read_lock();
573         list_for_each_entry_rcu(entry, ima_rules, list) {
574
575                 if (!(entry->action & actmask))
576                         continue;
577
578                 if (!ima_match_rules(entry, inode, cred, secid, func, mask,
579                                      keyring))
580                         continue;
581
582                 action |= entry->flags & IMA_ACTION_FLAGS;
583
584                 action |= entry->action & IMA_DO_MASK;
585                 if (entry->action & IMA_APPRAISE) {
586                         action |= get_subaction(entry, func);
587                         action &= ~IMA_HASH;
588                         if (ima_fail_unverifiable_sigs)
589                                 action |= IMA_FAIL_UNVERIFIABLE_SIGS;
590                 }
591
592
593                 if (entry->action & IMA_DO_MASK)
594                         actmask &= ~(entry->action | entry->action << 1);
595                 else
596                         actmask &= ~(entry->action | entry->action >> 1);
597
598                 if ((pcr) && (entry->flags & IMA_PCR))
599                         *pcr = entry->pcr;
600
601                 if (template_desc && entry->template)
602                         *template_desc = entry->template;
603
604                 if (!actmask)
605                         break;
606         }
607         rcu_read_unlock();
608
609         return action;
610 }
611
612 /*
613  * Initialize the ima_policy_flag variable based on the currently
614  * loaded policy.  Based on this flag, the decision to short circuit
615  * out of a function or not call the function in the first place
616  * can be made earlier.
617  */
618 void ima_update_policy_flag(void)
619 {
620         struct ima_rule_entry *entry;
621
622         list_for_each_entry(entry, ima_rules, list) {
623                 if (entry->action & IMA_DO_MASK)
624                         ima_policy_flag |= entry->action;
625         }
626
627         ima_appraise |= (build_ima_appraise | temp_ima_appraise);
628         if (!ima_appraise)
629                 ima_policy_flag &= ~IMA_APPRAISE;
630 }
631
632 static int ima_appraise_flag(enum ima_hooks func)
633 {
634         if (func == MODULE_CHECK)
635                 return IMA_APPRAISE_MODULES;
636         else if (func == FIRMWARE_CHECK)
637                 return IMA_APPRAISE_FIRMWARE;
638         else if (func == POLICY_CHECK)
639                 return IMA_APPRAISE_POLICY;
640         else if (func == KEXEC_KERNEL_CHECK)
641                 return IMA_APPRAISE_KEXEC;
642         return 0;
643 }
644
645 static void add_rules(struct ima_rule_entry *entries, int count,
646                       enum policy_rule_list policy_rule)
647 {
648         int i = 0;
649
650         for (i = 0; i < count; i++) {
651                 struct ima_rule_entry *entry;
652
653                 if (policy_rule & IMA_DEFAULT_POLICY)
654                         list_add_tail(&entries[i].list, &ima_default_rules);
655
656                 if (policy_rule & IMA_CUSTOM_POLICY) {
657                         entry = kmemdup(&entries[i], sizeof(*entry),
658                                         GFP_KERNEL);
659                         if (!entry)
660                                 continue;
661
662                         list_add_tail(&entry->list, &ima_policy_rules);
663                 }
664                 if (entries[i].action == APPRAISE) {
665                         if (entries != build_appraise_rules)
666                                 temp_ima_appraise |=
667                                         ima_appraise_flag(entries[i].func);
668                         else
669                                 build_ima_appraise |=
670                                         ima_appraise_flag(entries[i].func);
671                 }
672         }
673 }
674
675 static int ima_parse_rule(char *rule, struct ima_rule_entry *entry);
676
677 static int __init ima_init_arch_policy(void)
678 {
679         const char * const *arch_rules;
680         const char * const *rules;
681         int arch_entries = 0;
682         int i = 0;
683
684         arch_rules = arch_get_ima_policy();
685         if (!arch_rules)
686                 return arch_entries;
687
688         /* Get number of rules */
689         for (rules = arch_rules; *rules != NULL; rules++)
690                 arch_entries++;
691
692         arch_policy_entry = kcalloc(arch_entries + 1,
693                                     sizeof(*arch_policy_entry), GFP_KERNEL);
694         if (!arch_policy_entry)
695                 return 0;
696
697         /* Convert each policy string rules to struct ima_rule_entry format */
698         for (rules = arch_rules, i = 0; *rules != NULL; rules++) {
699                 char rule[255];
700                 int result;
701
702                 result = strlcpy(rule, *rules, sizeof(rule));
703
704                 INIT_LIST_HEAD(&arch_policy_entry[i].list);
705                 result = ima_parse_rule(rule, &arch_policy_entry[i]);
706                 if (result) {
707                         pr_warn("Skipping unknown architecture policy rule: %s\n",
708                                 rule);
709                         memset(&arch_policy_entry[i], 0,
710                                sizeof(*arch_policy_entry));
711                         continue;
712                 }
713                 i++;
714         }
715         return i;
716 }
717
718 /**
719  * ima_init_policy - initialize the default measure rules.
720  *
721  * ima_rules points to either the ima_default_rules or the
722  * the new ima_policy_rules.
723  */
724 void __init ima_init_policy(void)
725 {
726         int build_appraise_entries, arch_entries;
727
728         /* if !ima_policy, we load NO default rules */
729         if (ima_policy)
730                 add_rules(dont_measure_rules, ARRAY_SIZE(dont_measure_rules),
731                           IMA_DEFAULT_POLICY);
732
733         switch (ima_policy) {
734         case ORIGINAL_TCB:
735                 add_rules(original_measurement_rules,
736                           ARRAY_SIZE(original_measurement_rules),
737                           IMA_DEFAULT_POLICY);
738                 break;
739         case DEFAULT_TCB:
740                 add_rules(default_measurement_rules,
741                           ARRAY_SIZE(default_measurement_rules),
742                           IMA_DEFAULT_POLICY);
743         default:
744                 break;
745         }
746
747         /*
748          * Based on runtime secure boot flags, insert arch specific measurement
749          * and appraise rules requiring file signatures for both the initial
750          * and custom policies, prior to other appraise rules.
751          * (Highest priority)
752          */
753         arch_entries = ima_init_arch_policy();
754         if (!arch_entries)
755                 pr_info("No architecture policies found\n");
756         else
757                 add_rules(arch_policy_entry, arch_entries,
758                           IMA_DEFAULT_POLICY | IMA_CUSTOM_POLICY);
759
760         /*
761          * Insert the builtin "secure_boot" policy rules requiring file
762          * signatures, prior to other appraise rules.
763          */
764         if (ima_use_secure_boot)
765                 add_rules(secure_boot_rules, ARRAY_SIZE(secure_boot_rules),
766                           IMA_DEFAULT_POLICY);
767
768         /*
769          * Insert the build time appraise rules requiring file signatures
770          * for both the initial and custom policies, prior to other appraise
771          * rules. As the secure boot rules includes all of the build time
772          * rules, include either one or the other set of rules, but not both.
773          */
774         build_appraise_entries = ARRAY_SIZE(build_appraise_rules);
775         if (build_appraise_entries) {
776                 if (ima_use_secure_boot)
777                         add_rules(build_appraise_rules, build_appraise_entries,
778                                   IMA_CUSTOM_POLICY);
779                 else
780                         add_rules(build_appraise_rules, build_appraise_entries,
781                                   IMA_DEFAULT_POLICY | IMA_CUSTOM_POLICY);
782         }
783
784         if (ima_use_appraise_tcb)
785                 add_rules(default_appraise_rules,
786                           ARRAY_SIZE(default_appraise_rules),
787                           IMA_DEFAULT_POLICY);
788
789         ima_update_policy_flag();
790 }
791
792 /* Make sure we have a valid policy, at least containing some rules. */
793 int ima_check_policy(void)
794 {
795         if (list_empty(&ima_temp_rules))
796                 return -EINVAL;
797         return 0;
798 }
799
800 /**
801  * ima_update_policy - update default_rules with new measure rules
802  *
803  * Called on file .release to update the default rules with a complete new
804  * policy.  What we do here is to splice ima_policy_rules and ima_temp_rules so
805  * they make a queue.  The policy may be updated multiple times and this is the
806  * RCU updater.
807  *
808  * Policy rules are never deleted so ima_policy_flag gets zeroed only once when
809  * we switch from the default policy to user defined.
810  */
811 void ima_update_policy(void)
812 {
813         struct list_head *policy = &ima_policy_rules;
814
815         list_splice_tail_init_rcu(&ima_temp_rules, policy, synchronize_rcu);
816
817         if (ima_rules != policy) {
818                 ima_policy_flag = 0;
819                 ima_rules = policy;
820
821                 /*
822                  * IMA architecture specific policy rules are specified
823                  * as strings and converted to an array of ima_entry_rules
824                  * on boot.  After loading a custom policy, free the
825                  * architecture specific rules stored as an array.
826                  */
827                 kfree(arch_policy_entry);
828         }
829         ima_update_policy_flag();
830
831         /* Custom IMA policy has been loaded */
832         ima_process_queued_keys();
833 }
834
835 /* Keep the enumeration in sync with the policy_tokens! */
836 enum {
837         Opt_measure, Opt_dont_measure,
838         Opt_appraise, Opt_dont_appraise,
839         Opt_audit, Opt_hash, Opt_dont_hash,
840         Opt_obj_user, Opt_obj_role, Opt_obj_type,
841         Opt_subj_user, Opt_subj_role, Opt_subj_type,
842         Opt_func, Opt_mask, Opt_fsmagic, Opt_fsname,
843         Opt_fsuuid, Opt_uid_eq, Opt_euid_eq, Opt_fowner_eq,
844         Opt_uid_gt, Opt_euid_gt, Opt_fowner_gt,
845         Opt_uid_lt, Opt_euid_lt, Opt_fowner_lt,
846         Opt_appraise_type, Opt_appraise_flag,
847         Opt_permit_directio, Opt_pcr, Opt_template, Opt_keyrings,
848         Opt_err
849 };
850
851 static const match_table_t policy_tokens = {
852         {Opt_measure, "measure"},
853         {Opt_dont_measure, "dont_measure"},
854         {Opt_appraise, "appraise"},
855         {Opt_dont_appraise, "dont_appraise"},
856         {Opt_audit, "audit"},
857         {Opt_hash, "hash"},
858         {Opt_dont_hash, "dont_hash"},
859         {Opt_obj_user, "obj_user=%s"},
860         {Opt_obj_role, "obj_role=%s"},
861         {Opt_obj_type, "obj_type=%s"},
862         {Opt_subj_user, "subj_user=%s"},
863         {Opt_subj_role, "subj_role=%s"},
864         {Opt_subj_type, "subj_type=%s"},
865         {Opt_func, "func=%s"},
866         {Opt_mask, "mask=%s"},
867         {Opt_fsmagic, "fsmagic=%s"},
868         {Opt_fsname, "fsname=%s"},
869         {Opt_fsuuid, "fsuuid=%s"},
870         {Opt_uid_eq, "uid=%s"},
871         {Opt_euid_eq, "euid=%s"},
872         {Opt_fowner_eq, "fowner=%s"},
873         {Opt_uid_gt, "uid>%s"},
874         {Opt_euid_gt, "euid>%s"},
875         {Opt_fowner_gt, "fowner>%s"},
876         {Opt_uid_lt, "uid<%s"},
877         {Opt_euid_lt, "euid<%s"},
878         {Opt_fowner_lt, "fowner<%s"},
879         {Opt_appraise_type, "appraise_type=%s"},
880         {Opt_appraise_flag, "appraise_flag=%s"},
881         {Opt_permit_directio, "permit_directio"},
882         {Opt_pcr, "pcr=%s"},
883         {Opt_template, "template=%s"},
884         {Opt_keyrings, "keyrings=%s"},
885         {Opt_err, NULL}
886 };
887
888 static int ima_lsm_rule_init(struct ima_rule_entry *entry,
889                              substring_t *args, int lsm_rule, int audit_type)
890 {
891         int result;
892
893         if (entry->lsm[lsm_rule].rule)
894                 return -EINVAL;
895
896         entry->lsm[lsm_rule].args_p = match_strdup(args);
897         if (!entry->lsm[lsm_rule].args_p)
898                 return -ENOMEM;
899
900         entry->lsm[lsm_rule].type = audit_type;
901         result = ima_filter_rule_init(entry->lsm[lsm_rule].type, Audit_equal,
902                                       entry->lsm[lsm_rule].args_p,
903                                       &entry->lsm[lsm_rule].rule);
904         if (!entry->lsm[lsm_rule].rule) {
905                 pr_warn("rule for LSM \'%s\' is undefined\n",
906                         entry->lsm[lsm_rule].args_p);
907
908                 if (ima_rules == &ima_default_rules) {
909                         kfree(entry->lsm[lsm_rule].args_p);
910                         entry->lsm[lsm_rule].args_p = NULL;
911                         result = -EINVAL;
912                 } else
913                         result = 0;
914         }
915
916         return result;
917 }
918
919 static void ima_log_string_op(struct audit_buffer *ab, char *key, char *value,
920                               bool (*rule_operator)(kuid_t, kuid_t))
921 {
922         if (!ab)
923                 return;
924
925         if (rule_operator == &uid_gt)
926                 audit_log_format(ab, "%s>", key);
927         else if (rule_operator == &uid_lt)
928                 audit_log_format(ab, "%s<", key);
929         else
930                 audit_log_format(ab, "%s=", key);
931         audit_log_format(ab, "%s ", value);
932 }
933 static void ima_log_string(struct audit_buffer *ab, char *key, char *value)
934 {
935         ima_log_string_op(ab, key, value, NULL);
936 }
937
938 /*
939  * Validating the appended signature included in the measurement list requires
940  * the file hash calculated without the appended signature (i.e., the 'd-modsig'
941  * field). Therefore, notify the user if they have the 'modsig' field but not
942  * the 'd-modsig' field in the template.
943  */
944 static void check_template_modsig(const struct ima_template_desc *template)
945 {
946 #define MSG "template with 'modsig' field also needs 'd-modsig' field\n"
947         bool has_modsig, has_dmodsig;
948         static bool checked;
949         int i;
950
951         /* We only need to notify the user once. */
952         if (checked)
953                 return;
954
955         has_modsig = has_dmodsig = false;
956         for (i = 0; i < template->num_fields; i++) {
957                 if (!strcmp(template->fields[i]->field_id, "modsig"))
958                         has_modsig = true;
959                 else if (!strcmp(template->fields[i]->field_id, "d-modsig"))
960                         has_dmodsig = true;
961         }
962
963         if (has_modsig && !has_dmodsig)
964                 pr_notice(MSG);
965
966         checked = true;
967 #undef MSG
968 }
969
970 static bool ima_validate_rule(struct ima_rule_entry *entry)
971 {
972         /* Ensure that the action is set and is compatible with the flags */
973         if (entry->action == UNKNOWN)
974                 return false;
975
976         if (entry->action != MEASURE && entry->flags & IMA_PCR)
977                 return false;
978
979         if (entry->action != APPRAISE &&
980             entry->flags & (IMA_DIGSIG_REQUIRED | IMA_MODSIG_ALLOWED | IMA_CHECK_BLACKLIST))
981                 return false;
982
983         /*
984          * The IMA_FUNC bit must be set if and only if there's a valid hook
985          * function specified, and vice versa. Enforcing this property allows
986          * for the NONE case below to validate a rule without an explicit hook
987          * function.
988          */
989         if (((entry->flags & IMA_FUNC) && entry->func == NONE) ||
990             (!(entry->flags & IMA_FUNC) && entry->func != NONE))
991                 return false;
992
993         /*
994          * Ensure that the hook function is compatible with the other
995          * components of the rule
996          */
997         switch (entry->func) {
998         case NONE:
999         case FILE_CHECK:
1000         case MMAP_CHECK:
1001         case BPRM_CHECK:
1002         case CREDS_CHECK:
1003         case POST_SETATTR:
1004         case FIRMWARE_CHECK:
1005         case POLICY_CHECK:
1006                 if (entry->flags & ~(IMA_FUNC | IMA_MASK | IMA_FSMAGIC |
1007                                      IMA_UID | IMA_FOWNER | IMA_FSUUID |
1008                                      IMA_INMASK | IMA_EUID | IMA_PCR |
1009                                      IMA_FSNAME | IMA_DIGSIG_REQUIRED |
1010                                      IMA_PERMIT_DIRECTIO))
1011                         return false;
1012
1013                 break;
1014         case MODULE_CHECK:
1015         case KEXEC_KERNEL_CHECK:
1016         case KEXEC_INITRAMFS_CHECK:
1017                 if (entry->flags & ~(IMA_FUNC | IMA_MASK | IMA_FSMAGIC |
1018                                      IMA_UID | IMA_FOWNER | IMA_FSUUID |
1019                                      IMA_INMASK | IMA_EUID | IMA_PCR |
1020                                      IMA_FSNAME | IMA_DIGSIG_REQUIRED |
1021                                      IMA_PERMIT_DIRECTIO | IMA_MODSIG_ALLOWED |
1022                                      IMA_CHECK_BLACKLIST))
1023                         return false;
1024
1025                 break;
1026         case KEXEC_CMDLINE:
1027                 if (entry->action & ~(MEASURE | DONT_MEASURE))
1028                         return false;
1029
1030                 if (entry->flags & ~(IMA_FUNC | IMA_FSMAGIC | IMA_UID |
1031                                      IMA_FOWNER | IMA_FSUUID | IMA_EUID |
1032                                      IMA_PCR | IMA_FSNAME))
1033                         return false;
1034
1035                 break;
1036         case KEY_CHECK:
1037                 if (entry->action & ~(MEASURE | DONT_MEASURE))
1038                         return false;
1039
1040                 if (entry->flags & ~(IMA_FUNC | IMA_UID | IMA_PCR |
1041                                      IMA_KEYRINGS))
1042                         return false;
1043
1044                 if (ima_rule_contains_lsm_cond(entry))
1045                         return false;
1046
1047                 break;
1048         default:
1049                 return false;
1050         }
1051
1052         /* Ensure that combinations of flags are compatible with each other */
1053         if (entry->flags & IMA_CHECK_BLACKLIST &&
1054             !(entry->flags & IMA_MODSIG_ALLOWED))
1055                 return false;
1056
1057         return true;
1058 }
1059
1060 static int ima_parse_rule(char *rule, struct ima_rule_entry *entry)
1061 {
1062         struct audit_buffer *ab;
1063         char *from;
1064         char *p;
1065         bool uid_token;
1066         struct ima_template_desc *template_desc;
1067         int result = 0;
1068         size_t keyrings_len;
1069
1070         ab = integrity_audit_log_start(audit_context(), GFP_KERNEL,
1071                                        AUDIT_INTEGRITY_POLICY_RULE);
1072
1073         entry->uid = INVALID_UID;
1074         entry->fowner = INVALID_UID;
1075         entry->uid_op = &uid_eq;
1076         entry->fowner_op = &uid_eq;
1077         entry->action = UNKNOWN;
1078         while ((p = strsep(&rule, " \t")) != NULL) {
1079                 substring_t args[MAX_OPT_ARGS];
1080                 int token;
1081                 unsigned long lnum;
1082
1083                 if (result < 0)
1084                         break;
1085                 if ((*p == '\0') || (*p == ' ') || (*p == '\t'))
1086                         continue;
1087                 token = match_token(p, policy_tokens, args);
1088                 switch (token) {
1089                 case Opt_measure:
1090                         ima_log_string(ab, "action", "measure");
1091
1092                         if (entry->action != UNKNOWN)
1093                                 result = -EINVAL;
1094
1095                         entry->action = MEASURE;
1096                         break;
1097                 case Opt_dont_measure:
1098                         ima_log_string(ab, "action", "dont_measure");
1099
1100                         if (entry->action != UNKNOWN)
1101                                 result = -EINVAL;
1102
1103                         entry->action = DONT_MEASURE;
1104                         break;
1105                 case Opt_appraise:
1106                         ima_log_string(ab, "action", "appraise");
1107
1108                         if (entry->action != UNKNOWN)
1109                                 result = -EINVAL;
1110
1111                         entry->action = APPRAISE;
1112                         break;
1113                 case Opt_dont_appraise:
1114                         ima_log_string(ab, "action", "dont_appraise");
1115
1116                         if (entry->action != UNKNOWN)
1117                                 result = -EINVAL;
1118
1119                         entry->action = DONT_APPRAISE;
1120                         break;
1121                 case Opt_audit:
1122                         ima_log_string(ab, "action", "audit");
1123
1124                         if (entry->action != UNKNOWN)
1125                                 result = -EINVAL;
1126
1127                         entry->action = AUDIT;
1128                         break;
1129                 case Opt_hash:
1130                         ima_log_string(ab, "action", "hash");
1131
1132                         if (entry->action != UNKNOWN)
1133                                 result = -EINVAL;
1134
1135                         entry->action = HASH;
1136                         break;
1137                 case Opt_dont_hash:
1138                         ima_log_string(ab, "action", "dont_hash");
1139
1140                         if (entry->action != UNKNOWN)
1141                                 result = -EINVAL;
1142
1143                         entry->action = DONT_HASH;
1144                         break;
1145                 case Opt_func:
1146                         ima_log_string(ab, "func", args[0].from);
1147
1148                         if (entry->func)
1149                                 result = -EINVAL;
1150
1151                         if (strcmp(args[0].from, "FILE_CHECK") == 0)
1152                                 entry->func = FILE_CHECK;
1153                         /* PATH_CHECK is for backwards compat */
1154                         else if (strcmp(args[0].from, "PATH_CHECK") == 0)
1155                                 entry->func = FILE_CHECK;
1156                         else if (strcmp(args[0].from, "MODULE_CHECK") == 0)
1157                                 entry->func = MODULE_CHECK;
1158                         else if (strcmp(args[0].from, "FIRMWARE_CHECK") == 0)
1159                                 entry->func = FIRMWARE_CHECK;
1160                         else if ((strcmp(args[0].from, "FILE_MMAP") == 0)
1161                                 || (strcmp(args[0].from, "MMAP_CHECK") == 0))
1162                                 entry->func = MMAP_CHECK;
1163                         else if (strcmp(args[0].from, "BPRM_CHECK") == 0)
1164                                 entry->func = BPRM_CHECK;
1165                         else if (strcmp(args[0].from, "CREDS_CHECK") == 0)
1166                                 entry->func = CREDS_CHECK;
1167                         else if (strcmp(args[0].from, "KEXEC_KERNEL_CHECK") ==
1168                                  0)
1169                                 entry->func = KEXEC_KERNEL_CHECK;
1170                         else if (strcmp(args[0].from, "KEXEC_INITRAMFS_CHECK")
1171                                  == 0)
1172                                 entry->func = KEXEC_INITRAMFS_CHECK;
1173                         else if (strcmp(args[0].from, "POLICY_CHECK") == 0)
1174                                 entry->func = POLICY_CHECK;
1175                         else if (strcmp(args[0].from, "KEXEC_CMDLINE") == 0)
1176                                 entry->func = KEXEC_CMDLINE;
1177                         else if (strcmp(args[0].from, "KEY_CHECK") == 0)
1178                                 entry->func = KEY_CHECK;
1179                         else
1180                                 result = -EINVAL;
1181                         if (!result)
1182                                 entry->flags |= IMA_FUNC;
1183                         break;
1184                 case Opt_mask:
1185                         ima_log_string(ab, "mask", args[0].from);
1186
1187                         if (entry->mask)
1188                                 result = -EINVAL;
1189
1190                         from = args[0].from;
1191                         if (*from == '^')
1192                                 from++;
1193
1194                         if ((strcmp(from, "MAY_EXEC")) == 0)
1195                                 entry->mask = MAY_EXEC;
1196                         else if (strcmp(from, "MAY_WRITE") == 0)
1197                                 entry->mask = MAY_WRITE;
1198                         else if (strcmp(from, "MAY_READ") == 0)
1199                                 entry->mask = MAY_READ;
1200                         else if (strcmp(from, "MAY_APPEND") == 0)
1201                                 entry->mask = MAY_APPEND;
1202                         else
1203                                 result = -EINVAL;
1204                         if (!result)
1205                                 entry->flags |= (*args[0].from == '^')
1206                                      ? IMA_INMASK : IMA_MASK;
1207                         break;
1208                 case Opt_fsmagic:
1209                         ima_log_string(ab, "fsmagic", args[0].from);
1210
1211                         if (entry->fsmagic) {
1212                                 result = -EINVAL;
1213                                 break;
1214                         }
1215
1216                         result = kstrtoul(args[0].from, 16, &entry->fsmagic);
1217                         if (!result)
1218                                 entry->flags |= IMA_FSMAGIC;
1219                         break;
1220                 case Opt_fsname:
1221                         ima_log_string(ab, "fsname", args[0].from);
1222
1223                         entry->fsname = kstrdup(args[0].from, GFP_KERNEL);
1224                         if (!entry->fsname) {
1225                                 result = -ENOMEM;
1226                                 break;
1227                         }
1228                         result = 0;
1229                         entry->flags |= IMA_FSNAME;
1230                         break;
1231                 case Opt_keyrings:
1232                         ima_log_string(ab, "keyrings", args[0].from);
1233
1234                         keyrings_len = strlen(args[0].from) + 1;
1235
1236                         if ((entry->keyrings) ||
1237                             (keyrings_len < 2)) {
1238                                 result = -EINVAL;
1239                                 break;
1240                         }
1241
1242                         if (keyrings_len > ima_keyrings_len) {
1243                                 char *tmpbuf;
1244
1245                                 tmpbuf = krealloc(ima_keyrings, keyrings_len,
1246                                                   GFP_KERNEL);
1247                                 if (!tmpbuf) {
1248                                         result = -ENOMEM;
1249                                         break;
1250                                 }
1251
1252                                 ima_keyrings = tmpbuf;
1253                                 ima_keyrings_len = keyrings_len;
1254                         }
1255
1256                         entry->keyrings = kstrdup(args[0].from, GFP_KERNEL);
1257                         if (!entry->keyrings) {
1258                                 kfree(ima_keyrings);
1259                                 ima_keyrings = NULL;
1260                                 ima_keyrings_len = 0;
1261                                 result = -ENOMEM;
1262                                 break;
1263                         }
1264                         result = 0;
1265                         entry->flags |= IMA_KEYRINGS;
1266                         break;
1267                 case Opt_fsuuid:
1268                         ima_log_string(ab, "fsuuid", args[0].from);
1269
1270                         if (!uuid_is_null(&entry->fsuuid)) {
1271                                 result = -EINVAL;
1272                                 break;
1273                         }
1274
1275                         result = uuid_parse(args[0].from, &entry->fsuuid);
1276                         if (!result)
1277                                 entry->flags |= IMA_FSUUID;
1278                         break;
1279                 case Opt_uid_gt:
1280                 case Opt_euid_gt:
1281                         entry->uid_op = &uid_gt;
1282                         /* fall through */
1283                 case Opt_uid_lt:
1284                 case Opt_euid_lt:
1285                         if ((token == Opt_uid_lt) || (token == Opt_euid_lt))
1286                                 entry->uid_op = &uid_lt;
1287                         /* fall through */
1288                 case Opt_uid_eq:
1289                 case Opt_euid_eq:
1290                         uid_token = (token == Opt_uid_eq) ||
1291                                     (token == Opt_uid_gt) ||
1292                                     (token == Opt_uid_lt);
1293
1294                         ima_log_string_op(ab, uid_token ? "uid" : "euid",
1295                                           args[0].from, entry->uid_op);
1296
1297                         if (uid_valid(entry->uid)) {
1298                                 result = -EINVAL;
1299                                 break;
1300                         }
1301
1302                         result = kstrtoul(args[0].from, 10, &lnum);
1303                         if (!result) {
1304                                 entry->uid = make_kuid(current_user_ns(),
1305                                                        (uid_t) lnum);
1306                                 if (!uid_valid(entry->uid) ||
1307                                     (uid_t)lnum != lnum)
1308                                         result = -EINVAL;
1309                                 else
1310                                         entry->flags |= uid_token
1311                                             ? IMA_UID : IMA_EUID;
1312                         }
1313                         break;
1314                 case Opt_fowner_gt:
1315                         entry->fowner_op = &uid_gt;
1316                         /* fall through */
1317                 case Opt_fowner_lt:
1318                         if (token == Opt_fowner_lt)
1319                                 entry->fowner_op = &uid_lt;
1320                         /* fall through */
1321                 case Opt_fowner_eq:
1322                         ima_log_string_op(ab, "fowner", args[0].from,
1323                                           entry->fowner_op);
1324
1325                         if (uid_valid(entry->fowner)) {
1326                                 result = -EINVAL;
1327                                 break;
1328                         }
1329
1330                         result = kstrtoul(args[0].from, 10, &lnum);
1331                         if (!result) {
1332                                 entry->fowner = make_kuid(current_user_ns(), (uid_t)lnum);
1333                                 if (!uid_valid(entry->fowner) || (((uid_t)lnum) != lnum))
1334                                         result = -EINVAL;
1335                                 else
1336                                         entry->flags |= IMA_FOWNER;
1337                         }
1338                         break;
1339                 case Opt_obj_user:
1340                         ima_log_string(ab, "obj_user", args[0].from);
1341                         result = ima_lsm_rule_init(entry, args,
1342                                                    LSM_OBJ_USER,
1343                                                    AUDIT_OBJ_USER);
1344                         break;
1345                 case Opt_obj_role:
1346                         ima_log_string(ab, "obj_role", args[0].from);
1347                         result = ima_lsm_rule_init(entry, args,
1348                                                    LSM_OBJ_ROLE,
1349                                                    AUDIT_OBJ_ROLE);
1350                         break;
1351                 case Opt_obj_type:
1352                         ima_log_string(ab, "obj_type", args[0].from);
1353                         result = ima_lsm_rule_init(entry, args,
1354                                                    LSM_OBJ_TYPE,
1355                                                    AUDIT_OBJ_TYPE);
1356                         break;
1357                 case Opt_subj_user:
1358                         ima_log_string(ab, "subj_user", args[0].from);
1359                         result = ima_lsm_rule_init(entry, args,
1360                                                    LSM_SUBJ_USER,
1361                                                    AUDIT_SUBJ_USER);
1362                         break;
1363                 case Opt_subj_role:
1364                         ima_log_string(ab, "subj_role", args[0].from);
1365                         result = ima_lsm_rule_init(entry, args,
1366                                                    LSM_SUBJ_ROLE,
1367                                                    AUDIT_SUBJ_ROLE);
1368                         break;
1369                 case Opt_subj_type:
1370                         ima_log_string(ab, "subj_type", args[0].from);
1371                         result = ima_lsm_rule_init(entry, args,
1372                                                    LSM_SUBJ_TYPE,
1373                                                    AUDIT_SUBJ_TYPE);
1374                         break;
1375                 case Opt_appraise_type:
1376                         ima_log_string(ab, "appraise_type", args[0].from);
1377                         if ((strcmp(args[0].from, "imasig")) == 0)
1378                                 entry->flags |= IMA_DIGSIG_REQUIRED;
1379                         else if (IS_ENABLED(CONFIG_IMA_APPRAISE_MODSIG) &&
1380                                  strcmp(args[0].from, "imasig|modsig") == 0)
1381                                 entry->flags |= IMA_DIGSIG_REQUIRED |
1382                                                 IMA_MODSIG_ALLOWED;
1383                         else
1384                                 result = -EINVAL;
1385                         break;
1386                 case Opt_appraise_flag:
1387                         ima_log_string(ab, "appraise_flag", args[0].from);
1388                         if (IS_ENABLED(CONFIG_IMA_APPRAISE_MODSIG) &&
1389                             strstr(args[0].from, "blacklist"))
1390                                 entry->flags |= IMA_CHECK_BLACKLIST;
1391                         else
1392                                 result = -EINVAL;
1393                         break;
1394                 case Opt_permit_directio:
1395                         entry->flags |= IMA_PERMIT_DIRECTIO;
1396                         break;
1397                 case Opt_pcr:
1398                         ima_log_string(ab, "pcr", args[0].from);
1399
1400                         result = kstrtoint(args[0].from, 10, &entry->pcr);
1401                         if (result || INVALID_PCR(entry->pcr))
1402                                 result = -EINVAL;
1403                         else
1404                                 entry->flags |= IMA_PCR;
1405
1406                         break;
1407                 case Opt_template:
1408                         ima_log_string(ab, "template", args[0].from);
1409                         if (entry->action != MEASURE) {
1410                                 result = -EINVAL;
1411                                 break;
1412                         }
1413                         template_desc = lookup_template_desc(args[0].from);
1414                         if (!template_desc || entry->template) {
1415                                 result = -EINVAL;
1416                                 break;
1417                         }
1418
1419                         /*
1420                          * template_desc_init_fields() does nothing if
1421                          * the template is already initialised, so
1422                          * it's safe to do this unconditionally
1423                          */
1424                         template_desc_init_fields(template_desc->fmt,
1425                                                  &(template_desc->fields),
1426                                                  &(template_desc->num_fields));
1427                         entry->template = template_desc;
1428                         break;
1429                 case Opt_err:
1430                         ima_log_string(ab, "UNKNOWN", p);
1431                         result = -EINVAL;
1432                         break;
1433                 }
1434         }
1435         if (!result && !ima_validate_rule(entry))
1436                 result = -EINVAL;
1437         else if (entry->action == APPRAISE)
1438                 temp_ima_appraise |= ima_appraise_flag(entry->func);
1439
1440         if (!result && entry->flags & IMA_MODSIG_ALLOWED) {
1441                 template_desc = entry->template ? entry->template :
1442                                                   ima_template_desc_current();
1443                 check_template_modsig(template_desc);
1444         }
1445
1446         audit_log_format(ab, "res=%d", !result);
1447         audit_log_end(ab);
1448         return result;
1449 }
1450
1451 /**
1452  * ima_parse_add_rule - add a rule to ima_policy_rules
1453  * @rule - ima measurement policy rule
1454  *
1455  * Avoid locking by allowing just one writer at a time in ima_write_policy()
1456  * Returns the length of the rule parsed, an error code on failure
1457  */
1458 ssize_t ima_parse_add_rule(char *rule)
1459 {
1460         static const char op[] = "update_policy";
1461         char *p;
1462         struct ima_rule_entry *entry;
1463         ssize_t result, len;
1464         int audit_info = 0;
1465
1466         p = strsep(&rule, "\n");
1467         len = strlen(p) + 1;
1468         p += strspn(p, " \t");
1469
1470         if (*p == '#' || *p == '\0')
1471                 return len;
1472
1473         entry = kzalloc(sizeof(*entry), GFP_KERNEL);
1474         if (!entry) {
1475                 integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
1476                                     NULL, op, "-ENOMEM", -ENOMEM, audit_info);
1477                 return -ENOMEM;
1478         }
1479
1480         INIT_LIST_HEAD(&entry->list);
1481
1482         result = ima_parse_rule(p, entry);
1483         if (result) {
1484                 ima_free_rule(entry);
1485                 integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
1486                                     NULL, op, "invalid-policy", result,
1487                                     audit_info);
1488                 return result;
1489         }
1490
1491         list_add_tail(&entry->list, &ima_temp_rules);
1492
1493         return len;
1494 }
1495
1496 /**
1497  * ima_delete_rules() called to cleanup invalid in-flight policy.
1498  * We don't need locking as we operate on the temp list, which is
1499  * different from the active one.  There is also only one user of
1500  * ima_delete_rules() at a time.
1501  */
1502 void ima_delete_rules(void)
1503 {
1504         struct ima_rule_entry *entry, *tmp;
1505
1506         temp_ima_appraise = 0;
1507         list_for_each_entry_safe(entry, tmp, &ima_temp_rules, list) {
1508                 list_del(&entry->list);
1509                 ima_free_rule(entry);
1510         }
1511 }
1512
1513 #define __ima_hook_stringify(func, str) (#func),
1514
1515 const char *const func_tokens[] = {
1516         __ima_hooks(__ima_hook_stringify)
1517 };
1518
1519 #ifdef  CONFIG_IMA_READ_POLICY
1520 enum {
1521         mask_exec = 0, mask_write, mask_read, mask_append
1522 };
1523
1524 static const char *const mask_tokens[] = {
1525         "^MAY_EXEC",
1526         "^MAY_WRITE",
1527         "^MAY_READ",
1528         "^MAY_APPEND"
1529 };
1530
1531 void *ima_policy_start(struct seq_file *m, loff_t *pos)
1532 {
1533         loff_t l = *pos;
1534         struct ima_rule_entry *entry;
1535
1536         rcu_read_lock();
1537         list_for_each_entry_rcu(entry, ima_rules, list) {
1538                 if (!l--) {
1539                         rcu_read_unlock();
1540                         return entry;
1541                 }
1542         }
1543         rcu_read_unlock();
1544         return NULL;
1545 }
1546
1547 void *ima_policy_next(struct seq_file *m, void *v, loff_t *pos)
1548 {
1549         struct ima_rule_entry *entry = v;
1550
1551         rcu_read_lock();
1552         entry = list_entry_rcu(entry->list.next, struct ima_rule_entry, list);
1553         rcu_read_unlock();
1554         (*pos)++;
1555
1556         return (&entry->list == ima_rules) ? NULL : entry;
1557 }
1558
1559 void ima_policy_stop(struct seq_file *m, void *v)
1560 {
1561 }
1562
1563 #define pt(token)       policy_tokens[token].pattern
1564 #define mt(token)       mask_tokens[token]
1565
1566 /*
1567  * policy_func_show - display the ima_hooks policy rule
1568  */
1569 static void policy_func_show(struct seq_file *m, enum ima_hooks func)
1570 {
1571         if (func > 0 && func < MAX_CHECK)
1572                 seq_printf(m, "func=%s ", func_tokens[func]);
1573         else
1574                 seq_printf(m, "func=%d ", func);
1575 }
1576
1577 int ima_policy_show(struct seq_file *m, void *v)
1578 {
1579         struct ima_rule_entry *entry = v;
1580         int i;
1581         char tbuf[64] = {0,};
1582         int offset = 0;
1583
1584         rcu_read_lock();
1585
1586         if (entry->action & MEASURE)
1587                 seq_puts(m, pt(Opt_measure));
1588         if (entry->action & DONT_MEASURE)
1589                 seq_puts(m, pt(Opt_dont_measure));
1590         if (entry->action & APPRAISE)
1591                 seq_puts(m, pt(Opt_appraise));
1592         if (entry->action & DONT_APPRAISE)
1593                 seq_puts(m, pt(Opt_dont_appraise));
1594         if (entry->action & AUDIT)
1595                 seq_puts(m, pt(Opt_audit));
1596         if (entry->action & HASH)
1597                 seq_puts(m, pt(Opt_hash));
1598         if (entry->action & DONT_HASH)
1599                 seq_puts(m, pt(Opt_dont_hash));
1600
1601         seq_puts(m, " ");
1602
1603         if (entry->flags & IMA_FUNC)
1604                 policy_func_show(m, entry->func);
1605
1606         if ((entry->flags & IMA_MASK) || (entry->flags & IMA_INMASK)) {
1607                 if (entry->flags & IMA_MASK)
1608                         offset = 1;
1609                 if (entry->mask & MAY_EXEC)
1610                         seq_printf(m, pt(Opt_mask), mt(mask_exec) + offset);
1611                 if (entry->mask & MAY_WRITE)
1612                         seq_printf(m, pt(Opt_mask), mt(mask_write) + offset);
1613                 if (entry->mask & MAY_READ)
1614                         seq_printf(m, pt(Opt_mask), mt(mask_read) + offset);
1615                 if (entry->mask & MAY_APPEND)
1616                         seq_printf(m, pt(Opt_mask), mt(mask_append) + offset);
1617                 seq_puts(m, " ");
1618         }
1619
1620         if (entry->flags & IMA_FSMAGIC) {
1621                 snprintf(tbuf, sizeof(tbuf), "0x%lx", entry->fsmagic);
1622                 seq_printf(m, pt(Opt_fsmagic), tbuf);
1623                 seq_puts(m, " ");
1624         }
1625
1626         if (entry->flags & IMA_FSNAME) {
1627                 snprintf(tbuf, sizeof(tbuf), "%s", entry->fsname);
1628                 seq_printf(m, pt(Opt_fsname), tbuf);
1629                 seq_puts(m, " ");
1630         }
1631
1632         if (entry->flags & IMA_KEYRINGS) {
1633                 if (entry->keyrings != NULL)
1634                         snprintf(tbuf, sizeof(tbuf), "%s", entry->keyrings);
1635                 seq_printf(m, pt(Opt_keyrings), tbuf);
1636                 seq_puts(m, " ");
1637         }
1638
1639         if (entry->flags & IMA_PCR) {
1640                 snprintf(tbuf, sizeof(tbuf), "%d", entry->pcr);
1641                 seq_printf(m, pt(Opt_pcr), tbuf);
1642                 seq_puts(m, " ");
1643         }
1644
1645         if (entry->flags & IMA_FSUUID) {
1646                 seq_printf(m, "fsuuid=%pU", &entry->fsuuid);
1647                 seq_puts(m, " ");
1648         }
1649
1650         if (entry->flags & IMA_UID) {
1651                 snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->uid));
1652                 if (entry->uid_op == &uid_gt)
1653                         seq_printf(m, pt(Opt_uid_gt), tbuf);
1654                 else if (entry->uid_op == &uid_lt)
1655                         seq_printf(m, pt(Opt_uid_lt), tbuf);
1656                 else
1657                         seq_printf(m, pt(Opt_uid_eq), tbuf);
1658                 seq_puts(m, " ");
1659         }
1660
1661         if (entry->flags & IMA_EUID) {
1662                 snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->uid));
1663                 if (entry->uid_op == &uid_gt)
1664                         seq_printf(m, pt(Opt_euid_gt), tbuf);
1665                 else if (entry->uid_op == &uid_lt)
1666                         seq_printf(m, pt(Opt_euid_lt), tbuf);
1667                 else
1668                         seq_printf(m, pt(Opt_euid_eq), tbuf);
1669                 seq_puts(m, " ");
1670         }
1671
1672         if (entry->flags & IMA_FOWNER) {
1673                 snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->fowner));
1674                 if (entry->fowner_op == &uid_gt)
1675                         seq_printf(m, pt(Opt_fowner_gt), tbuf);
1676                 else if (entry->fowner_op == &uid_lt)
1677                         seq_printf(m, pt(Opt_fowner_lt), tbuf);
1678                 else
1679                         seq_printf(m, pt(Opt_fowner_eq), tbuf);
1680                 seq_puts(m, " ");
1681         }
1682
1683         for (i = 0; i < MAX_LSM_RULES; i++) {
1684                 if (entry->lsm[i].rule) {
1685                         switch (i) {
1686                         case LSM_OBJ_USER:
1687                                 seq_printf(m, pt(Opt_obj_user),
1688                                            entry->lsm[i].args_p);
1689                                 break;
1690                         case LSM_OBJ_ROLE:
1691                                 seq_printf(m, pt(Opt_obj_role),
1692                                            entry->lsm[i].args_p);
1693                                 break;
1694                         case LSM_OBJ_TYPE:
1695                                 seq_printf(m, pt(Opt_obj_type),
1696                                            entry->lsm[i].args_p);
1697                                 break;
1698                         case LSM_SUBJ_USER:
1699                                 seq_printf(m, pt(Opt_subj_user),
1700                                            entry->lsm[i].args_p);
1701                                 break;
1702                         case LSM_SUBJ_ROLE:
1703                                 seq_printf(m, pt(Opt_subj_role),
1704                                            entry->lsm[i].args_p);
1705                                 break;
1706                         case LSM_SUBJ_TYPE:
1707                                 seq_printf(m, pt(Opt_subj_type),
1708                                            entry->lsm[i].args_p);
1709                                 break;
1710                         }
1711                         seq_puts(m, " ");
1712                 }
1713         }
1714         if (entry->template)
1715                 seq_printf(m, "template=%s ", entry->template->name);
1716         if (entry->flags & IMA_DIGSIG_REQUIRED) {
1717                 if (entry->flags & IMA_MODSIG_ALLOWED)
1718                         seq_puts(m, "appraise_type=imasig|modsig ");
1719                 else
1720                         seq_puts(m, "appraise_type=imasig ");
1721         }
1722         if (entry->flags & IMA_CHECK_BLACKLIST)
1723                 seq_puts(m, "appraise_flag=check_blacklist ");
1724         if (entry->flags & IMA_PERMIT_DIRECTIO)
1725                 seq_puts(m, "permit_directio ");
1726         rcu_read_unlock();
1727         seq_puts(m, "\n");
1728         return 0;
1729 }
1730 #endif  /* CONFIG_IMA_READ_POLICY */
1731
1732 #if defined(CONFIG_IMA_APPRAISE) && defined(CONFIG_INTEGRITY_TRUSTED_KEYRING)
1733 /*
1734  * ima_appraise_signature: whether IMA will appraise a given function using
1735  * an IMA digital signature. This is restricted to cases where the kernel
1736  * has a set of built-in trusted keys in order to avoid an attacker simply
1737  * loading additional keys.
1738  */
1739 bool ima_appraise_signature(enum kernel_read_file_id id)
1740 {
1741         struct ima_rule_entry *entry;
1742         bool found = false;
1743         enum ima_hooks func;
1744
1745         if (id >= READING_MAX_ID)
1746                 return false;
1747
1748         func = read_idmap[id] ?: FILE_CHECK;
1749
1750         rcu_read_lock();
1751         list_for_each_entry_rcu(entry, ima_rules, list) {
1752                 if (entry->action != APPRAISE)
1753                         continue;
1754
1755                 /*
1756                  * A generic entry will match, but otherwise require that it
1757                  * match the func we're looking for
1758                  */
1759                 if (entry->func && entry->func != func)
1760                         continue;
1761
1762                 /*
1763                  * We require this to be a digital signature, not a raw IMA
1764                  * hash.
1765                  */
1766                 if (entry->flags & IMA_DIGSIG_REQUIRED)
1767                         found = true;
1768
1769                 /*
1770                  * We've found a rule that matches, so break now even if it
1771                  * didn't require a digital signature - a later rule that does
1772                  * won't override it, so would be a false positive.
1773                  */
1774                 break;
1775         }
1776
1777         rcu_read_unlock();
1778         return found;
1779 }
1780 #endif /* CONFIG_IMA_APPRAISE && CONFIG_INTEGRITY_TRUSTED_KEYRING */