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