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