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 = &ima_default_rules;
208 
209 /* Pre-allocated buffer used for matching keyrings. */
210 static char *ima_keyrings;
211 static size_t ima_keyrings_len;
212 
213 static int ima_policy __initdata;
214 
215 static int __init default_measure_policy_setup(char *str)
216 {
217 	if (ima_policy)
218 		return 1;
219 
220 	ima_policy = ORIGINAL_TCB;
221 	return 1;
222 }
223 __setup("ima_tcb", default_measure_policy_setup);
224 
225 static bool ima_use_appraise_tcb __initdata;
226 static bool ima_use_secure_boot __initdata;
227 static bool ima_fail_unverifiable_sigs __ro_after_init;
228 static int __init policy_setup(char *str)
229 {
230 	char *p;
231 
232 	while ((p = strsep(&str, " |\n")) != NULL) {
233 		if (*p == ' ')
234 			continue;
235 		if ((strcmp(p, "tcb") == 0) && !ima_policy)
236 			ima_policy = DEFAULT_TCB;
237 		else if (strcmp(p, "appraise_tcb") == 0)
238 			ima_use_appraise_tcb = true;
239 		else if (strcmp(p, "secure_boot") == 0)
240 			ima_use_secure_boot = true;
241 		else if (strcmp(p, "fail_securely") == 0)
242 			ima_fail_unverifiable_sigs = true;
243 	}
244 
245 	return 1;
246 }
247 __setup("ima_policy=", policy_setup);
248 
249 static int __init default_appraise_policy_setup(char *str)
250 {
251 	ima_use_appraise_tcb = true;
252 	return 1;
253 }
254 __setup("ima_appraise_tcb", default_appraise_policy_setup);
255 
256 static void ima_lsm_free_rule(struct ima_rule_entry *entry)
257 {
258 	int i;
259 
260 	for (i = 0; i < MAX_LSM_RULES; i++) {
261 		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 			if (entries != build_appraise_rules)
648 				temp_ima_appraise |=
649 					ima_appraise_flag(entries[i].func);
650 			else
651 				build_ima_appraise |=
652 					ima_appraise_flag(entries[i].func);
653 		}
654 	}
655 }
656 
657 static int ima_parse_rule(char *rule, struct ima_rule_entry *entry);
658 
659 static int __init ima_init_arch_policy(void)
660 {
661 	const char * const *arch_rules;
662 	const char * const *rules;
663 	int arch_entries = 0;
664 	int i = 0;
665 
666 	arch_rules = arch_get_ima_policy();
667 	if (!arch_rules)
668 		return arch_entries;
669 
670 	/* Get number of rules */
671 	for (rules = arch_rules; *rules != NULL; rules++)
672 		arch_entries++;
673 
674 	arch_policy_entry = kcalloc(arch_entries + 1,
675 				    sizeof(*arch_policy_entry), GFP_KERNEL);
676 	if (!arch_policy_entry)
677 		return 0;
678 
679 	/* Convert each policy string rules to struct ima_rule_entry format */
680 	for (rules = arch_rules, i = 0; *rules != NULL; rules++) {
681 		char rule[255];
682 		int result;
683 
684 		result = strlcpy(rule, *rules, sizeof(rule));
685 
686 		INIT_LIST_HEAD(&arch_policy_entry[i].list);
687 		result = ima_parse_rule(rule, &arch_policy_entry[i]);
688 		if (result) {
689 			pr_warn("Skipping unknown architecture policy rule: %s\n",
690 				rule);
691 			memset(&arch_policy_entry[i], 0,
692 			       sizeof(*arch_policy_entry));
693 			continue;
694 		}
695 		i++;
696 	}
697 	return i;
698 }
699 
700 /**
701  * ima_init_policy - initialize the default measure rules.
702  *
703  * ima_rules points to either the ima_default_rules or the
704  * the new ima_policy_rules.
705  */
706 void __init ima_init_policy(void)
707 {
708 	int build_appraise_entries, arch_entries;
709 
710 	/* if !ima_policy, we load NO default rules */
711 	if (ima_policy)
712 		add_rules(dont_measure_rules, ARRAY_SIZE(dont_measure_rules),
713 			  IMA_DEFAULT_POLICY);
714 
715 	switch (ima_policy) {
716 	case ORIGINAL_TCB:
717 		add_rules(original_measurement_rules,
718 			  ARRAY_SIZE(original_measurement_rules),
719 			  IMA_DEFAULT_POLICY);
720 		break;
721 	case DEFAULT_TCB:
722 		add_rules(default_measurement_rules,
723 			  ARRAY_SIZE(default_measurement_rules),
724 			  IMA_DEFAULT_POLICY);
725 	default:
726 		break;
727 	}
728 
729 	/*
730 	 * Based on runtime secure boot flags, insert arch specific measurement
731 	 * and appraise rules requiring file signatures for both the initial
732 	 * and custom policies, prior to other appraise rules.
733 	 * (Highest priority)
734 	 */
735 	arch_entries = ima_init_arch_policy();
736 	if (!arch_entries)
737 		pr_info("No architecture policies found\n");
738 	else
739 		add_rules(arch_policy_entry, arch_entries,
740 			  IMA_DEFAULT_POLICY | IMA_CUSTOM_POLICY);
741 
742 	/*
743 	 * Insert the builtin "secure_boot" policy rules requiring file
744 	 * signatures, prior to other appraise rules.
745 	 */
746 	if (ima_use_secure_boot)
747 		add_rules(secure_boot_rules, ARRAY_SIZE(secure_boot_rules),
748 			  IMA_DEFAULT_POLICY);
749 
750 	/*
751 	 * Insert the build time appraise rules requiring file signatures
752 	 * for both the initial and custom policies, prior to other appraise
753 	 * rules. As the secure boot rules includes all of the build time
754 	 * rules, include either one or the other set of rules, but not both.
755 	 */
756 	build_appraise_entries = ARRAY_SIZE(build_appraise_rules);
757 	if (build_appraise_entries) {
758 		if (ima_use_secure_boot)
759 			add_rules(build_appraise_rules, build_appraise_entries,
760 				  IMA_CUSTOM_POLICY);
761 		else
762 			add_rules(build_appraise_rules, build_appraise_entries,
763 				  IMA_DEFAULT_POLICY | IMA_CUSTOM_POLICY);
764 	}
765 
766 	if (ima_use_appraise_tcb)
767 		add_rules(default_appraise_rules,
768 			  ARRAY_SIZE(default_appraise_rules),
769 			  IMA_DEFAULT_POLICY);
770 
771 	ima_update_policy_flag();
772 }
773 
774 /* Make sure we have a valid policy, at least containing some rules. */
775 int ima_check_policy(void)
776 {
777 	if (list_empty(&ima_temp_rules))
778 		return -EINVAL;
779 	return 0;
780 }
781 
782 /**
783  * ima_update_policy - update default_rules with new measure rules
784  *
785  * Called on file .release to update the default rules with a complete new
786  * policy.  What we do here is to splice ima_policy_rules and ima_temp_rules so
787  * they make a queue.  The policy may be updated multiple times and this is the
788  * RCU updater.
789  *
790  * Policy rules are never deleted so ima_policy_flag gets zeroed only once when
791  * we switch from the default policy to user defined.
792  */
793 void ima_update_policy(void)
794 {
795 	struct list_head *policy = &ima_policy_rules;
796 
797 	list_splice_tail_init_rcu(&ima_temp_rules, policy, synchronize_rcu);
798 
799 	if (ima_rules != policy) {
800 		ima_policy_flag = 0;
801 		ima_rules = policy;
802 
803 		/*
804 		 * IMA architecture specific policy rules are specified
805 		 * as strings and converted to an array of ima_entry_rules
806 		 * on boot.  After loading a custom policy, free the
807 		 * architecture specific rules stored as an array.
808 		 */
809 		kfree(arch_policy_entry);
810 	}
811 	ima_update_policy_flag();
812 
813 	/* Custom IMA policy has been loaded */
814 	ima_process_queued_keys();
815 }
816 
817 /* Keep the enumeration in sync with the policy_tokens! */
818 enum {
819 	Opt_measure, Opt_dont_measure,
820 	Opt_appraise, Opt_dont_appraise,
821 	Opt_audit, Opt_hash, Opt_dont_hash,
822 	Opt_obj_user, Opt_obj_role, Opt_obj_type,
823 	Opt_subj_user, Opt_subj_role, Opt_subj_type,
824 	Opt_func, Opt_mask, Opt_fsmagic, Opt_fsname,
825 	Opt_fsuuid, Opt_uid_eq, Opt_euid_eq, Opt_fowner_eq,
826 	Opt_uid_gt, Opt_euid_gt, Opt_fowner_gt,
827 	Opt_uid_lt, Opt_euid_lt, Opt_fowner_lt,
828 	Opt_appraise_type, Opt_appraise_flag,
829 	Opt_permit_directio, Opt_pcr, Opt_template, Opt_keyrings,
830 	Opt_err
831 };
832 
833 static const match_table_t policy_tokens = {
834 	{Opt_measure, "measure"},
835 	{Opt_dont_measure, "dont_measure"},
836 	{Opt_appraise, "appraise"},
837 	{Opt_dont_appraise, "dont_appraise"},
838 	{Opt_audit, "audit"},
839 	{Opt_hash, "hash"},
840 	{Opt_dont_hash, "dont_hash"},
841 	{Opt_obj_user, "obj_user=%s"},
842 	{Opt_obj_role, "obj_role=%s"},
843 	{Opt_obj_type, "obj_type=%s"},
844 	{Opt_subj_user, "subj_user=%s"},
845 	{Opt_subj_role, "subj_role=%s"},
846 	{Opt_subj_type, "subj_type=%s"},
847 	{Opt_func, "func=%s"},
848 	{Opt_mask, "mask=%s"},
849 	{Opt_fsmagic, "fsmagic=%s"},
850 	{Opt_fsname, "fsname=%s"},
851 	{Opt_fsuuid, "fsuuid=%s"},
852 	{Opt_uid_eq, "uid=%s"},
853 	{Opt_euid_eq, "euid=%s"},
854 	{Opt_fowner_eq, "fowner=%s"},
855 	{Opt_uid_gt, "uid>%s"},
856 	{Opt_euid_gt, "euid>%s"},
857 	{Opt_fowner_gt, "fowner>%s"},
858 	{Opt_uid_lt, "uid<%s"},
859 	{Opt_euid_lt, "euid<%s"},
860 	{Opt_fowner_lt, "fowner<%s"},
861 	{Opt_appraise_type, "appraise_type=%s"},
862 	{Opt_appraise_flag, "appraise_flag=%s"},
863 	{Opt_permit_directio, "permit_directio"},
864 	{Opt_pcr, "pcr=%s"},
865 	{Opt_template, "template=%s"},
866 	{Opt_keyrings, "keyrings=%s"},
867 	{Opt_err, NULL}
868 };
869 
870 static int ima_lsm_rule_init(struct ima_rule_entry *entry,
871 			     substring_t *args, int lsm_rule, int audit_type)
872 {
873 	int result;
874 
875 	if (entry->lsm[lsm_rule].rule)
876 		return -EINVAL;
877 
878 	entry->lsm[lsm_rule].args_p = match_strdup(args);
879 	if (!entry->lsm[lsm_rule].args_p)
880 		return -ENOMEM;
881 
882 	entry->lsm[lsm_rule].type = audit_type;
883 	result = security_filter_rule_init(entry->lsm[lsm_rule].type,
884 					   Audit_equal,
885 					   entry->lsm[lsm_rule].args_p,
886 					   &entry->lsm[lsm_rule].rule);
887 	if (!entry->lsm[lsm_rule].rule) {
888 		pr_warn("rule for LSM \'%s\' is undefined\n",
889 			(char *)entry->lsm[lsm_rule].args_p);
890 
891 		if (ima_rules == &ima_default_rules) {
892 			kfree(entry->lsm[lsm_rule].args_p);
893 			result = -EINVAL;
894 		} else
895 			result = 0;
896 	}
897 
898 	return result;
899 }
900 
901 static void ima_log_string_op(struct audit_buffer *ab, char *key, char *value,
902 			      bool (*rule_operator)(kuid_t, kuid_t))
903 {
904 	if (!ab)
905 		return;
906 
907 	if (rule_operator == &uid_gt)
908 		audit_log_format(ab, "%s>", key);
909 	else if (rule_operator == &uid_lt)
910 		audit_log_format(ab, "%s<", key);
911 	else
912 		audit_log_format(ab, "%s=", key);
913 	audit_log_format(ab, "%s ", value);
914 }
915 static void ima_log_string(struct audit_buffer *ab, char *key, char *value)
916 {
917 	ima_log_string_op(ab, key, value, NULL);
918 }
919 
920 /*
921  * Validating the appended signature included in the measurement list requires
922  * the file hash calculated without the appended signature (i.e., the 'd-modsig'
923  * field). Therefore, notify the user if they have the 'modsig' field but not
924  * the 'd-modsig' field in the template.
925  */
926 static void check_template_modsig(const struct ima_template_desc *template)
927 {
928 #define MSG "template with 'modsig' field also needs 'd-modsig' field\n"
929 	bool has_modsig, has_dmodsig;
930 	static bool checked;
931 	int i;
932 
933 	/* We only need to notify the user once. */
934 	if (checked)
935 		return;
936 
937 	has_modsig = has_dmodsig = false;
938 	for (i = 0; i < template->num_fields; i++) {
939 		if (!strcmp(template->fields[i]->field_id, "modsig"))
940 			has_modsig = true;
941 		else if (!strcmp(template->fields[i]->field_id, "d-modsig"))
942 			has_dmodsig = true;
943 	}
944 
945 	if (has_modsig && !has_dmodsig)
946 		pr_notice(MSG);
947 
948 	checked = true;
949 #undef MSG
950 }
951 
952 static int ima_parse_rule(char *rule, struct ima_rule_entry *entry)
953 {
954 	struct audit_buffer *ab;
955 	char *from;
956 	char *p;
957 	bool uid_token;
958 	struct ima_template_desc *template_desc;
959 	int result = 0;
960 	size_t keyrings_len;
961 
962 	ab = integrity_audit_log_start(audit_context(), GFP_KERNEL,
963 				       AUDIT_INTEGRITY_POLICY_RULE);
964 
965 	entry->uid = INVALID_UID;
966 	entry->fowner = INVALID_UID;
967 	entry->uid_op = &uid_eq;
968 	entry->fowner_op = &uid_eq;
969 	entry->action = UNKNOWN;
970 	while ((p = strsep(&rule, " \t")) != NULL) {
971 		substring_t args[MAX_OPT_ARGS];
972 		int token;
973 		unsigned long lnum;
974 
975 		if (result < 0)
976 			break;
977 		if ((*p == '\0') || (*p == ' ') || (*p == '\t'))
978 			continue;
979 		token = match_token(p, policy_tokens, args);
980 		switch (token) {
981 		case Opt_measure:
982 			ima_log_string(ab, "action", "measure");
983 
984 			if (entry->action != UNKNOWN)
985 				result = -EINVAL;
986 
987 			entry->action = MEASURE;
988 			break;
989 		case Opt_dont_measure:
990 			ima_log_string(ab, "action", "dont_measure");
991 
992 			if (entry->action != UNKNOWN)
993 				result = -EINVAL;
994 
995 			entry->action = DONT_MEASURE;
996 			break;
997 		case Opt_appraise:
998 			ima_log_string(ab, "action", "appraise");
999 
1000 			if (entry->action != UNKNOWN)
1001 				result = -EINVAL;
1002 
1003 			entry->action = APPRAISE;
1004 			break;
1005 		case Opt_dont_appraise:
1006 			ima_log_string(ab, "action", "dont_appraise");
1007 
1008 			if (entry->action != UNKNOWN)
1009 				result = -EINVAL;
1010 
1011 			entry->action = DONT_APPRAISE;
1012 			break;
1013 		case Opt_audit:
1014 			ima_log_string(ab, "action", "audit");
1015 
1016 			if (entry->action != UNKNOWN)
1017 				result = -EINVAL;
1018 
1019 			entry->action = AUDIT;
1020 			break;
1021 		case Opt_hash:
1022 			ima_log_string(ab, "action", "hash");
1023 
1024 			if (entry->action != UNKNOWN)
1025 				result = -EINVAL;
1026 
1027 			entry->action = HASH;
1028 			break;
1029 		case Opt_dont_hash:
1030 			ima_log_string(ab, "action", "dont_hash");
1031 
1032 			if (entry->action != UNKNOWN)
1033 				result = -EINVAL;
1034 
1035 			entry->action = DONT_HASH;
1036 			break;
1037 		case Opt_func:
1038 			ima_log_string(ab, "func", args[0].from);
1039 
1040 			if (entry->func)
1041 				result = -EINVAL;
1042 
1043 			if (strcmp(args[0].from, "FILE_CHECK") == 0)
1044 				entry->func = FILE_CHECK;
1045 			/* PATH_CHECK is for backwards compat */
1046 			else if (strcmp(args[0].from, "PATH_CHECK") == 0)
1047 				entry->func = FILE_CHECK;
1048 			else if (strcmp(args[0].from, "MODULE_CHECK") == 0)
1049 				entry->func = MODULE_CHECK;
1050 			else if (strcmp(args[0].from, "FIRMWARE_CHECK") == 0)
1051 				entry->func = FIRMWARE_CHECK;
1052 			else if ((strcmp(args[0].from, "FILE_MMAP") == 0)
1053 				|| (strcmp(args[0].from, "MMAP_CHECK") == 0))
1054 				entry->func = MMAP_CHECK;
1055 			else if (strcmp(args[0].from, "BPRM_CHECK") == 0)
1056 				entry->func = BPRM_CHECK;
1057 			else if (strcmp(args[0].from, "CREDS_CHECK") == 0)
1058 				entry->func = CREDS_CHECK;
1059 			else if (strcmp(args[0].from, "KEXEC_KERNEL_CHECK") ==
1060 				 0)
1061 				entry->func = KEXEC_KERNEL_CHECK;
1062 			else if (strcmp(args[0].from, "KEXEC_INITRAMFS_CHECK")
1063 				 == 0)
1064 				entry->func = KEXEC_INITRAMFS_CHECK;
1065 			else if (strcmp(args[0].from, "POLICY_CHECK") == 0)
1066 				entry->func = POLICY_CHECK;
1067 			else if (strcmp(args[0].from, "KEXEC_CMDLINE") == 0)
1068 				entry->func = KEXEC_CMDLINE;
1069 			else if (strcmp(args[0].from, "KEY_CHECK") == 0)
1070 				entry->func = KEY_CHECK;
1071 			else
1072 				result = -EINVAL;
1073 			if (!result)
1074 				entry->flags |= IMA_FUNC;
1075 			break;
1076 		case Opt_mask:
1077 			ima_log_string(ab, "mask", args[0].from);
1078 
1079 			if (entry->mask)
1080 				result = -EINVAL;
1081 
1082 			from = args[0].from;
1083 			if (*from == '^')
1084 				from++;
1085 
1086 			if ((strcmp(from, "MAY_EXEC")) == 0)
1087 				entry->mask = MAY_EXEC;
1088 			else if (strcmp(from, "MAY_WRITE") == 0)
1089 				entry->mask = MAY_WRITE;
1090 			else if (strcmp(from, "MAY_READ") == 0)
1091 				entry->mask = MAY_READ;
1092 			else if (strcmp(from, "MAY_APPEND") == 0)
1093 				entry->mask = MAY_APPEND;
1094 			else
1095 				result = -EINVAL;
1096 			if (!result)
1097 				entry->flags |= (*args[0].from == '^')
1098 				     ? IMA_INMASK : IMA_MASK;
1099 			break;
1100 		case Opt_fsmagic:
1101 			ima_log_string(ab, "fsmagic", args[0].from);
1102 
1103 			if (entry->fsmagic) {
1104 				result = -EINVAL;
1105 				break;
1106 			}
1107 
1108 			result = kstrtoul(args[0].from, 16, &entry->fsmagic);
1109 			if (!result)
1110 				entry->flags |= IMA_FSMAGIC;
1111 			break;
1112 		case Opt_fsname:
1113 			ima_log_string(ab, "fsname", args[0].from);
1114 
1115 			entry->fsname = kstrdup(args[0].from, GFP_KERNEL);
1116 			if (!entry->fsname) {
1117 				result = -ENOMEM;
1118 				break;
1119 			}
1120 			result = 0;
1121 			entry->flags |= IMA_FSNAME;
1122 			break;
1123 		case Opt_keyrings:
1124 			ima_log_string(ab, "keyrings", args[0].from);
1125 
1126 			keyrings_len = strlen(args[0].from) + 1;
1127 
1128 			if ((entry->keyrings) ||
1129 			    (entry->action != MEASURE) ||
1130 			    (entry->func != KEY_CHECK) ||
1131 			    (keyrings_len < 2)) {
1132 				result = -EINVAL;
1133 				break;
1134 			}
1135 
1136 			if (keyrings_len > ima_keyrings_len) {
1137 				char *tmpbuf;
1138 
1139 				tmpbuf = krealloc(ima_keyrings, keyrings_len,
1140 						  GFP_KERNEL);
1141 				if (!tmpbuf) {
1142 					result = -ENOMEM;
1143 					break;
1144 				}
1145 
1146 				ima_keyrings = tmpbuf;
1147 				ima_keyrings_len = keyrings_len;
1148 			}
1149 
1150 			entry->keyrings = kstrdup(args[0].from, GFP_KERNEL);
1151 			if (!entry->keyrings) {
1152 				kfree(ima_keyrings);
1153 				ima_keyrings = NULL;
1154 				ima_keyrings_len = 0;
1155 				result = -ENOMEM;
1156 				break;
1157 			}
1158 			result = 0;
1159 			entry->flags |= IMA_KEYRINGS;
1160 			break;
1161 		case Opt_fsuuid:
1162 			ima_log_string(ab, "fsuuid", args[0].from);
1163 
1164 			if (!uuid_is_null(&entry->fsuuid)) {
1165 				result = -EINVAL;
1166 				break;
1167 			}
1168 
1169 			result = uuid_parse(args[0].from, &entry->fsuuid);
1170 			if (!result)
1171 				entry->flags |= IMA_FSUUID;
1172 			break;
1173 		case Opt_uid_gt:
1174 		case Opt_euid_gt:
1175 			entry->uid_op = &uid_gt;
1176 			/* fall through */
1177 		case Opt_uid_lt:
1178 		case Opt_euid_lt:
1179 			if ((token == Opt_uid_lt) || (token == Opt_euid_lt))
1180 				entry->uid_op = &uid_lt;
1181 			/* fall through */
1182 		case Opt_uid_eq:
1183 		case Opt_euid_eq:
1184 			uid_token = (token == Opt_uid_eq) ||
1185 				    (token == Opt_uid_gt) ||
1186 				    (token == Opt_uid_lt);
1187 
1188 			ima_log_string_op(ab, uid_token ? "uid" : "euid",
1189 					  args[0].from, entry->uid_op);
1190 
1191 			if (uid_valid(entry->uid)) {
1192 				result = -EINVAL;
1193 				break;
1194 			}
1195 
1196 			result = kstrtoul(args[0].from, 10, &lnum);
1197 			if (!result) {
1198 				entry->uid = make_kuid(current_user_ns(),
1199 						       (uid_t) lnum);
1200 				if (!uid_valid(entry->uid) ||
1201 				    (uid_t)lnum != lnum)
1202 					result = -EINVAL;
1203 				else
1204 					entry->flags |= uid_token
1205 					    ? IMA_UID : IMA_EUID;
1206 			}
1207 			break;
1208 		case Opt_fowner_gt:
1209 			entry->fowner_op = &uid_gt;
1210 			/* fall through */
1211 		case Opt_fowner_lt:
1212 			if (token == Opt_fowner_lt)
1213 				entry->fowner_op = &uid_lt;
1214 			/* fall through */
1215 		case Opt_fowner_eq:
1216 			ima_log_string_op(ab, "fowner", args[0].from,
1217 					  entry->fowner_op);
1218 
1219 			if (uid_valid(entry->fowner)) {
1220 				result = -EINVAL;
1221 				break;
1222 			}
1223 
1224 			result = kstrtoul(args[0].from, 10, &lnum);
1225 			if (!result) {
1226 				entry->fowner = make_kuid(current_user_ns(), (uid_t)lnum);
1227 				if (!uid_valid(entry->fowner) || (((uid_t)lnum) != lnum))
1228 					result = -EINVAL;
1229 				else
1230 					entry->flags |= IMA_FOWNER;
1231 			}
1232 			break;
1233 		case Opt_obj_user:
1234 			ima_log_string(ab, "obj_user", args[0].from);
1235 			result = ima_lsm_rule_init(entry, args,
1236 						   LSM_OBJ_USER,
1237 						   AUDIT_OBJ_USER);
1238 			break;
1239 		case Opt_obj_role:
1240 			ima_log_string(ab, "obj_role", args[0].from);
1241 			result = ima_lsm_rule_init(entry, args,
1242 						   LSM_OBJ_ROLE,
1243 						   AUDIT_OBJ_ROLE);
1244 			break;
1245 		case Opt_obj_type:
1246 			ima_log_string(ab, "obj_type", args[0].from);
1247 			result = ima_lsm_rule_init(entry, args,
1248 						   LSM_OBJ_TYPE,
1249 						   AUDIT_OBJ_TYPE);
1250 			break;
1251 		case Opt_subj_user:
1252 			ima_log_string(ab, "subj_user", args[0].from);
1253 			result = ima_lsm_rule_init(entry, args,
1254 						   LSM_SUBJ_USER,
1255 						   AUDIT_SUBJ_USER);
1256 			break;
1257 		case Opt_subj_role:
1258 			ima_log_string(ab, "subj_role", args[0].from);
1259 			result = ima_lsm_rule_init(entry, args,
1260 						   LSM_SUBJ_ROLE,
1261 						   AUDIT_SUBJ_ROLE);
1262 			break;
1263 		case Opt_subj_type:
1264 			ima_log_string(ab, "subj_type", args[0].from);
1265 			result = ima_lsm_rule_init(entry, args,
1266 						   LSM_SUBJ_TYPE,
1267 						   AUDIT_SUBJ_TYPE);
1268 			break;
1269 		case Opt_appraise_type:
1270 			if (entry->action != APPRAISE) {
1271 				result = -EINVAL;
1272 				break;
1273 			}
1274 
1275 			ima_log_string(ab, "appraise_type", args[0].from);
1276 			if ((strcmp(args[0].from, "imasig")) == 0)
1277 				entry->flags |= IMA_DIGSIG_REQUIRED;
1278 			else if (ima_hook_supports_modsig(entry->func) &&
1279 				 strcmp(args[0].from, "imasig|modsig") == 0)
1280 				entry->flags |= IMA_DIGSIG_REQUIRED |
1281 						IMA_MODSIG_ALLOWED;
1282 			else
1283 				result = -EINVAL;
1284 			break;
1285 		case Opt_appraise_flag:
1286 			ima_log_string(ab, "appraise_flag", args[0].from);
1287 			if (strstr(args[0].from, "blacklist"))
1288 				entry->flags |= IMA_CHECK_BLACKLIST;
1289 			break;
1290 		case Opt_permit_directio:
1291 			entry->flags |= IMA_PERMIT_DIRECTIO;
1292 			break;
1293 		case Opt_pcr:
1294 			if (entry->action != MEASURE) {
1295 				result = -EINVAL;
1296 				break;
1297 			}
1298 			ima_log_string(ab, "pcr", args[0].from);
1299 
1300 			result = kstrtoint(args[0].from, 10, &entry->pcr);
1301 			if (result || INVALID_PCR(entry->pcr))
1302 				result = -EINVAL;
1303 			else
1304 				entry->flags |= IMA_PCR;
1305 
1306 			break;
1307 		case Opt_template:
1308 			ima_log_string(ab, "template", args[0].from);
1309 			if (entry->action != MEASURE) {
1310 				result = -EINVAL;
1311 				break;
1312 			}
1313 			template_desc = lookup_template_desc(args[0].from);
1314 			if (!template_desc || entry->template) {
1315 				result = -EINVAL;
1316 				break;
1317 			}
1318 
1319 			/*
1320 			 * template_desc_init_fields() does nothing if
1321 			 * the template is already initialised, so
1322 			 * it's safe to do this unconditionally
1323 			 */
1324 			template_desc_init_fields(template_desc->fmt,
1325 						 &(template_desc->fields),
1326 						 &(template_desc->num_fields));
1327 			entry->template = template_desc;
1328 			break;
1329 		case Opt_err:
1330 			ima_log_string(ab, "UNKNOWN", p);
1331 			result = -EINVAL;
1332 			break;
1333 		}
1334 	}
1335 	if (!result && (entry->action == UNKNOWN))
1336 		result = -EINVAL;
1337 	else if (entry->action == APPRAISE)
1338 		temp_ima_appraise |= ima_appraise_flag(entry->func);
1339 
1340 	if (!result && entry->flags & IMA_MODSIG_ALLOWED) {
1341 		template_desc = entry->template ? entry->template :
1342 						  ima_template_desc_current();
1343 		check_template_modsig(template_desc);
1344 	}
1345 
1346 	audit_log_format(ab, "res=%d", !result);
1347 	audit_log_end(ab);
1348 	return result;
1349 }
1350 
1351 /**
1352  * ima_parse_add_rule - add a rule to ima_policy_rules
1353  * @rule - ima measurement policy rule
1354  *
1355  * Avoid locking by allowing just one writer at a time in ima_write_policy()
1356  * Returns the length of the rule parsed, an error code on failure
1357  */
1358 ssize_t ima_parse_add_rule(char *rule)
1359 {
1360 	static const char op[] = "update_policy";
1361 	char *p;
1362 	struct ima_rule_entry *entry;
1363 	ssize_t result, len;
1364 	int audit_info = 0;
1365 
1366 	p = strsep(&rule, "\n");
1367 	len = strlen(p) + 1;
1368 	p += strspn(p, " \t");
1369 
1370 	if (*p == '#' || *p == '\0')
1371 		return len;
1372 
1373 	entry = kzalloc(sizeof(*entry), GFP_KERNEL);
1374 	if (!entry) {
1375 		integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
1376 				    NULL, op, "-ENOMEM", -ENOMEM, audit_info);
1377 		return -ENOMEM;
1378 	}
1379 
1380 	INIT_LIST_HEAD(&entry->list);
1381 
1382 	result = ima_parse_rule(p, entry);
1383 	if (result) {
1384 		kfree(entry);
1385 		integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
1386 				    NULL, op, "invalid-policy", result,
1387 				    audit_info);
1388 		return result;
1389 	}
1390 
1391 	list_add_tail(&entry->list, &ima_temp_rules);
1392 
1393 	return len;
1394 }
1395 
1396 /**
1397  * ima_delete_rules() called to cleanup invalid in-flight policy.
1398  * We don't need locking as we operate on the temp list, which is
1399  * different from the active one.  There is also only one user of
1400  * ima_delete_rules() at a time.
1401  */
1402 void ima_delete_rules(void)
1403 {
1404 	struct ima_rule_entry *entry, *tmp;
1405 	int i;
1406 
1407 	temp_ima_appraise = 0;
1408 	list_for_each_entry_safe(entry, tmp, &ima_temp_rules, list) {
1409 		for (i = 0; i < MAX_LSM_RULES; i++)
1410 			kfree(entry->lsm[i].args_p);
1411 
1412 		list_del(&entry->list);
1413 		kfree(entry);
1414 	}
1415 }
1416 
1417 #define __ima_hook_stringify(str)	(#str),
1418 
1419 const char *const func_tokens[] = {
1420 	__ima_hooks(__ima_hook_stringify)
1421 };
1422 
1423 #ifdef	CONFIG_IMA_READ_POLICY
1424 enum {
1425 	mask_exec = 0, mask_write, mask_read, mask_append
1426 };
1427 
1428 static const char *const mask_tokens[] = {
1429 	"^MAY_EXEC",
1430 	"^MAY_WRITE",
1431 	"^MAY_READ",
1432 	"^MAY_APPEND"
1433 };
1434 
1435 void *ima_policy_start(struct seq_file *m, loff_t *pos)
1436 {
1437 	loff_t l = *pos;
1438 	struct ima_rule_entry *entry;
1439 
1440 	rcu_read_lock();
1441 	list_for_each_entry_rcu(entry, ima_rules, list) {
1442 		if (!l--) {
1443 			rcu_read_unlock();
1444 			return entry;
1445 		}
1446 	}
1447 	rcu_read_unlock();
1448 	return NULL;
1449 }
1450 
1451 void *ima_policy_next(struct seq_file *m, void *v, loff_t *pos)
1452 {
1453 	struct ima_rule_entry *entry = v;
1454 
1455 	rcu_read_lock();
1456 	entry = list_entry_rcu(entry->list.next, struct ima_rule_entry, list);
1457 	rcu_read_unlock();
1458 	(*pos)++;
1459 
1460 	return (&entry->list == ima_rules) ? NULL : entry;
1461 }
1462 
1463 void ima_policy_stop(struct seq_file *m, void *v)
1464 {
1465 }
1466 
1467 #define pt(token)	policy_tokens[token].pattern
1468 #define mt(token)	mask_tokens[token]
1469 
1470 /*
1471  * policy_func_show - display the ima_hooks policy rule
1472  */
1473 static void policy_func_show(struct seq_file *m, enum ima_hooks func)
1474 {
1475 	if (func > 0 && func < MAX_CHECK)
1476 		seq_printf(m, "func=%s ", func_tokens[func]);
1477 	else
1478 		seq_printf(m, "func=%d ", func);
1479 }
1480 
1481 int ima_policy_show(struct seq_file *m, void *v)
1482 {
1483 	struct ima_rule_entry *entry = v;
1484 	int i;
1485 	char tbuf[64] = {0,};
1486 	int offset = 0;
1487 
1488 	rcu_read_lock();
1489 
1490 	if (entry->action & MEASURE)
1491 		seq_puts(m, pt(Opt_measure));
1492 	if (entry->action & DONT_MEASURE)
1493 		seq_puts(m, pt(Opt_dont_measure));
1494 	if (entry->action & APPRAISE)
1495 		seq_puts(m, pt(Opt_appraise));
1496 	if (entry->action & DONT_APPRAISE)
1497 		seq_puts(m, pt(Opt_dont_appraise));
1498 	if (entry->action & AUDIT)
1499 		seq_puts(m, pt(Opt_audit));
1500 	if (entry->action & HASH)
1501 		seq_puts(m, pt(Opt_hash));
1502 	if (entry->action & DONT_HASH)
1503 		seq_puts(m, pt(Opt_dont_hash));
1504 
1505 	seq_puts(m, " ");
1506 
1507 	if (entry->flags & IMA_FUNC)
1508 		policy_func_show(m, entry->func);
1509 
1510 	if ((entry->flags & IMA_MASK) || (entry->flags & IMA_INMASK)) {
1511 		if (entry->flags & IMA_MASK)
1512 			offset = 1;
1513 		if (entry->mask & MAY_EXEC)
1514 			seq_printf(m, pt(Opt_mask), mt(mask_exec) + offset);
1515 		if (entry->mask & MAY_WRITE)
1516 			seq_printf(m, pt(Opt_mask), mt(mask_write) + offset);
1517 		if (entry->mask & MAY_READ)
1518 			seq_printf(m, pt(Opt_mask), mt(mask_read) + offset);
1519 		if (entry->mask & MAY_APPEND)
1520 			seq_printf(m, pt(Opt_mask), mt(mask_append) + offset);
1521 		seq_puts(m, " ");
1522 	}
1523 
1524 	if (entry->flags & IMA_FSMAGIC) {
1525 		snprintf(tbuf, sizeof(tbuf), "0x%lx", entry->fsmagic);
1526 		seq_printf(m, pt(Opt_fsmagic), tbuf);
1527 		seq_puts(m, " ");
1528 	}
1529 
1530 	if (entry->flags & IMA_FSNAME) {
1531 		snprintf(tbuf, sizeof(tbuf), "%s", entry->fsname);
1532 		seq_printf(m, pt(Opt_fsname), tbuf);
1533 		seq_puts(m, " ");
1534 	}
1535 
1536 	if (entry->flags & IMA_KEYRINGS) {
1537 		if (entry->keyrings != NULL)
1538 			snprintf(tbuf, sizeof(tbuf), "%s", entry->keyrings);
1539 		seq_printf(m, pt(Opt_keyrings), tbuf);
1540 		seq_puts(m, " ");
1541 	}
1542 
1543 	if (entry->flags & IMA_PCR) {
1544 		snprintf(tbuf, sizeof(tbuf), "%d", entry->pcr);
1545 		seq_printf(m, pt(Opt_pcr), tbuf);
1546 		seq_puts(m, " ");
1547 	}
1548 
1549 	if (entry->flags & IMA_FSUUID) {
1550 		seq_printf(m, "fsuuid=%pU", &entry->fsuuid);
1551 		seq_puts(m, " ");
1552 	}
1553 
1554 	if (entry->flags & IMA_UID) {
1555 		snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->uid));
1556 		if (entry->uid_op == &uid_gt)
1557 			seq_printf(m, pt(Opt_uid_gt), tbuf);
1558 		else if (entry->uid_op == &uid_lt)
1559 			seq_printf(m, pt(Opt_uid_lt), tbuf);
1560 		else
1561 			seq_printf(m, pt(Opt_uid_eq), tbuf);
1562 		seq_puts(m, " ");
1563 	}
1564 
1565 	if (entry->flags & IMA_EUID) {
1566 		snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->uid));
1567 		if (entry->uid_op == &uid_gt)
1568 			seq_printf(m, pt(Opt_euid_gt), tbuf);
1569 		else if (entry->uid_op == &uid_lt)
1570 			seq_printf(m, pt(Opt_euid_lt), tbuf);
1571 		else
1572 			seq_printf(m, pt(Opt_euid_eq), tbuf);
1573 		seq_puts(m, " ");
1574 	}
1575 
1576 	if (entry->flags & IMA_FOWNER) {
1577 		snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->fowner));
1578 		if (entry->fowner_op == &uid_gt)
1579 			seq_printf(m, pt(Opt_fowner_gt), tbuf);
1580 		else if (entry->fowner_op == &uid_lt)
1581 			seq_printf(m, pt(Opt_fowner_lt), tbuf);
1582 		else
1583 			seq_printf(m, pt(Opt_fowner_eq), tbuf);
1584 		seq_puts(m, " ");
1585 	}
1586 
1587 	for (i = 0; i < MAX_LSM_RULES; i++) {
1588 		if (entry->lsm[i].rule) {
1589 			switch (i) {
1590 			case LSM_OBJ_USER:
1591 				seq_printf(m, pt(Opt_obj_user),
1592 					   (char *)entry->lsm[i].args_p);
1593 				break;
1594 			case LSM_OBJ_ROLE:
1595 				seq_printf(m, pt(Opt_obj_role),
1596 					   (char *)entry->lsm[i].args_p);
1597 				break;
1598 			case LSM_OBJ_TYPE:
1599 				seq_printf(m, pt(Opt_obj_type),
1600 					   (char *)entry->lsm[i].args_p);
1601 				break;
1602 			case LSM_SUBJ_USER:
1603 				seq_printf(m, pt(Opt_subj_user),
1604 					   (char *)entry->lsm[i].args_p);
1605 				break;
1606 			case LSM_SUBJ_ROLE:
1607 				seq_printf(m, pt(Opt_subj_role),
1608 					   (char *)entry->lsm[i].args_p);
1609 				break;
1610 			case LSM_SUBJ_TYPE:
1611 				seq_printf(m, pt(Opt_subj_type),
1612 					   (char *)entry->lsm[i].args_p);
1613 				break;
1614 			}
1615 			seq_puts(m, " ");
1616 		}
1617 	}
1618 	if (entry->template)
1619 		seq_printf(m, "template=%s ", entry->template->name);
1620 	if (entry->flags & IMA_DIGSIG_REQUIRED) {
1621 		if (entry->flags & IMA_MODSIG_ALLOWED)
1622 			seq_puts(m, "appraise_type=imasig|modsig ");
1623 		else
1624 			seq_puts(m, "appraise_type=imasig ");
1625 	}
1626 	if (entry->flags & IMA_CHECK_BLACKLIST)
1627 		seq_puts(m, "appraise_flag=check_blacklist ");
1628 	if (entry->flags & IMA_PERMIT_DIRECTIO)
1629 		seq_puts(m, "permit_directio ");
1630 	rcu_read_unlock();
1631 	seq_puts(m, "\n");
1632 	return 0;
1633 }
1634 #endif	/* CONFIG_IMA_READ_POLICY */
1635 
1636 #if defined(CONFIG_IMA_APPRAISE) && defined(CONFIG_INTEGRITY_TRUSTED_KEYRING)
1637 /*
1638  * ima_appraise_signature: whether IMA will appraise a given function using
1639  * an IMA digital signature. This is restricted to cases where the kernel
1640  * has a set of built-in trusted keys in order to avoid an attacker simply
1641  * loading additional keys.
1642  */
1643 bool ima_appraise_signature(enum kernel_read_file_id id)
1644 {
1645 	struct ima_rule_entry *entry;
1646 	bool found = false;
1647 	enum ima_hooks func;
1648 
1649 	if (id >= READING_MAX_ID)
1650 		return false;
1651 
1652 	func = read_idmap[id] ?: FILE_CHECK;
1653 
1654 	rcu_read_lock();
1655 	list_for_each_entry_rcu(entry, ima_rules, list) {
1656 		if (entry->action != APPRAISE)
1657 			continue;
1658 
1659 		/*
1660 		 * A generic entry will match, but otherwise require that it
1661 		 * match the func we're looking for
1662 		 */
1663 		if (entry->func && entry->func != func)
1664 			continue;
1665 
1666 		/*
1667 		 * We require this to be a digital signature, not a raw IMA
1668 		 * hash.
1669 		 */
1670 		if (entry->flags & IMA_DIGSIG_REQUIRED)
1671 			found = true;
1672 
1673 		/*
1674 		 * We've found a rule that matches, so break now even if it
1675 		 * didn't require a digital signature - a later rule that does
1676 		 * won't override it, so would be a false positive.
1677 		 */
1678 		break;
1679 	}
1680 
1681 	rcu_read_unlock();
1682 	return found;
1683 }
1684 #endif /* CONFIG_IMA_APPRAISE && CONFIG_INTEGRITY_TRUSTED_KEYRING */
1685