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