1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2008 IBM Corporation
4  * Author: Mimi Zohar <zohar@us.ibm.com>
5  *
6  * ima_policy.c
7  *	- initialize default measure policy rules
8  */
9 
10 #include <linux/init.h>
11 #include <linux/list.h>
12 #include <linux/kernel_read_file.h>
13 #include <linux/fs.h>
14 #include <linux/security.h>
15 #include <linux/magic.h>
16 #include <linux/parser.h>
17 #include <linux/slab.h>
18 #include <linux/rculist.h>
19 #include <linux/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 #define IMA_LABEL	0x0800
37 #define IMA_VALIDATE_ALGOS	0x1000
38 #define IMA_GID		0x2000
39 #define IMA_EGID	0x4000
40 #define IMA_FGROUP	0x8000
41 
42 #define UNKNOWN		0
43 #define MEASURE		0x0001	/* same as IMA_MEASURE */
44 #define DONT_MEASURE	0x0002
45 #define APPRAISE	0x0004	/* same as IMA_APPRAISE */
46 #define DONT_APPRAISE	0x0008
47 #define AUDIT		0x0040
48 #define HASH		0x0100
49 #define DONT_HASH	0x0200
50 
51 #define INVALID_PCR(a) (((a) < 0) || \
52 	(a) >= (sizeof_field(struct integrity_iint_cache, measured_pcrs) * 8))
53 
54 int ima_policy_flag;
55 static int temp_ima_appraise;
56 static int build_ima_appraise __ro_after_init;
57 
58 atomic_t ima_setxattr_allowed_hash_algorithms;
59 
60 #define MAX_LSM_RULES 6
61 enum lsm_rule_types { LSM_OBJ_USER, LSM_OBJ_ROLE, LSM_OBJ_TYPE,
62 	LSM_SUBJ_USER, LSM_SUBJ_ROLE, LSM_SUBJ_TYPE
63 };
64 
65 enum policy_types { ORIGINAL_TCB = 1, DEFAULT_TCB };
66 
67 enum policy_rule_list { IMA_DEFAULT_POLICY = 1, IMA_CUSTOM_POLICY };
68 
69 struct ima_rule_opt_list {
70 	size_t count;
71 	char *items[];
72 };
73 
74 struct ima_rule_entry {
75 	struct list_head list;
76 	int action;
77 	unsigned int flags;
78 	enum ima_hooks func;
79 	int mask;
80 	unsigned long fsmagic;
81 	uuid_t fsuuid;
82 	kuid_t uid;
83 	kgid_t gid;
84 	kuid_t fowner;
85 	kgid_t fgroup;
86 	bool (*uid_op)(kuid_t cred_uid, kuid_t rule_uid);    /* Handlers for operators       */
87 	bool (*gid_op)(kgid_t cred_gid, kgid_t rule_gid);
88 	bool (*fowner_op)(vfsuid_t vfsuid, kuid_t rule_uid); /* vfsuid_eq_kuid(), vfsuid_gt_kuid(), vfsuid_lt_kuid() */
89 	bool (*fgroup_op)(vfsgid_t vfsgid, kgid_t rule_gid); /* vfsgid_eq_kgid(), vfsgid_gt_kgid(), vfsgid_lt_kgid() */
90 	int pcr;
91 	unsigned int allowed_algos; /* bitfield of allowed hash algorithms */
92 	struct {
93 		void *rule;	/* LSM file metadata specific */
94 		char *args_p;	/* audit value */
95 		int type;	/* audit type */
96 	} lsm[MAX_LSM_RULES];
97 	char *fsname;
98 	struct ima_rule_opt_list *keyrings; /* Measure keys added to these keyrings */
99 	struct ima_rule_opt_list *label; /* Measure data grouped under this label */
100 	struct ima_template_desc *template;
101 };
102 
103 /*
104  * sanity check in case the kernels gains more hash algorithms that can
105  * fit in an unsigned int
106  */
107 static_assert(
108 	8 * sizeof(unsigned int) >= HASH_ALGO__LAST,
109 	"The bitfield allowed_algos in ima_rule_entry is too small to contain all the supported hash algorithms, consider using a bigger type");
110 
111 /*
112  * Without LSM specific knowledge, the default policy can only be
113  * written in terms of .action, .func, .mask, .fsmagic, .uid, .gid,
114  * .fowner, and .fgroup
115  */
116 
117 /*
118  * The minimum rule set to allow for full TCB coverage.  Measures all files
119  * opened or mmap for exec and everything read by root.  Dangerous because
120  * normal users can easily run the machine out of memory simply building
121  * and running executables.
122  */
123 static struct ima_rule_entry dont_measure_rules[] __ro_after_init = {
124 	{.action = DONT_MEASURE, .fsmagic = PROC_SUPER_MAGIC, .flags = IMA_FSMAGIC},
125 	{.action = DONT_MEASURE, .fsmagic = SYSFS_MAGIC, .flags = IMA_FSMAGIC},
126 	{.action = DONT_MEASURE, .fsmagic = DEBUGFS_MAGIC, .flags = IMA_FSMAGIC},
127 	{.action = DONT_MEASURE, .fsmagic = TMPFS_MAGIC, .flags = IMA_FSMAGIC},
128 	{.action = DONT_MEASURE, .fsmagic = DEVPTS_SUPER_MAGIC, .flags = IMA_FSMAGIC},
129 	{.action = DONT_MEASURE, .fsmagic = BINFMTFS_MAGIC, .flags = IMA_FSMAGIC},
130 	{.action = DONT_MEASURE, .fsmagic = SECURITYFS_MAGIC, .flags = IMA_FSMAGIC},
131 	{.action = DONT_MEASURE, .fsmagic = SELINUX_MAGIC, .flags = IMA_FSMAGIC},
132 	{.action = DONT_MEASURE, .fsmagic = SMACK_MAGIC, .flags = IMA_FSMAGIC},
133 	{.action = DONT_MEASURE, .fsmagic = CGROUP_SUPER_MAGIC,
134 	 .flags = IMA_FSMAGIC},
135 	{.action = DONT_MEASURE, .fsmagic = CGROUP2_SUPER_MAGIC,
136 	 .flags = IMA_FSMAGIC},
137 	{.action = DONT_MEASURE, .fsmagic = NSFS_MAGIC, .flags = IMA_FSMAGIC},
138 	{.action = DONT_MEASURE, .fsmagic = EFIVARFS_MAGIC, .flags = IMA_FSMAGIC}
139 };
140 
141 static struct ima_rule_entry original_measurement_rules[] __ro_after_init = {
142 	{.action = MEASURE, .func = MMAP_CHECK, .mask = MAY_EXEC,
143 	 .flags = IMA_FUNC | IMA_MASK},
144 	{.action = MEASURE, .func = BPRM_CHECK, .mask = MAY_EXEC,
145 	 .flags = IMA_FUNC | IMA_MASK},
146 	{.action = MEASURE, .func = FILE_CHECK, .mask = MAY_READ,
147 	 .uid = GLOBAL_ROOT_UID, .uid_op = &uid_eq,
148 	 .flags = IMA_FUNC | IMA_MASK | IMA_UID},
149 	{.action = MEASURE, .func = MODULE_CHECK, .flags = IMA_FUNC},
150 	{.action = MEASURE, .func = FIRMWARE_CHECK, .flags = IMA_FUNC},
151 };
152 
153 static struct ima_rule_entry default_measurement_rules[] __ro_after_init = {
154 	{.action = MEASURE, .func = MMAP_CHECK, .mask = MAY_EXEC,
155 	 .flags = IMA_FUNC | IMA_MASK},
156 	{.action = MEASURE, .func = BPRM_CHECK, .mask = MAY_EXEC,
157 	 .flags = IMA_FUNC | IMA_MASK},
158 	{.action = MEASURE, .func = FILE_CHECK, .mask = MAY_READ,
159 	 .uid = GLOBAL_ROOT_UID, .uid_op = &uid_eq,
160 	 .flags = IMA_FUNC | IMA_INMASK | IMA_EUID},
161 	{.action = MEASURE, .func = FILE_CHECK, .mask = MAY_READ,
162 	 .uid = GLOBAL_ROOT_UID, .uid_op = &uid_eq,
163 	 .flags = IMA_FUNC | IMA_INMASK | IMA_UID},
164 	{.action = MEASURE, .func = MODULE_CHECK, .flags = IMA_FUNC},
165 	{.action = MEASURE, .func = FIRMWARE_CHECK, .flags = IMA_FUNC},
166 	{.action = MEASURE, .func = POLICY_CHECK, .flags = IMA_FUNC},
167 };
168 
169 static struct ima_rule_entry default_appraise_rules[] __ro_after_init = {
170 	{.action = DONT_APPRAISE, .fsmagic = PROC_SUPER_MAGIC, .flags = IMA_FSMAGIC},
171 	{.action = DONT_APPRAISE, .fsmagic = SYSFS_MAGIC, .flags = IMA_FSMAGIC},
172 	{.action = DONT_APPRAISE, .fsmagic = DEBUGFS_MAGIC, .flags = IMA_FSMAGIC},
173 	{.action = DONT_APPRAISE, .fsmagic = TMPFS_MAGIC, .flags = IMA_FSMAGIC},
174 	{.action = DONT_APPRAISE, .fsmagic = RAMFS_MAGIC, .flags = IMA_FSMAGIC},
175 	{.action = DONT_APPRAISE, .fsmagic = DEVPTS_SUPER_MAGIC, .flags = IMA_FSMAGIC},
176 	{.action = DONT_APPRAISE, .fsmagic = BINFMTFS_MAGIC, .flags = IMA_FSMAGIC},
177 	{.action = DONT_APPRAISE, .fsmagic = SECURITYFS_MAGIC, .flags = IMA_FSMAGIC},
178 	{.action = DONT_APPRAISE, .fsmagic = SELINUX_MAGIC, .flags = IMA_FSMAGIC},
179 	{.action = DONT_APPRAISE, .fsmagic = SMACK_MAGIC, .flags = IMA_FSMAGIC},
180 	{.action = DONT_APPRAISE, .fsmagic = NSFS_MAGIC, .flags = IMA_FSMAGIC},
181 	{.action = DONT_APPRAISE, .fsmagic = EFIVARFS_MAGIC, .flags = IMA_FSMAGIC},
182 	{.action = DONT_APPRAISE, .fsmagic = CGROUP_SUPER_MAGIC, .flags = IMA_FSMAGIC},
183 	{.action = DONT_APPRAISE, .fsmagic = CGROUP2_SUPER_MAGIC, .flags = IMA_FSMAGIC},
184 #ifdef CONFIG_IMA_WRITE_POLICY
185 	{.action = APPRAISE, .func = POLICY_CHECK,
186 	.flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
187 #endif
188 #ifndef CONFIG_IMA_APPRAISE_SIGNED_INIT
189 	{.action = APPRAISE, .fowner = GLOBAL_ROOT_UID, .fowner_op = &vfsuid_eq_kuid,
190 	 .flags = IMA_FOWNER},
191 #else
192 	/* force signature */
193 	{.action = APPRAISE, .fowner = GLOBAL_ROOT_UID, .fowner_op = &vfsuid_eq_kuid,
194 	 .flags = IMA_FOWNER | IMA_DIGSIG_REQUIRED},
195 #endif
196 };
197 
198 static struct ima_rule_entry build_appraise_rules[] __ro_after_init = {
199 #ifdef CONFIG_IMA_APPRAISE_REQUIRE_MODULE_SIGS
200 	{.action = APPRAISE, .func = MODULE_CHECK,
201 	 .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
202 #endif
203 #ifdef CONFIG_IMA_APPRAISE_REQUIRE_FIRMWARE_SIGS
204 	{.action = APPRAISE, .func = FIRMWARE_CHECK,
205 	 .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
206 #endif
207 #ifdef CONFIG_IMA_APPRAISE_REQUIRE_KEXEC_SIGS
208 	{.action = APPRAISE, .func = KEXEC_KERNEL_CHECK,
209 	 .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
210 #endif
211 #ifdef CONFIG_IMA_APPRAISE_REQUIRE_POLICY_SIGS
212 	{.action = APPRAISE, .func = POLICY_CHECK,
213 	 .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
214 #endif
215 };
216 
217 static struct ima_rule_entry secure_boot_rules[] __ro_after_init = {
218 	{.action = APPRAISE, .func = MODULE_CHECK,
219 	 .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
220 	{.action = APPRAISE, .func = FIRMWARE_CHECK,
221 	 .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
222 	{.action = APPRAISE, .func = KEXEC_KERNEL_CHECK,
223 	 .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
224 	{.action = APPRAISE, .func = POLICY_CHECK,
225 	 .flags = IMA_FUNC | IMA_DIGSIG_REQUIRED},
226 };
227 
228 static struct ima_rule_entry critical_data_rules[] __ro_after_init = {
229 	{.action = MEASURE, .func = CRITICAL_DATA, .flags = IMA_FUNC},
230 };
231 
232 /* An array of architecture specific rules */
233 static struct ima_rule_entry *arch_policy_entry __ro_after_init;
234 
235 static LIST_HEAD(ima_default_rules);
236 static LIST_HEAD(ima_policy_rules);
237 static LIST_HEAD(ima_temp_rules);
238 static struct list_head __rcu *ima_rules = (struct list_head __rcu *)(&ima_default_rules);
239 
240 static int ima_policy __initdata;
241 
242 static int __init default_measure_policy_setup(char *str)
243 {
244 	if (ima_policy)
245 		return 1;
246 
247 	ima_policy = ORIGINAL_TCB;
248 	return 1;
249 }
250 __setup("ima_tcb", default_measure_policy_setup);
251 
252 static bool ima_use_appraise_tcb __initdata;
253 static bool ima_use_secure_boot __initdata;
254 static bool ima_use_critical_data __initdata;
255 static bool ima_fail_unverifiable_sigs __ro_after_init;
256 static int __init policy_setup(char *str)
257 {
258 	char *p;
259 
260 	while ((p = strsep(&str, " |\n")) != NULL) {
261 		if (*p == ' ')
262 			continue;
263 		if ((strcmp(p, "tcb") == 0) && !ima_policy)
264 			ima_policy = DEFAULT_TCB;
265 		else if (strcmp(p, "appraise_tcb") == 0)
266 			ima_use_appraise_tcb = true;
267 		else if (strcmp(p, "secure_boot") == 0)
268 			ima_use_secure_boot = true;
269 		else if (strcmp(p, "critical_data") == 0)
270 			ima_use_critical_data = true;
271 		else if (strcmp(p, "fail_securely") == 0)
272 			ima_fail_unverifiable_sigs = true;
273 		else
274 			pr_err("policy \"%s\" not found", p);
275 	}
276 
277 	return 1;
278 }
279 __setup("ima_policy=", policy_setup);
280 
281 static int __init default_appraise_policy_setup(char *str)
282 {
283 	ima_use_appraise_tcb = true;
284 	return 1;
285 }
286 __setup("ima_appraise_tcb", default_appraise_policy_setup);
287 
288 static struct ima_rule_opt_list *ima_alloc_rule_opt_list(const substring_t *src)
289 {
290 	struct ima_rule_opt_list *opt_list;
291 	size_t count = 0;
292 	char *src_copy;
293 	char *cur, *next;
294 	size_t i;
295 
296 	src_copy = match_strdup(src);
297 	if (!src_copy)
298 		return ERR_PTR(-ENOMEM);
299 
300 	next = src_copy;
301 	while ((cur = strsep(&next, "|"))) {
302 		/* Don't accept an empty list item */
303 		if (!(*cur)) {
304 			kfree(src_copy);
305 			return ERR_PTR(-EINVAL);
306 		}
307 		count++;
308 	}
309 
310 	/* Don't accept an empty list */
311 	if (!count) {
312 		kfree(src_copy);
313 		return ERR_PTR(-EINVAL);
314 	}
315 
316 	opt_list = kzalloc(struct_size(opt_list, items, count), GFP_KERNEL);
317 	if (!opt_list) {
318 		kfree(src_copy);
319 		return ERR_PTR(-ENOMEM);
320 	}
321 
322 	/*
323 	 * strsep() has already replaced all instances of '|' with '\0',
324 	 * leaving a byte sequence of NUL-terminated strings. Reference each
325 	 * string with the array of items.
326 	 *
327 	 * IMPORTANT: Ownership of the allocated buffer is transferred from
328 	 * src_copy to the first element in the items array. To free the
329 	 * buffer, kfree() must only be called on the first element of the
330 	 * array.
331 	 */
332 	for (i = 0, cur = src_copy; i < count; i++) {
333 		opt_list->items[i] = cur;
334 		cur = strchr(cur, '\0') + 1;
335 	}
336 	opt_list->count = count;
337 
338 	return opt_list;
339 }
340 
341 static void ima_free_rule_opt_list(struct ima_rule_opt_list *opt_list)
342 {
343 	if (!opt_list)
344 		return;
345 
346 	if (opt_list->count) {
347 		kfree(opt_list->items[0]);
348 		opt_list->count = 0;
349 	}
350 
351 	kfree(opt_list);
352 }
353 
354 static void ima_lsm_free_rule(struct ima_rule_entry *entry)
355 {
356 	int i;
357 
358 	for (i = 0; i < MAX_LSM_RULES; i++) {
359 		ima_filter_rule_free(entry->lsm[i].rule);
360 		kfree(entry->lsm[i].args_p);
361 	}
362 }
363 
364 static void ima_free_rule(struct ima_rule_entry *entry)
365 {
366 	if (!entry)
367 		return;
368 
369 	/*
370 	 * entry->template->fields may be allocated in ima_parse_rule() but that
371 	 * reference is owned by the corresponding ima_template_desc element in
372 	 * the defined_templates list and cannot be freed here
373 	 */
374 	kfree(entry->fsname);
375 	ima_free_rule_opt_list(entry->keyrings);
376 	ima_lsm_free_rule(entry);
377 	kfree(entry);
378 }
379 
380 static struct ima_rule_entry *ima_lsm_copy_rule(struct ima_rule_entry *entry)
381 {
382 	struct ima_rule_entry *nentry;
383 	int i;
384 
385 	/*
386 	 * Immutable elements are copied over as pointers and data; only
387 	 * lsm rules can change
388 	 */
389 	nentry = kmemdup(entry, sizeof(*nentry), GFP_KERNEL);
390 	if (!nentry)
391 		return NULL;
392 
393 	memset(nentry->lsm, 0, sizeof_field(struct ima_rule_entry, lsm));
394 
395 	for (i = 0; i < MAX_LSM_RULES; i++) {
396 		if (!entry->lsm[i].args_p)
397 			continue;
398 
399 		nentry->lsm[i].type = entry->lsm[i].type;
400 		nentry->lsm[i].args_p = entry->lsm[i].args_p;
401 
402 		ima_filter_rule_init(nentry->lsm[i].type, Audit_equal,
403 				     nentry->lsm[i].args_p,
404 				     &nentry->lsm[i].rule);
405 		if (!nentry->lsm[i].rule)
406 			pr_warn("rule for LSM \'%s\' is undefined\n",
407 				nentry->lsm[i].args_p);
408 	}
409 	return nentry;
410 }
411 
412 static int ima_lsm_update_rule(struct ima_rule_entry *entry)
413 {
414 	int i;
415 	struct ima_rule_entry *nentry;
416 
417 	nentry = ima_lsm_copy_rule(entry);
418 	if (!nentry)
419 		return -ENOMEM;
420 
421 	list_replace_rcu(&entry->list, &nentry->list);
422 	synchronize_rcu();
423 	/*
424 	 * ima_lsm_copy_rule() shallow copied all references, except for the
425 	 * LSM references, from entry to nentry so we only want to free the LSM
426 	 * references and the entry itself. All other memory references will now
427 	 * be owned by nentry.
428 	 */
429 	for (i = 0; i < MAX_LSM_RULES; i++)
430 		ima_filter_rule_free(entry->lsm[i].rule);
431 	kfree(entry);
432 
433 	return 0;
434 }
435 
436 static bool ima_rule_contains_lsm_cond(struct ima_rule_entry *entry)
437 {
438 	int i;
439 
440 	for (i = 0; i < MAX_LSM_RULES; i++)
441 		if (entry->lsm[i].args_p)
442 			return true;
443 
444 	return false;
445 }
446 
447 /*
448  * The LSM policy can be reloaded, leaving the IMA LSM based rules referring
449  * to the old, stale LSM policy.  Update the IMA LSM based rules to reflect
450  * the reloaded LSM policy.
451  */
452 static void ima_lsm_update_rules(void)
453 {
454 	struct ima_rule_entry *entry, *e;
455 	int result;
456 
457 	list_for_each_entry_safe(entry, e, &ima_policy_rules, list) {
458 		if (!ima_rule_contains_lsm_cond(entry))
459 			continue;
460 
461 		result = ima_lsm_update_rule(entry);
462 		if (result) {
463 			pr_err("lsm rule update error %d\n", result);
464 			return;
465 		}
466 	}
467 }
468 
469 int ima_lsm_policy_change(struct notifier_block *nb, unsigned long event,
470 			  void *lsm_data)
471 {
472 	if (event != LSM_POLICY_CHANGE)
473 		return NOTIFY_DONE;
474 
475 	ima_lsm_update_rules();
476 	return NOTIFY_OK;
477 }
478 
479 /**
480  * ima_match_rule_data - determine whether func_data matches the policy rule
481  * @rule: a pointer to a rule
482  * @func_data: data to match against the measure rule data
483  * @cred: a pointer to a credentials structure for user validation
484  *
485  * Returns true if func_data matches one in the rule, false otherwise.
486  */
487 static bool ima_match_rule_data(struct ima_rule_entry *rule,
488 				const char *func_data,
489 				const struct cred *cred)
490 {
491 	const struct ima_rule_opt_list *opt_list = NULL;
492 	bool matched = false;
493 	size_t i;
494 
495 	if ((rule->flags & IMA_UID) && !rule->uid_op(cred->uid, rule->uid))
496 		return false;
497 
498 	switch (rule->func) {
499 	case KEY_CHECK:
500 		if (!rule->keyrings)
501 			return true;
502 
503 		opt_list = rule->keyrings;
504 		break;
505 	case CRITICAL_DATA:
506 		if (!rule->label)
507 			return true;
508 
509 		opt_list = rule->label;
510 		break;
511 	default:
512 		return false;
513 	}
514 
515 	if (!func_data)
516 		return false;
517 
518 	for (i = 0; i < opt_list->count; i++) {
519 		if (!strcmp(opt_list->items[i], func_data)) {
520 			matched = true;
521 			break;
522 		}
523 	}
524 
525 	return matched;
526 }
527 
528 /**
529  * ima_match_rules - determine whether an inode matches the policy rule.
530  * @rule: a pointer to a rule
531  * @mnt_userns:	user namespace of the mount the inode was found from
532  * @inode: a pointer to an inode
533  * @cred: a pointer to a credentials structure for user validation
534  * @secid: the secid of the task to be validated
535  * @func: LIM hook identifier
536  * @mask: requested action (MAY_READ | MAY_WRITE | MAY_APPEND | MAY_EXEC)
537  * @func_data: func specific data, may be NULL
538  *
539  * Returns true on rule match, false on failure.
540  */
541 static bool ima_match_rules(struct ima_rule_entry *rule,
542 			    struct user_namespace *mnt_userns,
543 			    struct inode *inode, const struct cred *cred,
544 			    u32 secid, enum ima_hooks func, int mask,
545 			    const char *func_data)
546 {
547 	int i;
548 	bool result = false;
549 	struct ima_rule_entry *lsm_rule = rule;
550 	bool rule_reinitialized = false;
551 
552 	if ((rule->flags & IMA_FUNC) &&
553 	    (rule->func != func && func != POST_SETATTR))
554 		return false;
555 
556 	switch (func) {
557 	case KEY_CHECK:
558 	case CRITICAL_DATA:
559 		return ((rule->func == func) &&
560 			ima_match_rule_data(rule, func_data, cred));
561 	default:
562 		break;
563 	}
564 
565 	if ((rule->flags & IMA_MASK) &&
566 	    (rule->mask != mask && func != POST_SETATTR))
567 		return false;
568 	if ((rule->flags & IMA_INMASK) &&
569 	    (!(rule->mask & mask) && func != POST_SETATTR))
570 		return false;
571 	if ((rule->flags & IMA_FSMAGIC)
572 	    && rule->fsmagic != inode->i_sb->s_magic)
573 		return false;
574 	if ((rule->flags & IMA_FSNAME)
575 	    && strcmp(rule->fsname, inode->i_sb->s_type->name))
576 		return false;
577 	if ((rule->flags & IMA_FSUUID) &&
578 	    !uuid_equal(&rule->fsuuid, &inode->i_sb->s_uuid))
579 		return false;
580 	if ((rule->flags & IMA_UID) && !rule->uid_op(cred->uid, rule->uid))
581 		return false;
582 	if (rule->flags & IMA_EUID) {
583 		if (has_capability_noaudit(current, CAP_SETUID)) {
584 			if (!rule->uid_op(cred->euid, rule->uid)
585 			    && !rule->uid_op(cred->suid, rule->uid)
586 			    && !rule->uid_op(cred->uid, rule->uid))
587 				return false;
588 		} else if (!rule->uid_op(cred->euid, rule->uid))
589 			return false;
590 	}
591 	if ((rule->flags & IMA_GID) && !rule->gid_op(cred->gid, rule->gid))
592 		return false;
593 	if (rule->flags & IMA_EGID) {
594 		if (has_capability_noaudit(current, CAP_SETGID)) {
595 			if (!rule->gid_op(cred->egid, rule->gid)
596 			    && !rule->gid_op(cred->sgid, rule->gid)
597 			    && !rule->gid_op(cred->gid, rule->gid))
598 				return false;
599 		} else if (!rule->gid_op(cred->egid, rule->gid))
600 			return false;
601 	}
602 	if ((rule->flags & IMA_FOWNER) &&
603 	    !rule->fowner_op(i_uid_into_vfsuid(mnt_userns, inode),
604 			     rule->fowner))
605 		return false;
606 	if ((rule->flags & IMA_FGROUP) &&
607 	    !rule->fgroup_op(i_gid_into_vfsgid(mnt_userns, inode),
608 			     rule->fgroup))
609 		return false;
610 	for (i = 0; i < MAX_LSM_RULES; i++) {
611 		int rc = 0;
612 		u32 osid;
613 
614 		if (!lsm_rule->lsm[i].rule) {
615 			if (!lsm_rule->lsm[i].args_p)
616 				continue;
617 			else
618 				return false;
619 		}
620 
621 retry:
622 		switch (i) {
623 		case LSM_OBJ_USER:
624 		case LSM_OBJ_ROLE:
625 		case LSM_OBJ_TYPE:
626 			security_inode_getsecid(inode, &osid);
627 			rc = ima_filter_rule_match(osid, lsm_rule->lsm[i].type,
628 						   Audit_equal,
629 						   lsm_rule->lsm[i].rule);
630 			break;
631 		case LSM_SUBJ_USER:
632 		case LSM_SUBJ_ROLE:
633 		case LSM_SUBJ_TYPE:
634 			rc = ima_filter_rule_match(secid, lsm_rule->lsm[i].type,
635 						   Audit_equal,
636 						   lsm_rule->lsm[i].rule);
637 			break;
638 		default:
639 			break;
640 		}
641 
642 		if (rc == -ESTALE && !rule_reinitialized) {
643 			lsm_rule = ima_lsm_copy_rule(rule);
644 			if (lsm_rule) {
645 				rule_reinitialized = true;
646 				goto retry;
647 			}
648 		}
649 		if (!rc) {
650 			result = false;
651 			goto out;
652 		}
653 	}
654 	result = true;
655 
656 out:
657 	if (rule_reinitialized) {
658 		for (i = 0; i < MAX_LSM_RULES; i++)
659 			ima_filter_rule_free(lsm_rule->lsm[i].rule);
660 		kfree(lsm_rule);
661 	}
662 	return result;
663 }
664 
665 /*
666  * In addition to knowing that we need to appraise the file in general,
667  * we need to differentiate between calling hooks, for hook specific rules.
668  */
669 static int get_subaction(struct ima_rule_entry *rule, enum ima_hooks func)
670 {
671 	if (!(rule->flags & IMA_FUNC))
672 		return IMA_FILE_APPRAISE;
673 
674 	switch (func) {
675 	case MMAP_CHECK:
676 		return IMA_MMAP_APPRAISE;
677 	case BPRM_CHECK:
678 		return IMA_BPRM_APPRAISE;
679 	case CREDS_CHECK:
680 		return IMA_CREDS_APPRAISE;
681 	case FILE_CHECK:
682 	case POST_SETATTR:
683 		return IMA_FILE_APPRAISE;
684 	case MODULE_CHECK ... MAX_CHECK - 1:
685 	default:
686 		return IMA_READ_APPRAISE;
687 	}
688 }
689 
690 /**
691  * ima_match_policy - decision based on LSM and other conditions
692  * @mnt_userns:	user namespace of the mount the inode was found from
693  * @inode: pointer to an inode for which the policy decision is being made
694  * @cred: pointer to a credentials structure for which the policy decision is
695  *        being made
696  * @secid: LSM secid of the task to be validated
697  * @func: IMA hook identifier
698  * @mask: requested action (MAY_READ | MAY_WRITE | MAY_APPEND | MAY_EXEC)
699  * @pcr: set the pcr to extend
700  * @template_desc: the template that should be used for this rule
701  * @func_data: func specific data, may be NULL
702  * @allowed_algos: allowlist of hash algorithms for the IMA xattr
703  *
704  * Measure decision based on func/mask/fsmagic and LSM(subj/obj/type)
705  * conditions.
706  *
707  * Since the IMA policy may be updated multiple times we need to lock the
708  * list when walking it.  Reads are many orders of magnitude more numerous
709  * than writes so ima_match_policy() is classical RCU candidate.
710  */
711 int ima_match_policy(struct user_namespace *mnt_userns, struct inode *inode,
712 		     const struct cred *cred, u32 secid, enum ima_hooks func,
713 		     int mask, int flags, int *pcr,
714 		     struct ima_template_desc **template_desc,
715 		     const char *func_data, unsigned int *allowed_algos)
716 {
717 	struct ima_rule_entry *entry;
718 	int action = 0, actmask = flags | (flags << 1);
719 	struct list_head *ima_rules_tmp;
720 
721 	if (template_desc && !*template_desc)
722 		*template_desc = ima_template_desc_current();
723 
724 	rcu_read_lock();
725 	ima_rules_tmp = rcu_dereference(ima_rules);
726 	list_for_each_entry_rcu(entry, ima_rules_tmp, list) {
727 
728 		if (!(entry->action & actmask))
729 			continue;
730 
731 		if (!ima_match_rules(entry, mnt_userns, inode, cred, secid,
732 				     func, mask, func_data))
733 			continue;
734 
735 		action |= entry->flags & IMA_NONACTION_FLAGS;
736 
737 		action |= entry->action & IMA_DO_MASK;
738 		if (entry->action & IMA_APPRAISE) {
739 			action |= get_subaction(entry, func);
740 			action &= ~IMA_HASH;
741 			if (ima_fail_unverifiable_sigs)
742 				action |= IMA_FAIL_UNVERIFIABLE_SIGS;
743 
744 			if (allowed_algos &&
745 			    entry->flags & IMA_VALIDATE_ALGOS)
746 				*allowed_algos = entry->allowed_algos;
747 		}
748 
749 		if (entry->action & IMA_DO_MASK)
750 			actmask &= ~(entry->action | entry->action << 1);
751 		else
752 			actmask &= ~(entry->action | entry->action >> 1);
753 
754 		if ((pcr) && (entry->flags & IMA_PCR))
755 			*pcr = entry->pcr;
756 
757 		if (template_desc && entry->template)
758 			*template_desc = entry->template;
759 
760 		if (!actmask)
761 			break;
762 	}
763 	rcu_read_unlock();
764 
765 	return action;
766 }
767 
768 /**
769  * ima_update_policy_flags() - Update global IMA variables
770  *
771  * Update ima_policy_flag and ima_setxattr_allowed_hash_algorithms
772  * based on the currently loaded policy.
773  *
774  * With ima_policy_flag, the decision to short circuit out of a function
775  * or not call the function in the first place can be made earlier.
776  *
777  * With ima_setxattr_allowed_hash_algorithms, the policy can restrict the
778  * set of hash algorithms accepted when updating the security.ima xattr of
779  * a file.
780  *
781  * Context: called after a policy update and at system initialization.
782  */
783 void ima_update_policy_flags(void)
784 {
785 	struct ima_rule_entry *entry;
786 	int new_policy_flag = 0;
787 	struct list_head *ima_rules_tmp;
788 
789 	rcu_read_lock();
790 	ima_rules_tmp = rcu_dereference(ima_rules);
791 	list_for_each_entry_rcu(entry, ima_rules_tmp, list) {
792 		/*
793 		 * SETXATTR_CHECK rules do not implement a full policy check
794 		 * because rule checking would probably have an important
795 		 * performance impact on setxattr(). As a consequence, only one
796 		 * SETXATTR_CHECK can be active at a given time.
797 		 * Because we want to preserve that property, we set out to use
798 		 * atomic_cmpxchg. Either:
799 		 * - the atomic was non-zero: a setxattr hash policy is
800 		 *   already enforced, we do nothing
801 		 * - the atomic was zero: no setxattr policy was set, enable
802 		 *   the setxattr hash policy
803 		 */
804 		if (entry->func == SETXATTR_CHECK) {
805 			atomic_cmpxchg(&ima_setxattr_allowed_hash_algorithms,
806 				       0, entry->allowed_algos);
807 			/* SETXATTR_CHECK doesn't impact ima_policy_flag */
808 			continue;
809 		}
810 
811 		if (entry->action & IMA_DO_MASK)
812 			new_policy_flag |= entry->action;
813 	}
814 	rcu_read_unlock();
815 
816 	ima_appraise |= (build_ima_appraise | temp_ima_appraise);
817 	if (!ima_appraise)
818 		new_policy_flag &= ~IMA_APPRAISE;
819 
820 	ima_policy_flag = new_policy_flag;
821 }
822 
823 static int ima_appraise_flag(enum ima_hooks func)
824 {
825 	if (func == MODULE_CHECK)
826 		return IMA_APPRAISE_MODULES;
827 	else if (func == FIRMWARE_CHECK)
828 		return IMA_APPRAISE_FIRMWARE;
829 	else if (func == POLICY_CHECK)
830 		return IMA_APPRAISE_POLICY;
831 	else if (func == KEXEC_KERNEL_CHECK)
832 		return IMA_APPRAISE_KEXEC;
833 	return 0;
834 }
835 
836 static void add_rules(struct ima_rule_entry *entries, int count,
837 		      enum policy_rule_list policy_rule)
838 {
839 	int i = 0;
840 
841 	for (i = 0; i < count; i++) {
842 		struct ima_rule_entry *entry;
843 
844 		if (policy_rule & IMA_DEFAULT_POLICY)
845 			list_add_tail(&entries[i].list, &ima_default_rules);
846 
847 		if (policy_rule & IMA_CUSTOM_POLICY) {
848 			entry = kmemdup(&entries[i], sizeof(*entry),
849 					GFP_KERNEL);
850 			if (!entry)
851 				continue;
852 
853 			list_add_tail(&entry->list, &ima_policy_rules);
854 		}
855 		if (entries[i].action == APPRAISE) {
856 			if (entries != build_appraise_rules)
857 				temp_ima_appraise |=
858 					ima_appraise_flag(entries[i].func);
859 			else
860 				build_ima_appraise |=
861 					ima_appraise_flag(entries[i].func);
862 		}
863 	}
864 }
865 
866 static int ima_parse_rule(char *rule, struct ima_rule_entry *entry);
867 
868 static int __init ima_init_arch_policy(void)
869 {
870 	const char * const *arch_rules;
871 	const char * const *rules;
872 	int arch_entries = 0;
873 	int i = 0;
874 
875 	arch_rules = arch_get_ima_policy();
876 	if (!arch_rules)
877 		return arch_entries;
878 
879 	/* Get number of rules */
880 	for (rules = arch_rules; *rules != NULL; rules++)
881 		arch_entries++;
882 
883 	arch_policy_entry = kcalloc(arch_entries + 1,
884 				    sizeof(*arch_policy_entry), GFP_KERNEL);
885 	if (!arch_policy_entry)
886 		return 0;
887 
888 	/* Convert each policy string rules to struct ima_rule_entry format */
889 	for (rules = arch_rules, i = 0; *rules != NULL; rules++) {
890 		char rule[255];
891 		int result;
892 
893 		result = strscpy(rule, *rules, sizeof(rule));
894 
895 		INIT_LIST_HEAD(&arch_policy_entry[i].list);
896 		result = ima_parse_rule(rule, &arch_policy_entry[i]);
897 		if (result) {
898 			pr_warn("Skipping unknown architecture policy rule: %s\n",
899 				rule);
900 			memset(&arch_policy_entry[i], 0,
901 			       sizeof(*arch_policy_entry));
902 			continue;
903 		}
904 		i++;
905 	}
906 	return i;
907 }
908 
909 /**
910  * ima_init_policy - initialize the default measure rules.
911  *
912  * ima_rules points to either the ima_default_rules or the new ima_policy_rules.
913  */
914 void __init ima_init_policy(void)
915 {
916 	int build_appraise_entries, arch_entries;
917 
918 	/* if !ima_policy, we load NO default rules */
919 	if (ima_policy)
920 		add_rules(dont_measure_rules, ARRAY_SIZE(dont_measure_rules),
921 			  IMA_DEFAULT_POLICY);
922 
923 	switch (ima_policy) {
924 	case ORIGINAL_TCB:
925 		add_rules(original_measurement_rules,
926 			  ARRAY_SIZE(original_measurement_rules),
927 			  IMA_DEFAULT_POLICY);
928 		break;
929 	case DEFAULT_TCB:
930 		add_rules(default_measurement_rules,
931 			  ARRAY_SIZE(default_measurement_rules),
932 			  IMA_DEFAULT_POLICY);
933 		break;
934 	default:
935 		break;
936 	}
937 
938 	/*
939 	 * Based on runtime secure boot flags, insert arch specific measurement
940 	 * and appraise rules requiring file signatures for both the initial
941 	 * and custom policies, prior to other appraise rules.
942 	 * (Highest priority)
943 	 */
944 	arch_entries = ima_init_arch_policy();
945 	if (!arch_entries)
946 		pr_info("No architecture policies found\n");
947 	else
948 		add_rules(arch_policy_entry, arch_entries,
949 			  IMA_DEFAULT_POLICY | IMA_CUSTOM_POLICY);
950 
951 	/*
952 	 * Insert the builtin "secure_boot" policy rules requiring file
953 	 * signatures, prior to other appraise rules.
954 	 */
955 	if (ima_use_secure_boot)
956 		add_rules(secure_boot_rules, ARRAY_SIZE(secure_boot_rules),
957 			  IMA_DEFAULT_POLICY);
958 
959 	/*
960 	 * Insert the build time appraise rules requiring file signatures
961 	 * for both the initial and custom policies, prior to other appraise
962 	 * rules. As the secure boot rules includes all of the build time
963 	 * rules, include either one or the other set of rules, but not both.
964 	 */
965 	build_appraise_entries = ARRAY_SIZE(build_appraise_rules);
966 	if (build_appraise_entries) {
967 		if (ima_use_secure_boot)
968 			add_rules(build_appraise_rules, build_appraise_entries,
969 				  IMA_CUSTOM_POLICY);
970 		else
971 			add_rules(build_appraise_rules, build_appraise_entries,
972 				  IMA_DEFAULT_POLICY | IMA_CUSTOM_POLICY);
973 	}
974 
975 	if (ima_use_appraise_tcb)
976 		add_rules(default_appraise_rules,
977 			  ARRAY_SIZE(default_appraise_rules),
978 			  IMA_DEFAULT_POLICY);
979 
980 	if (ima_use_critical_data)
981 		add_rules(critical_data_rules,
982 			  ARRAY_SIZE(critical_data_rules),
983 			  IMA_DEFAULT_POLICY);
984 
985 	atomic_set(&ima_setxattr_allowed_hash_algorithms, 0);
986 
987 	ima_update_policy_flags();
988 }
989 
990 /* Make sure we have a valid policy, at least containing some rules. */
991 int ima_check_policy(void)
992 {
993 	if (list_empty(&ima_temp_rules))
994 		return -EINVAL;
995 	return 0;
996 }
997 
998 /**
999  * ima_update_policy - update default_rules with new measure rules
1000  *
1001  * Called on file .release to update the default rules with a complete new
1002  * policy.  What we do here is to splice ima_policy_rules and ima_temp_rules so
1003  * they make a queue.  The policy may be updated multiple times and this is the
1004  * RCU updater.
1005  *
1006  * Policy rules are never deleted so ima_policy_flag gets zeroed only once when
1007  * we switch from the default policy to user defined.
1008  */
1009 void ima_update_policy(void)
1010 {
1011 	struct list_head *policy = &ima_policy_rules;
1012 
1013 	list_splice_tail_init_rcu(&ima_temp_rules, policy, synchronize_rcu);
1014 
1015 	if (ima_rules != (struct list_head __rcu *)policy) {
1016 		ima_policy_flag = 0;
1017 
1018 		rcu_assign_pointer(ima_rules, policy);
1019 		/*
1020 		 * IMA architecture specific policy rules are specified
1021 		 * as strings and converted to an array of ima_entry_rules
1022 		 * on boot.  After loading a custom policy, free the
1023 		 * architecture specific rules stored as an array.
1024 		 */
1025 		kfree(arch_policy_entry);
1026 	}
1027 	ima_update_policy_flags();
1028 
1029 	/* Custom IMA policy has been loaded */
1030 	ima_process_queued_keys();
1031 }
1032 
1033 /* Keep the enumeration in sync with the policy_tokens! */
1034 enum policy_opt {
1035 	Opt_measure, Opt_dont_measure,
1036 	Opt_appraise, Opt_dont_appraise,
1037 	Opt_audit, Opt_hash, Opt_dont_hash,
1038 	Opt_obj_user, Opt_obj_role, Opt_obj_type,
1039 	Opt_subj_user, Opt_subj_role, Opt_subj_type,
1040 	Opt_func, Opt_mask, Opt_fsmagic, Opt_fsname, Opt_fsuuid,
1041 	Opt_uid_eq, Opt_euid_eq, Opt_gid_eq, Opt_egid_eq,
1042 	Opt_fowner_eq, Opt_fgroup_eq,
1043 	Opt_uid_gt, Opt_euid_gt, Opt_gid_gt, Opt_egid_gt,
1044 	Opt_fowner_gt, Opt_fgroup_gt,
1045 	Opt_uid_lt, Opt_euid_lt, Opt_gid_lt, Opt_egid_lt,
1046 	Opt_fowner_lt, Opt_fgroup_lt,
1047 	Opt_digest_type,
1048 	Opt_appraise_type, Opt_appraise_flag, Opt_appraise_algos,
1049 	Opt_permit_directio, Opt_pcr, Opt_template, Opt_keyrings,
1050 	Opt_label, Opt_err
1051 };
1052 
1053 static const match_table_t policy_tokens = {
1054 	{Opt_measure, "measure"},
1055 	{Opt_dont_measure, "dont_measure"},
1056 	{Opt_appraise, "appraise"},
1057 	{Opt_dont_appraise, "dont_appraise"},
1058 	{Opt_audit, "audit"},
1059 	{Opt_hash, "hash"},
1060 	{Opt_dont_hash, "dont_hash"},
1061 	{Opt_obj_user, "obj_user=%s"},
1062 	{Opt_obj_role, "obj_role=%s"},
1063 	{Opt_obj_type, "obj_type=%s"},
1064 	{Opt_subj_user, "subj_user=%s"},
1065 	{Opt_subj_role, "subj_role=%s"},
1066 	{Opt_subj_type, "subj_type=%s"},
1067 	{Opt_func, "func=%s"},
1068 	{Opt_mask, "mask=%s"},
1069 	{Opt_fsmagic, "fsmagic=%s"},
1070 	{Opt_fsname, "fsname=%s"},
1071 	{Opt_fsuuid, "fsuuid=%s"},
1072 	{Opt_uid_eq, "uid=%s"},
1073 	{Opt_euid_eq, "euid=%s"},
1074 	{Opt_gid_eq, "gid=%s"},
1075 	{Opt_egid_eq, "egid=%s"},
1076 	{Opt_fowner_eq, "fowner=%s"},
1077 	{Opt_fgroup_eq, "fgroup=%s"},
1078 	{Opt_uid_gt, "uid>%s"},
1079 	{Opt_euid_gt, "euid>%s"},
1080 	{Opt_gid_gt, "gid>%s"},
1081 	{Opt_egid_gt, "egid>%s"},
1082 	{Opt_fowner_gt, "fowner>%s"},
1083 	{Opt_fgroup_gt, "fgroup>%s"},
1084 	{Opt_uid_lt, "uid<%s"},
1085 	{Opt_euid_lt, "euid<%s"},
1086 	{Opt_gid_lt, "gid<%s"},
1087 	{Opt_egid_lt, "egid<%s"},
1088 	{Opt_fowner_lt, "fowner<%s"},
1089 	{Opt_fgroup_lt, "fgroup<%s"},
1090 	{Opt_digest_type, "digest_type=%s"},
1091 	{Opt_appraise_type, "appraise_type=%s"},
1092 	{Opt_appraise_flag, "appraise_flag=%s"},
1093 	{Opt_appraise_algos, "appraise_algos=%s"},
1094 	{Opt_permit_directio, "permit_directio"},
1095 	{Opt_pcr, "pcr=%s"},
1096 	{Opt_template, "template=%s"},
1097 	{Opt_keyrings, "keyrings=%s"},
1098 	{Opt_label, "label=%s"},
1099 	{Opt_err, NULL}
1100 };
1101 
1102 static int ima_lsm_rule_init(struct ima_rule_entry *entry,
1103 			     substring_t *args, int lsm_rule, int audit_type)
1104 {
1105 	int result;
1106 
1107 	if (entry->lsm[lsm_rule].rule)
1108 		return -EINVAL;
1109 
1110 	entry->lsm[lsm_rule].args_p = match_strdup(args);
1111 	if (!entry->lsm[lsm_rule].args_p)
1112 		return -ENOMEM;
1113 
1114 	entry->lsm[lsm_rule].type = audit_type;
1115 	result = ima_filter_rule_init(entry->lsm[lsm_rule].type, Audit_equal,
1116 				      entry->lsm[lsm_rule].args_p,
1117 				      &entry->lsm[lsm_rule].rule);
1118 	if (!entry->lsm[lsm_rule].rule) {
1119 		pr_warn("rule for LSM \'%s\' is undefined\n",
1120 			entry->lsm[lsm_rule].args_p);
1121 
1122 		if (ima_rules == (struct list_head __rcu *)(&ima_default_rules)) {
1123 			kfree(entry->lsm[lsm_rule].args_p);
1124 			entry->lsm[lsm_rule].args_p = NULL;
1125 			result = -EINVAL;
1126 		} else
1127 			result = 0;
1128 	}
1129 
1130 	return result;
1131 }
1132 
1133 static void ima_log_string_op(struct audit_buffer *ab, char *key, char *value,
1134 			      enum policy_opt rule_operator)
1135 {
1136 	if (!ab)
1137 		return;
1138 
1139 	switch (rule_operator) {
1140 	case Opt_uid_gt:
1141 	case Opt_euid_gt:
1142 	case Opt_gid_gt:
1143 	case Opt_egid_gt:
1144 	case Opt_fowner_gt:
1145 	case Opt_fgroup_gt:
1146 		audit_log_format(ab, "%s>", key);
1147 		break;
1148 	case Opt_uid_lt:
1149 	case Opt_euid_lt:
1150 	case Opt_gid_lt:
1151 	case Opt_egid_lt:
1152 	case Opt_fowner_lt:
1153 	case Opt_fgroup_lt:
1154 		audit_log_format(ab, "%s<", key);
1155 		break;
1156 	default:
1157 		audit_log_format(ab, "%s=", key);
1158 	}
1159 	audit_log_format(ab, "%s ", value);
1160 }
1161 static void ima_log_string(struct audit_buffer *ab, char *key, char *value)
1162 {
1163 	ima_log_string_op(ab, key, value, Opt_err);
1164 }
1165 
1166 /*
1167  * Validating the appended signature included in the measurement list requires
1168  * the file hash calculated without the appended signature (i.e., the 'd-modsig'
1169  * field). Therefore, notify the user if they have the 'modsig' field but not
1170  * the 'd-modsig' field in the template.
1171  */
1172 static void check_template_modsig(const struct ima_template_desc *template)
1173 {
1174 #define MSG "template with 'modsig' field also needs 'd-modsig' field\n"
1175 	bool has_modsig, has_dmodsig;
1176 	static bool checked;
1177 	int i;
1178 
1179 	/* We only need to notify the user once. */
1180 	if (checked)
1181 		return;
1182 
1183 	has_modsig = has_dmodsig = false;
1184 	for (i = 0; i < template->num_fields; i++) {
1185 		if (!strcmp(template->fields[i]->field_id, "modsig"))
1186 			has_modsig = true;
1187 		else if (!strcmp(template->fields[i]->field_id, "d-modsig"))
1188 			has_dmodsig = true;
1189 	}
1190 
1191 	if (has_modsig && !has_dmodsig)
1192 		pr_notice(MSG);
1193 
1194 	checked = true;
1195 #undef MSG
1196 }
1197 
1198 /*
1199  * Warn if the template does not contain the given field.
1200  */
1201 static void check_template_field(const struct ima_template_desc *template,
1202 				 const char *field, const char *msg)
1203 {
1204 	int i;
1205 
1206 	for (i = 0; i < template->num_fields; i++)
1207 		if (!strcmp(template->fields[i]->field_id, field))
1208 			return;
1209 
1210 	pr_notice_once("%s", msg);
1211 }
1212 
1213 static bool ima_validate_rule(struct ima_rule_entry *entry)
1214 {
1215 	/* Ensure that the action is set and is compatible with the flags */
1216 	if (entry->action == UNKNOWN)
1217 		return false;
1218 
1219 	if (entry->action != MEASURE && entry->flags & IMA_PCR)
1220 		return false;
1221 
1222 	if (entry->action != APPRAISE &&
1223 	    entry->flags & (IMA_DIGSIG_REQUIRED | IMA_MODSIG_ALLOWED |
1224 			    IMA_CHECK_BLACKLIST | IMA_VALIDATE_ALGOS))
1225 		return false;
1226 
1227 	/*
1228 	 * The IMA_FUNC bit must be set if and only if there's a valid hook
1229 	 * function specified, and vice versa. Enforcing this property allows
1230 	 * for the NONE case below to validate a rule without an explicit hook
1231 	 * function.
1232 	 */
1233 	if (((entry->flags & IMA_FUNC) && entry->func == NONE) ||
1234 	    (!(entry->flags & IMA_FUNC) && entry->func != NONE))
1235 		return false;
1236 
1237 	/*
1238 	 * Ensure that the hook function is compatible with the other
1239 	 * components of the rule
1240 	 */
1241 	switch (entry->func) {
1242 	case NONE:
1243 	case FILE_CHECK:
1244 	case MMAP_CHECK:
1245 	case BPRM_CHECK:
1246 	case CREDS_CHECK:
1247 	case POST_SETATTR:
1248 	case FIRMWARE_CHECK:
1249 	case POLICY_CHECK:
1250 		if (entry->flags & ~(IMA_FUNC | IMA_MASK | IMA_FSMAGIC |
1251 				     IMA_UID | IMA_FOWNER | IMA_FSUUID |
1252 				     IMA_INMASK | IMA_EUID | IMA_PCR |
1253 				     IMA_FSNAME | IMA_GID | IMA_EGID |
1254 				     IMA_FGROUP | IMA_DIGSIG_REQUIRED |
1255 				     IMA_PERMIT_DIRECTIO | IMA_VALIDATE_ALGOS |
1256 				     IMA_VERITY_REQUIRED))
1257 			return false;
1258 
1259 		break;
1260 	case MODULE_CHECK:
1261 	case KEXEC_KERNEL_CHECK:
1262 	case KEXEC_INITRAMFS_CHECK:
1263 		if (entry->flags & ~(IMA_FUNC | IMA_MASK | IMA_FSMAGIC |
1264 				     IMA_UID | IMA_FOWNER | IMA_FSUUID |
1265 				     IMA_INMASK | IMA_EUID | IMA_PCR |
1266 				     IMA_FSNAME | IMA_GID | IMA_EGID |
1267 				     IMA_FGROUP | IMA_DIGSIG_REQUIRED |
1268 				     IMA_PERMIT_DIRECTIO | IMA_MODSIG_ALLOWED |
1269 				     IMA_CHECK_BLACKLIST | IMA_VALIDATE_ALGOS))
1270 			return false;
1271 
1272 		break;
1273 	case KEXEC_CMDLINE:
1274 		if (entry->action & ~(MEASURE | DONT_MEASURE))
1275 			return false;
1276 
1277 		if (entry->flags & ~(IMA_FUNC | IMA_FSMAGIC | IMA_UID |
1278 				     IMA_FOWNER | IMA_FSUUID | IMA_EUID |
1279 				     IMA_PCR | IMA_FSNAME | IMA_GID | IMA_EGID |
1280 				     IMA_FGROUP))
1281 			return false;
1282 
1283 		break;
1284 	case KEY_CHECK:
1285 		if (entry->action & ~(MEASURE | DONT_MEASURE))
1286 			return false;
1287 
1288 		if (entry->flags & ~(IMA_FUNC | IMA_UID | IMA_GID | IMA_PCR |
1289 				     IMA_KEYRINGS))
1290 			return false;
1291 
1292 		if (ima_rule_contains_lsm_cond(entry))
1293 			return false;
1294 
1295 		break;
1296 	case CRITICAL_DATA:
1297 		if (entry->action & ~(MEASURE | DONT_MEASURE))
1298 			return false;
1299 
1300 		if (entry->flags & ~(IMA_FUNC | IMA_UID | IMA_GID | IMA_PCR |
1301 				     IMA_LABEL))
1302 			return false;
1303 
1304 		if (ima_rule_contains_lsm_cond(entry))
1305 			return false;
1306 
1307 		break;
1308 	case SETXATTR_CHECK:
1309 		/* any action other than APPRAISE is unsupported */
1310 		if (entry->action != APPRAISE)
1311 			return false;
1312 
1313 		/* SETXATTR_CHECK requires an appraise_algos parameter */
1314 		if (!(entry->flags & IMA_VALIDATE_ALGOS))
1315 			return false;
1316 
1317 		/*
1318 		 * full policies are not supported, they would have too
1319 		 * much of a performance impact
1320 		 */
1321 		if (entry->flags & ~(IMA_FUNC | IMA_VALIDATE_ALGOS))
1322 			return false;
1323 
1324 		break;
1325 	default:
1326 		return false;
1327 	}
1328 
1329 	/* Ensure that combinations of flags are compatible with each other */
1330 	if (entry->flags & IMA_CHECK_BLACKLIST &&
1331 	    !(entry->flags & IMA_MODSIG_ALLOWED))
1332 		return false;
1333 
1334 	/*
1335 	 * Unlike for regular IMA 'appraise' policy rules where security.ima
1336 	 * xattr may contain either a file hash or signature, the security.ima
1337 	 * xattr for fsverity must contain a file signature (sigv3).  Ensure
1338 	 * that 'appraise' rules for fsverity require file signatures by
1339 	 * checking the IMA_DIGSIG_REQUIRED flag is set.
1340 	 */
1341 	if (entry->action == APPRAISE &&
1342 	    (entry->flags & IMA_VERITY_REQUIRED) &&
1343 	    !(entry->flags & IMA_DIGSIG_REQUIRED))
1344 		return false;
1345 
1346 	return true;
1347 }
1348 
1349 static unsigned int ima_parse_appraise_algos(char *arg)
1350 {
1351 	unsigned int res = 0;
1352 	int idx;
1353 	char *token;
1354 
1355 	while ((token = strsep(&arg, ",")) != NULL) {
1356 		idx = match_string(hash_algo_name, HASH_ALGO__LAST, token);
1357 
1358 		if (idx < 0) {
1359 			pr_err("unknown hash algorithm \"%s\"",
1360 			       token);
1361 			return 0;
1362 		}
1363 
1364 		if (!crypto_has_alg(hash_algo_name[idx], 0, 0)) {
1365 			pr_err("unavailable hash algorithm \"%s\", check your kernel configuration",
1366 			       token);
1367 			return 0;
1368 		}
1369 
1370 		/* Add the hash algorithm to the 'allowed' bitfield */
1371 		res |= (1U << idx);
1372 	}
1373 
1374 	return res;
1375 }
1376 
1377 static int ima_parse_rule(char *rule, struct ima_rule_entry *entry)
1378 {
1379 	struct audit_buffer *ab;
1380 	char *from;
1381 	char *p;
1382 	bool eid_token; /* either euid or egid */
1383 	struct ima_template_desc *template_desc;
1384 	int result = 0;
1385 
1386 	ab = integrity_audit_log_start(audit_context(), GFP_KERNEL,
1387 				       AUDIT_INTEGRITY_POLICY_RULE);
1388 
1389 	entry->uid = INVALID_UID;
1390 	entry->gid = INVALID_GID;
1391 	entry->fowner = INVALID_UID;
1392 	entry->fgroup = INVALID_GID;
1393 	entry->uid_op = &uid_eq;
1394 	entry->gid_op = &gid_eq;
1395 	entry->fowner_op = &vfsuid_eq_kuid;
1396 	entry->fgroup_op = &vfsgid_eq_kgid;
1397 	entry->action = UNKNOWN;
1398 	while ((p = strsep(&rule, " \t")) != NULL) {
1399 		substring_t args[MAX_OPT_ARGS];
1400 		int token;
1401 		unsigned long lnum;
1402 
1403 		if (result < 0)
1404 			break;
1405 		if ((*p == '\0') || (*p == ' ') || (*p == '\t'))
1406 			continue;
1407 		token = match_token(p, policy_tokens, args);
1408 		switch (token) {
1409 		case Opt_measure:
1410 			ima_log_string(ab, "action", "measure");
1411 
1412 			if (entry->action != UNKNOWN)
1413 				result = -EINVAL;
1414 
1415 			entry->action = MEASURE;
1416 			break;
1417 		case Opt_dont_measure:
1418 			ima_log_string(ab, "action", "dont_measure");
1419 
1420 			if (entry->action != UNKNOWN)
1421 				result = -EINVAL;
1422 
1423 			entry->action = DONT_MEASURE;
1424 			break;
1425 		case Opt_appraise:
1426 			ima_log_string(ab, "action", "appraise");
1427 
1428 			if (entry->action != UNKNOWN)
1429 				result = -EINVAL;
1430 
1431 			entry->action = APPRAISE;
1432 			break;
1433 		case Opt_dont_appraise:
1434 			ima_log_string(ab, "action", "dont_appraise");
1435 
1436 			if (entry->action != UNKNOWN)
1437 				result = -EINVAL;
1438 
1439 			entry->action = DONT_APPRAISE;
1440 			break;
1441 		case Opt_audit:
1442 			ima_log_string(ab, "action", "audit");
1443 
1444 			if (entry->action != UNKNOWN)
1445 				result = -EINVAL;
1446 
1447 			entry->action = AUDIT;
1448 			break;
1449 		case Opt_hash:
1450 			ima_log_string(ab, "action", "hash");
1451 
1452 			if (entry->action != UNKNOWN)
1453 				result = -EINVAL;
1454 
1455 			entry->action = HASH;
1456 			break;
1457 		case Opt_dont_hash:
1458 			ima_log_string(ab, "action", "dont_hash");
1459 
1460 			if (entry->action != UNKNOWN)
1461 				result = -EINVAL;
1462 
1463 			entry->action = DONT_HASH;
1464 			break;
1465 		case Opt_func:
1466 			ima_log_string(ab, "func", args[0].from);
1467 
1468 			if (entry->func)
1469 				result = -EINVAL;
1470 
1471 			if (strcmp(args[0].from, "FILE_CHECK") == 0)
1472 				entry->func = FILE_CHECK;
1473 			/* PATH_CHECK is for backwards compat */
1474 			else if (strcmp(args[0].from, "PATH_CHECK") == 0)
1475 				entry->func = FILE_CHECK;
1476 			else if (strcmp(args[0].from, "MODULE_CHECK") == 0)
1477 				entry->func = MODULE_CHECK;
1478 			else if (strcmp(args[0].from, "FIRMWARE_CHECK") == 0)
1479 				entry->func = FIRMWARE_CHECK;
1480 			else if ((strcmp(args[0].from, "FILE_MMAP") == 0)
1481 				|| (strcmp(args[0].from, "MMAP_CHECK") == 0))
1482 				entry->func = MMAP_CHECK;
1483 			else if (strcmp(args[0].from, "BPRM_CHECK") == 0)
1484 				entry->func = BPRM_CHECK;
1485 			else if (strcmp(args[0].from, "CREDS_CHECK") == 0)
1486 				entry->func = CREDS_CHECK;
1487 			else if (strcmp(args[0].from, "KEXEC_KERNEL_CHECK") ==
1488 				 0)
1489 				entry->func = KEXEC_KERNEL_CHECK;
1490 			else if (strcmp(args[0].from, "KEXEC_INITRAMFS_CHECK")
1491 				 == 0)
1492 				entry->func = KEXEC_INITRAMFS_CHECK;
1493 			else if (strcmp(args[0].from, "POLICY_CHECK") == 0)
1494 				entry->func = POLICY_CHECK;
1495 			else if (strcmp(args[0].from, "KEXEC_CMDLINE") == 0)
1496 				entry->func = KEXEC_CMDLINE;
1497 			else if (IS_ENABLED(CONFIG_IMA_MEASURE_ASYMMETRIC_KEYS) &&
1498 				 strcmp(args[0].from, "KEY_CHECK") == 0)
1499 				entry->func = KEY_CHECK;
1500 			else if (strcmp(args[0].from, "CRITICAL_DATA") == 0)
1501 				entry->func = CRITICAL_DATA;
1502 			else if (strcmp(args[0].from, "SETXATTR_CHECK") == 0)
1503 				entry->func = SETXATTR_CHECK;
1504 			else
1505 				result = -EINVAL;
1506 			if (!result)
1507 				entry->flags |= IMA_FUNC;
1508 			break;
1509 		case Opt_mask:
1510 			ima_log_string(ab, "mask", args[0].from);
1511 
1512 			if (entry->mask)
1513 				result = -EINVAL;
1514 
1515 			from = args[0].from;
1516 			if (*from == '^')
1517 				from++;
1518 
1519 			if ((strcmp(from, "MAY_EXEC")) == 0)
1520 				entry->mask = MAY_EXEC;
1521 			else if (strcmp(from, "MAY_WRITE") == 0)
1522 				entry->mask = MAY_WRITE;
1523 			else if (strcmp(from, "MAY_READ") == 0)
1524 				entry->mask = MAY_READ;
1525 			else if (strcmp(from, "MAY_APPEND") == 0)
1526 				entry->mask = MAY_APPEND;
1527 			else
1528 				result = -EINVAL;
1529 			if (!result)
1530 				entry->flags |= (*args[0].from == '^')
1531 				     ? IMA_INMASK : IMA_MASK;
1532 			break;
1533 		case Opt_fsmagic:
1534 			ima_log_string(ab, "fsmagic", args[0].from);
1535 
1536 			if (entry->fsmagic) {
1537 				result = -EINVAL;
1538 				break;
1539 			}
1540 
1541 			result = kstrtoul(args[0].from, 16, &entry->fsmagic);
1542 			if (!result)
1543 				entry->flags |= IMA_FSMAGIC;
1544 			break;
1545 		case Opt_fsname:
1546 			ima_log_string(ab, "fsname", args[0].from);
1547 
1548 			entry->fsname = kstrdup(args[0].from, GFP_KERNEL);
1549 			if (!entry->fsname) {
1550 				result = -ENOMEM;
1551 				break;
1552 			}
1553 			result = 0;
1554 			entry->flags |= IMA_FSNAME;
1555 			break;
1556 		case Opt_keyrings:
1557 			ima_log_string(ab, "keyrings", args[0].from);
1558 
1559 			if (!IS_ENABLED(CONFIG_IMA_MEASURE_ASYMMETRIC_KEYS) ||
1560 			    entry->keyrings) {
1561 				result = -EINVAL;
1562 				break;
1563 			}
1564 
1565 			entry->keyrings = ima_alloc_rule_opt_list(args);
1566 			if (IS_ERR(entry->keyrings)) {
1567 				result = PTR_ERR(entry->keyrings);
1568 				entry->keyrings = NULL;
1569 				break;
1570 			}
1571 
1572 			entry->flags |= IMA_KEYRINGS;
1573 			break;
1574 		case Opt_label:
1575 			ima_log_string(ab, "label", args[0].from);
1576 
1577 			if (entry->label) {
1578 				result = -EINVAL;
1579 				break;
1580 			}
1581 
1582 			entry->label = ima_alloc_rule_opt_list(args);
1583 			if (IS_ERR(entry->label)) {
1584 				result = PTR_ERR(entry->label);
1585 				entry->label = NULL;
1586 				break;
1587 			}
1588 
1589 			entry->flags |= IMA_LABEL;
1590 			break;
1591 		case Opt_fsuuid:
1592 			ima_log_string(ab, "fsuuid", args[0].from);
1593 
1594 			if (!uuid_is_null(&entry->fsuuid)) {
1595 				result = -EINVAL;
1596 				break;
1597 			}
1598 
1599 			result = uuid_parse(args[0].from, &entry->fsuuid);
1600 			if (!result)
1601 				entry->flags |= IMA_FSUUID;
1602 			break;
1603 		case Opt_uid_gt:
1604 		case Opt_euid_gt:
1605 			entry->uid_op = &uid_gt;
1606 			fallthrough;
1607 		case Opt_uid_lt:
1608 		case Opt_euid_lt:
1609 			if ((token == Opt_uid_lt) || (token == Opt_euid_lt))
1610 				entry->uid_op = &uid_lt;
1611 			fallthrough;
1612 		case Opt_uid_eq:
1613 		case Opt_euid_eq:
1614 			eid_token = (token == Opt_euid_eq) ||
1615 				    (token == Opt_euid_gt) ||
1616 				    (token == Opt_euid_lt);
1617 
1618 			ima_log_string_op(ab, eid_token ? "euid" : "uid",
1619 					  args[0].from, token);
1620 
1621 			if (uid_valid(entry->uid)) {
1622 				result = -EINVAL;
1623 				break;
1624 			}
1625 
1626 			result = kstrtoul(args[0].from, 10, &lnum);
1627 			if (!result) {
1628 				entry->uid = make_kuid(current_user_ns(),
1629 						       (uid_t) lnum);
1630 				if (!uid_valid(entry->uid) ||
1631 				    (uid_t)lnum != lnum)
1632 					result = -EINVAL;
1633 				else
1634 					entry->flags |= eid_token
1635 					    ? IMA_EUID : IMA_UID;
1636 			}
1637 			break;
1638 		case Opt_gid_gt:
1639 		case Opt_egid_gt:
1640 			entry->gid_op = &gid_gt;
1641 			fallthrough;
1642 		case Opt_gid_lt:
1643 		case Opt_egid_lt:
1644 			if ((token == Opt_gid_lt) || (token == Opt_egid_lt))
1645 				entry->gid_op = &gid_lt;
1646 			fallthrough;
1647 		case Opt_gid_eq:
1648 		case Opt_egid_eq:
1649 			eid_token = (token == Opt_egid_eq) ||
1650 				    (token == Opt_egid_gt) ||
1651 				    (token == Opt_egid_lt);
1652 
1653 			ima_log_string_op(ab, eid_token ? "egid" : "gid",
1654 					  args[0].from, token);
1655 
1656 			if (gid_valid(entry->gid)) {
1657 				result = -EINVAL;
1658 				break;
1659 			}
1660 
1661 			result = kstrtoul(args[0].from, 10, &lnum);
1662 			if (!result) {
1663 				entry->gid = make_kgid(current_user_ns(),
1664 						       (gid_t)lnum);
1665 				if (!gid_valid(entry->gid) ||
1666 				    (((gid_t)lnum) != lnum))
1667 					result = -EINVAL;
1668 				else
1669 					entry->flags |= eid_token
1670 					    ? IMA_EGID : IMA_GID;
1671 			}
1672 			break;
1673 		case Opt_fowner_gt:
1674 			entry->fowner_op = &vfsuid_gt_kuid;
1675 			fallthrough;
1676 		case Opt_fowner_lt:
1677 			if (token == Opt_fowner_lt)
1678 				entry->fowner_op = &vfsuid_lt_kuid;
1679 			fallthrough;
1680 		case Opt_fowner_eq:
1681 			ima_log_string_op(ab, "fowner", args[0].from, token);
1682 
1683 			if (uid_valid(entry->fowner)) {
1684 				result = -EINVAL;
1685 				break;
1686 			}
1687 
1688 			result = kstrtoul(args[0].from, 10, &lnum);
1689 			if (!result) {
1690 				entry->fowner = make_kuid(current_user_ns(),
1691 							  (uid_t)lnum);
1692 				if (!uid_valid(entry->fowner) ||
1693 				    (((uid_t)lnum) != lnum))
1694 					result = -EINVAL;
1695 				else
1696 					entry->flags |= IMA_FOWNER;
1697 			}
1698 			break;
1699 		case Opt_fgroup_gt:
1700 			entry->fgroup_op = &vfsgid_gt_kgid;
1701 			fallthrough;
1702 		case Opt_fgroup_lt:
1703 			if (token == Opt_fgroup_lt)
1704 				entry->fgroup_op = &vfsgid_lt_kgid;
1705 			fallthrough;
1706 		case Opt_fgroup_eq:
1707 			ima_log_string_op(ab, "fgroup", args[0].from, token);
1708 
1709 			if (gid_valid(entry->fgroup)) {
1710 				result = -EINVAL;
1711 				break;
1712 			}
1713 
1714 			result = kstrtoul(args[0].from, 10, &lnum);
1715 			if (!result) {
1716 				entry->fgroup = make_kgid(current_user_ns(),
1717 							  (gid_t)lnum);
1718 				if (!gid_valid(entry->fgroup) ||
1719 				    (((gid_t)lnum) != lnum))
1720 					result = -EINVAL;
1721 				else
1722 					entry->flags |= IMA_FGROUP;
1723 			}
1724 			break;
1725 		case Opt_obj_user:
1726 			ima_log_string(ab, "obj_user", args[0].from);
1727 			result = ima_lsm_rule_init(entry, args,
1728 						   LSM_OBJ_USER,
1729 						   AUDIT_OBJ_USER);
1730 			break;
1731 		case Opt_obj_role:
1732 			ima_log_string(ab, "obj_role", args[0].from);
1733 			result = ima_lsm_rule_init(entry, args,
1734 						   LSM_OBJ_ROLE,
1735 						   AUDIT_OBJ_ROLE);
1736 			break;
1737 		case Opt_obj_type:
1738 			ima_log_string(ab, "obj_type", args[0].from);
1739 			result = ima_lsm_rule_init(entry, args,
1740 						   LSM_OBJ_TYPE,
1741 						   AUDIT_OBJ_TYPE);
1742 			break;
1743 		case Opt_subj_user:
1744 			ima_log_string(ab, "subj_user", args[0].from);
1745 			result = ima_lsm_rule_init(entry, args,
1746 						   LSM_SUBJ_USER,
1747 						   AUDIT_SUBJ_USER);
1748 			break;
1749 		case Opt_subj_role:
1750 			ima_log_string(ab, "subj_role", args[0].from);
1751 			result = ima_lsm_rule_init(entry, args,
1752 						   LSM_SUBJ_ROLE,
1753 						   AUDIT_SUBJ_ROLE);
1754 			break;
1755 		case Opt_subj_type:
1756 			ima_log_string(ab, "subj_type", args[0].from);
1757 			result = ima_lsm_rule_init(entry, args,
1758 						   LSM_SUBJ_TYPE,
1759 						   AUDIT_SUBJ_TYPE);
1760 			break;
1761 		case Opt_digest_type:
1762 			ima_log_string(ab, "digest_type", args[0].from);
1763 			if (entry->flags & IMA_DIGSIG_REQUIRED)
1764 				result = -EINVAL;
1765 			else if ((strcmp(args[0].from, "verity")) == 0)
1766 				entry->flags |= IMA_VERITY_REQUIRED;
1767 			else
1768 				result = -EINVAL;
1769 			break;
1770 		case Opt_appraise_type:
1771 			ima_log_string(ab, "appraise_type", args[0].from);
1772 
1773 			if ((strcmp(args[0].from, "imasig")) == 0) {
1774 				if (entry->flags & IMA_VERITY_REQUIRED)
1775 					result = -EINVAL;
1776 				else
1777 					entry->flags |= IMA_DIGSIG_REQUIRED;
1778 			} else if (strcmp(args[0].from, "sigv3") == 0) {
1779 				/* Only fsverity supports sigv3 for now */
1780 				if (entry->flags & IMA_VERITY_REQUIRED)
1781 					entry->flags |= IMA_DIGSIG_REQUIRED;
1782 				else
1783 					result = -EINVAL;
1784 			} else if (IS_ENABLED(CONFIG_IMA_APPRAISE_MODSIG) &&
1785 				 strcmp(args[0].from, "imasig|modsig") == 0) {
1786 				if (entry->flags & IMA_VERITY_REQUIRED)
1787 					result = -EINVAL;
1788 				else
1789 					entry->flags |= IMA_DIGSIG_REQUIRED |
1790 						IMA_MODSIG_ALLOWED;
1791 			} else {
1792 				result = -EINVAL;
1793 			}
1794 			break;
1795 		case Opt_appraise_flag:
1796 			ima_log_string(ab, "appraise_flag", args[0].from);
1797 			if (IS_ENABLED(CONFIG_IMA_APPRAISE_MODSIG) &&
1798 			    strstr(args[0].from, "blacklist"))
1799 				entry->flags |= IMA_CHECK_BLACKLIST;
1800 			else
1801 				result = -EINVAL;
1802 			break;
1803 		case Opt_appraise_algos:
1804 			ima_log_string(ab, "appraise_algos", args[0].from);
1805 
1806 			if (entry->allowed_algos) {
1807 				result = -EINVAL;
1808 				break;
1809 			}
1810 
1811 			entry->allowed_algos =
1812 				ima_parse_appraise_algos(args[0].from);
1813 			/* invalid or empty list of algorithms */
1814 			if (!entry->allowed_algos) {
1815 				result = -EINVAL;
1816 				break;
1817 			}
1818 
1819 			entry->flags |= IMA_VALIDATE_ALGOS;
1820 
1821 			break;
1822 		case Opt_permit_directio:
1823 			entry->flags |= IMA_PERMIT_DIRECTIO;
1824 			break;
1825 		case Opt_pcr:
1826 			ima_log_string(ab, "pcr", args[0].from);
1827 
1828 			result = kstrtoint(args[0].from, 10, &entry->pcr);
1829 			if (result || INVALID_PCR(entry->pcr))
1830 				result = -EINVAL;
1831 			else
1832 				entry->flags |= IMA_PCR;
1833 
1834 			break;
1835 		case Opt_template:
1836 			ima_log_string(ab, "template", args[0].from);
1837 			if (entry->action != MEASURE) {
1838 				result = -EINVAL;
1839 				break;
1840 			}
1841 			template_desc = lookup_template_desc(args[0].from);
1842 			if (!template_desc || entry->template) {
1843 				result = -EINVAL;
1844 				break;
1845 			}
1846 
1847 			/*
1848 			 * template_desc_init_fields() does nothing if
1849 			 * the template is already initialised, so
1850 			 * it's safe to do this unconditionally
1851 			 */
1852 			template_desc_init_fields(template_desc->fmt,
1853 						 &(template_desc->fields),
1854 						 &(template_desc->num_fields));
1855 			entry->template = template_desc;
1856 			break;
1857 		case Opt_err:
1858 			ima_log_string(ab, "UNKNOWN", p);
1859 			result = -EINVAL;
1860 			break;
1861 		}
1862 	}
1863 	if (!result && !ima_validate_rule(entry))
1864 		result = -EINVAL;
1865 	else if (entry->action == APPRAISE)
1866 		temp_ima_appraise |= ima_appraise_flag(entry->func);
1867 
1868 	if (!result && entry->flags & IMA_MODSIG_ALLOWED) {
1869 		template_desc = entry->template ? entry->template :
1870 						  ima_template_desc_current();
1871 		check_template_modsig(template_desc);
1872 	}
1873 
1874 	/* d-ngv2 template field recommended for unsigned fs-verity digests */
1875 	if (!result && entry->action == MEASURE &&
1876 	    entry->flags & IMA_VERITY_REQUIRED) {
1877 		template_desc = entry->template ? entry->template :
1878 						  ima_template_desc_current();
1879 		check_template_field(template_desc, "d-ngv2",
1880 				     "verity rules should include d-ngv2");
1881 	}
1882 
1883 	audit_log_format(ab, "res=%d", !result);
1884 	audit_log_end(ab);
1885 	return result;
1886 }
1887 
1888 /**
1889  * ima_parse_add_rule - add a rule to ima_policy_rules
1890  * @rule - ima measurement policy rule
1891  *
1892  * Avoid locking by allowing just one writer at a time in ima_write_policy()
1893  * Returns the length of the rule parsed, an error code on failure
1894  */
1895 ssize_t ima_parse_add_rule(char *rule)
1896 {
1897 	static const char op[] = "update_policy";
1898 	char *p;
1899 	struct ima_rule_entry *entry;
1900 	ssize_t result, len;
1901 	int audit_info = 0;
1902 
1903 	p = strsep(&rule, "\n");
1904 	len = strlen(p) + 1;
1905 	p += strspn(p, " \t");
1906 
1907 	if (*p == '#' || *p == '\0')
1908 		return len;
1909 
1910 	entry = kzalloc(sizeof(*entry), GFP_KERNEL);
1911 	if (!entry) {
1912 		integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
1913 				    NULL, op, "-ENOMEM", -ENOMEM, audit_info);
1914 		return -ENOMEM;
1915 	}
1916 
1917 	INIT_LIST_HEAD(&entry->list);
1918 
1919 	result = ima_parse_rule(p, entry);
1920 	if (result) {
1921 		ima_free_rule(entry);
1922 		integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
1923 				    NULL, op, "invalid-policy", result,
1924 				    audit_info);
1925 		return result;
1926 	}
1927 
1928 	list_add_tail(&entry->list, &ima_temp_rules);
1929 
1930 	return len;
1931 }
1932 
1933 /**
1934  * ima_delete_rules() called to cleanup invalid in-flight policy.
1935  * We don't need locking as we operate on the temp list, which is
1936  * different from the active one.  There is also only one user of
1937  * ima_delete_rules() at a time.
1938  */
1939 void ima_delete_rules(void)
1940 {
1941 	struct ima_rule_entry *entry, *tmp;
1942 
1943 	temp_ima_appraise = 0;
1944 	list_for_each_entry_safe(entry, tmp, &ima_temp_rules, list) {
1945 		list_del(&entry->list);
1946 		ima_free_rule(entry);
1947 	}
1948 }
1949 
1950 #define __ima_hook_stringify(func, str)	(#func),
1951 
1952 const char *const func_tokens[] = {
1953 	__ima_hooks(__ima_hook_stringify)
1954 };
1955 
1956 #ifdef	CONFIG_IMA_READ_POLICY
1957 enum {
1958 	mask_exec = 0, mask_write, mask_read, mask_append
1959 };
1960 
1961 static const char *const mask_tokens[] = {
1962 	"^MAY_EXEC",
1963 	"^MAY_WRITE",
1964 	"^MAY_READ",
1965 	"^MAY_APPEND"
1966 };
1967 
1968 void *ima_policy_start(struct seq_file *m, loff_t *pos)
1969 {
1970 	loff_t l = *pos;
1971 	struct ima_rule_entry *entry;
1972 	struct list_head *ima_rules_tmp;
1973 
1974 	rcu_read_lock();
1975 	ima_rules_tmp = rcu_dereference(ima_rules);
1976 	list_for_each_entry_rcu(entry, ima_rules_tmp, list) {
1977 		if (!l--) {
1978 			rcu_read_unlock();
1979 			return entry;
1980 		}
1981 	}
1982 	rcu_read_unlock();
1983 	return NULL;
1984 }
1985 
1986 void *ima_policy_next(struct seq_file *m, void *v, loff_t *pos)
1987 {
1988 	struct ima_rule_entry *entry = v;
1989 
1990 	rcu_read_lock();
1991 	entry = list_entry_rcu(entry->list.next, struct ima_rule_entry, list);
1992 	rcu_read_unlock();
1993 	(*pos)++;
1994 
1995 	return (&entry->list == &ima_default_rules ||
1996 		&entry->list == &ima_policy_rules) ? NULL : entry;
1997 }
1998 
1999 void ima_policy_stop(struct seq_file *m, void *v)
2000 {
2001 }
2002 
2003 #define pt(token)	policy_tokens[token].pattern
2004 #define mt(token)	mask_tokens[token]
2005 
2006 /*
2007  * policy_func_show - display the ima_hooks policy rule
2008  */
2009 static void policy_func_show(struct seq_file *m, enum ima_hooks func)
2010 {
2011 	if (func > 0 && func < MAX_CHECK)
2012 		seq_printf(m, "func=%s ", func_tokens[func]);
2013 	else
2014 		seq_printf(m, "func=%d ", func);
2015 }
2016 
2017 static void ima_show_rule_opt_list(struct seq_file *m,
2018 				   const struct ima_rule_opt_list *opt_list)
2019 {
2020 	size_t i;
2021 
2022 	for (i = 0; i < opt_list->count; i++)
2023 		seq_printf(m, "%s%s", i ? "|" : "", opt_list->items[i]);
2024 }
2025 
2026 static void ima_policy_show_appraise_algos(struct seq_file *m,
2027 					   unsigned int allowed_hashes)
2028 {
2029 	int idx, list_size = 0;
2030 
2031 	for (idx = 0; idx < HASH_ALGO__LAST; idx++) {
2032 		if (!(allowed_hashes & (1U << idx)))
2033 			continue;
2034 
2035 		/* only add commas if the list contains multiple entries */
2036 		if (list_size++)
2037 			seq_puts(m, ",");
2038 
2039 		seq_puts(m, hash_algo_name[idx]);
2040 	}
2041 }
2042 
2043 int ima_policy_show(struct seq_file *m, void *v)
2044 {
2045 	struct ima_rule_entry *entry = v;
2046 	int i;
2047 	char tbuf[64] = {0,};
2048 	int offset = 0;
2049 
2050 	rcu_read_lock();
2051 
2052 	/* Do not print rules with inactive LSM labels */
2053 	for (i = 0; i < MAX_LSM_RULES; i++) {
2054 		if (entry->lsm[i].args_p && !entry->lsm[i].rule) {
2055 			rcu_read_unlock();
2056 			return 0;
2057 		}
2058 	}
2059 
2060 	if (entry->action & MEASURE)
2061 		seq_puts(m, pt(Opt_measure));
2062 	if (entry->action & DONT_MEASURE)
2063 		seq_puts(m, pt(Opt_dont_measure));
2064 	if (entry->action & APPRAISE)
2065 		seq_puts(m, pt(Opt_appraise));
2066 	if (entry->action & DONT_APPRAISE)
2067 		seq_puts(m, pt(Opt_dont_appraise));
2068 	if (entry->action & AUDIT)
2069 		seq_puts(m, pt(Opt_audit));
2070 	if (entry->action & HASH)
2071 		seq_puts(m, pt(Opt_hash));
2072 	if (entry->action & DONT_HASH)
2073 		seq_puts(m, pt(Opt_dont_hash));
2074 
2075 	seq_puts(m, " ");
2076 
2077 	if (entry->flags & IMA_FUNC)
2078 		policy_func_show(m, entry->func);
2079 
2080 	if ((entry->flags & IMA_MASK) || (entry->flags & IMA_INMASK)) {
2081 		if (entry->flags & IMA_MASK)
2082 			offset = 1;
2083 		if (entry->mask & MAY_EXEC)
2084 			seq_printf(m, pt(Opt_mask), mt(mask_exec) + offset);
2085 		if (entry->mask & MAY_WRITE)
2086 			seq_printf(m, pt(Opt_mask), mt(mask_write) + offset);
2087 		if (entry->mask & MAY_READ)
2088 			seq_printf(m, pt(Opt_mask), mt(mask_read) + offset);
2089 		if (entry->mask & MAY_APPEND)
2090 			seq_printf(m, pt(Opt_mask), mt(mask_append) + offset);
2091 		seq_puts(m, " ");
2092 	}
2093 
2094 	if (entry->flags & IMA_FSMAGIC) {
2095 		snprintf(tbuf, sizeof(tbuf), "0x%lx", entry->fsmagic);
2096 		seq_printf(m, pt(Opt_fsmagic), tbuf);
2097 		seq_puts(m, " ");
2098 	}
2099 
2100 	if (entry->flags & IMA_FSNAME) {
2101 		snprintf(tbuf, sizeof(tbuf), "%s", entry->fsname);
2102 		seq_printf(m, pt(Opt_fsname), tbuf);
2103 		seq_puts(m, " ");
2104 	}
2105 
2106 	if (entry->flags & IMA_KEYRINGS) {
2107 		seq_puts(m, "keyrings=");
2108 		ima_show_rule_opt_list(m, entry->keyrings);
2109 		seq_puts(m, " ");
2110 	}
2111 
2112 	if (entry->flags & IMA_LABEL) {
2113 		seq_puts(m, "label=");
2114 		ima_show_rule_opt_list(m, entry->label);
2115 		seq_puts(m, " ");
2116 	}
2117 
2118 	if (entry->flags & IMA_PCR) {
2119 		snprintf(tbuf, sizeof(tbuf), "%d", entry->pcr);
2120 		seq_printf(m, pt(Opt_pcr), tbuf);
2121 		seq_puts(m, " ");
2122 	}
2123 
2124 	if (entry->flags & IMA_FSUUID) {
2125 		seq_printf(m, "fsuuid=%pU", &entry->fsuuid);
2126 		seq_puts(m, " ");
2127 	}
2128 
2129 	if (entry->flags & IMA_UID) {
2130 		snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->uid));
2131 		if (entry->uid_op == &uid_gt)
2132 			seq_printf(m, pt(Opt_uid_gt), tbuf);
2133 		else if (entry->uid_op == &uid_lt)
2134 			seq_printf(m, pt(Opt_uid_lt), tbuf);
2135 		else
2136 			seq_printf(m, pt(Opt_uid_eq), tbuf);
2137 		seq_puts(m, " ");
2138 	}
2139 
2140 	if (entry->flags & IMA_EUID) {
2141 		snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->uid));
2142 		if (entry->uid_op == &uid_gt)
2143 			seq_printf(m, pt(Opt_euid_gt), tbuf);
2144 		else if (entry->uid_op == &uid_lt)
2145 			seq_printf(m, pt(Opt_euid_lt), tbuf);
2146 		else
2147 			seq_printf(m, pt(Opt_euid_eq), tbuf);
2148 		seq_puts(m, " ");
2149 	}
2150 
2151 	if (entry->flags & IMA_GID) {
2152 		snprintf(tbuf, sizeof(tbuf), "%d", __kgid_val(entry->gid));
2153 		if (entry->gid_op == &gid_gt)
2154 			seq_printf(m, pt(Opt_gid_gt), tbuf);
2155 		else if (entry->gid_op == &gid_lt)
2156 			seq_printf(m, pt(Opt_gid_lt), tbuf);
2157 		else
2158 			seq_printf(m, pt(Opt_gid_eq), tbuf);
2159 		seq_puts(m, " ");
2160 	}
2161 
2162 	if (entry->flags & IMA_EGID) {
2163 		snprintf(tbuf, sizeof(tbuf), "%d", __kgid_val(entry->gid));
2164 		if (entry->gid_op == &gid_gt)
2165 			seq_printf(m, pt(Opt_egid_gt), tbuf);
2166 		else if (entry->gid_op == &gid_lt)
2167 			seq_printf(m, pt(Opt_egid_lt), tbuf);
2168 		else
2169 			seq_printf(m, pt(Opt_egid_eq), tbuf);
2170 		seq_puts(m, " ");
2171 	}
2172 
2173 	if (entry->flags & IMA_FOWNER) {
2174 		snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->fowner));
2175 		if (entry->fowner_op == &vfsuid_gt_kuid)
2176 			seq_printf(m, pt(Opt_fowner_gt), tbuf);
2177 		else if (entry->fowner_op == &vfsuid_lt_kuid)
2178 			seq_printf(m, pt(Opt_fowner_lt), tbuf);
2179 		else
2180 			seq_printf(m, pt(Opt_fowner_eq), tbuf);
2181 		seq_puts(m, " ");
2182 	}
2183 
2184 	if (entry->flags & IMA_FGROUP) {
2185 		snprintf(tbuf, sizeof(tbuf), "%d", __kgid_val(entry->fgroup));
2186 		if (entry->fgroup_op == &vfsgid_gt_kgid)
2187 			seq_printf(m, pt(Opt_fgroup_gt), tbuf);
2188 		else if (entry->fgroup_op == &vfsgid_lt_kgid)
2189 			seq_printf(m, pt(Opt_fgroup_lt), tbuf);
2190 		else
2191 			seq_printf(m, pt(Opt_fgroup_eq), tbuf);
2192 		seq_puts(m, " ");
2193 	}
2194 
2195 	if (entry->flags & IMA_VALIDATE_ALGOS) {
2196 		seq_puts(m, "appraise_algos=");
2197 		ima_policy_show_appraise_algos(m, entry->allowed_algos);
2198 		seq_puts(m, " ");
2199 	}
2200 
2201 	for (i = 0; i < MAX_LSM_RULES; i++) {
2202 		if (entry->lsm[i].rule) {
2203 			switch (i) {
2204 			case LSM_OBJ_USER:
2205 				seq_printf(m, pt(Opt_obj_user),
2206 					   entry->lsm[i].args_p);
2207 				break;
2208 			case LSM_OBJ_ROLE:
2209 				seq_printf(m, pt(Opt_obj_role),
2210 					   entry->lsm[i].args_p);
2211 				break;
2212 			case LSM_OBJ_TYPE:
2213 				seq_printf(m, pt(Opt_obj_type),
2214 					   entry->lsm[i].args_p);
2215 				break;
2216 			case LSM_SUBJ_USER:
2217 				seq_printf(m, pt(Opt_subj_user),
2218 					   entry->lsm[i].args_p);
2219 				break;
2220 			case LSM_SUBJ_ROLE:
2221 				seq_printf(m, pt(Opt_subj_role),
2222 					   entry->lsm[i].args_p);
2223 				break;
2224 			case LSM_SUBJ_TYPE:
2225 				seq_printf(m, pt(Opt_subj_type),
2226 					   entry->lsm[i].args_p);
2227 				break;
2228 			}
2229 			seq_puts(m, " ");
2230 		}
2231 	}
2232 	if (entry->template)
2233 		seq_printf(m, "template=%s ", entry->template->name);
2234 	if (entry->flags & IMA_DIGSIG_REQUIRED) {
2235 		if (entry->flags & IMA_VERITY_REQUIRED)
2236 			seq_puts(m, "appraise_type=sigv3 ");
2237 		else if (entry->flags & IMA_MODSIG_ALLOWED)
2238 			seq_puts(m, "appraise_type=imasig|modsig ");
2239 		else
2240 			seq_puts(m, "appraise_type=imasig ");
2241 	}
2242 	if (entry->flags & IMA_VERITY_REQUIRED)
2243 		seq_puts(m, "digest_type=verity ");
2244 	if (entry->flags & IMA_CHECK_BLACKLIST)
2245 		seq_puts(m, "appraise_flag=check_blacklist ");
2246 	if (entry->flags & IMA_PERMIT_DIRECTIO)
2247 		seq_puts(m, "permit_directio ");
2248 	rcu_read_unlock();
2249 	seq_puts(m, "\n");
2250 	return 0;
2251 }
2252 #endif	/* CONFIG_IMA_READ_POLICY */
2253 
2254 #if defined(CONFIG_IMA_APPRAISE) && defined(CONFIG_INTEGRITY_TRUSTED_KEYRING)
2255 /*
2256  * ima_appraise_signature: whether IMA will appraise a given function using
2257  * an IMA digital signature. This is restricted to cases where the kernel
2258  * has a set of built-in trusted keys in order to avoid an attacker simply
2259  * loading additional keys.
2260  */
2261 bool ima_appraise_signature(enum kernel_read_file_id id)
2262 {
2263 	struct ima_rule_entry *entry;
2264 	bool found = false;
2265 	enum ima_hooks func;
2266 	struct list_head *ima_rules_tmp;
2267 
2268 	if (id >= READING_MAX_ID)
2269 		return false;
2270 
2271 	if (id == READING_KEXEC_IMAGE && !(ima_appraise & IMA_APPRAISE_ENFORCE)
2272 	    && security_locked_down(LOCKDOWN_KEXEC))
2273 		return false;
2274 
2275 	func = read_idmap[id] ?: FILE_CHECK;
2276 
2277 	rcu_read_lock();
2278 	ima_rules_tmp = rcu_dereference(ima_rules);
2279 	list_for_each_entry_rcu(entry, ima_rules_tmp, list) {
2280 		if (entry->action != APPRAISE)
2281 			continue;
2282 
2283 		/*
2284 		 * A generic entry will match, but otherwise require that it
2285 		 * match the func we're looking for
2286 		 */
2287 		if (entry->func && entry->func != func)
2288 			continue;
2289 
2290 		/*
2291 		 * We require this to be a digital signature, not a raw IMA
2292 		 * hash.
2293 		 */
2294 		if (entry->flags & IMA_DIGSIG_REQUIRED)
2295 			found = true;
2296 
2297 		/*
2298 		 * We've found a rule that matches, so break now even if it
2299 		 * didn't require a digital signature - a later rule that does
2300 		 * won't override it, so would be a false positive.
2301 		 */
2302 		break;
2303 	}
2304 
2305 	rcu_read_unlock();
2306 	return found;
2307 }
2308 #endif /* CONFIG_IMA_APPRAISE && CONFIG_INTEGRITY_TRUSTED_KEYRING */
2309