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