xref: /linux/security/integrity/ima/ima_policy.c (revision 011b1134b82c2750d83a299a1369c678845de45a)
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  * @secid: the secid 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 			    u32 secid, 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 		u32 osid;
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_getsecid(inode, &osid);
653 			rc = ima_filter_rule_match(osid, lsm_rule->lsm[i].type,
654 						   Audit_equal,
655 						   lsm_rule->lsm[i].rule);
656 			break;
657 		case LSM_SUBJ_USER:
658 		case LSM_SUBJ_ROLE:
659 		case LSM_SUBJ_TYPE:
660 			rc = ima_filter_rule_match(secid, lsm_rule->lsm[i].type,
661 						   Audit_equal,
662 						   lsm_rule->lsm[i].rule);
663 			break;
664 		default:
665 			break;
666 		}
667 
668 		if (rc == -ESTALE && !rule_reinitialized) {
669 			lsm_rule = ima_lsm_copy_rule(rule, GFP_ATOMIC);
670 			if (lsm_rule) {
671 				rule_reinitialized = true;
672 				goto retry;
673 			}
674 		}
675 		if (!rc) {
676 			result = false;
677 			goto out;
678 		}
679 	}
680 	result = true;
681 
682 out:
683 	if (rule_reinitialized) {
684 		for (i = 0; i < MAX_LSM_RULES; i++)
685 			ima_filter_rule_free(lsm_rule->lsm[i].rule);
686 		kfree(lsm_rule);
687 	}
688 	return result;
689 }
690 
691 /*
692  * In addition to knowing that we need to appraise the file in general,
693  * we need to differentiate between calling hooks, for hook specific rules.
694  */
695 static int get_subaction(struct ima_rule_entry *rule, enum ima_hooks func)
696 {
697 	if (!(rule->flags & IMA_FUNC))
698 		return IMA_FILE_APPRAISE;
699 
700 	switch (func) {
701 	case MMAP_CHECK:
702 	case MMAP_CHECK_REQPROT:
703 		return IMA_MMAP_APPRAISE;
704 	case BPRM_CHECK:
705 		return IMA_BPRM_APPRAISE;
706 	case CREDS_CHECK:
707 		return IMA_CREDS_APPRAISE;
708 	case FILE_CHECK:
709 	case POST_SETATTR:
710 		return IMA_FILE_APPRAISE;
711 	case MODULE_CHECK ... MAX_CHECK - 1:
712 	default:
713 		return IMA_READ_APPRAISE;
714 	}
715 }
716 
717 /**
718  * ima_match_policy - decision based on LSM and other conditions
719  * @idmap: idmap of the mount the inode was found from
720  * @inode: pointer to an inode for which the policy decision is being made
721  * @cred: pointer to a credentials structure for which the policy decision is
722  *        being made
723  * @secid: LSM secid of the task to be validated
724  * @func: IMA hook identifier
725  * @mask: requested action (MAY_READ | MAY_WRITE | MAY_APPEND | MAY_EXEC)
726  * @flags: IMA actions to consider (e.g. IMA_MEASURE | IMA_APPRAISE)
727  * @pcr: set the pcr to extend
728  * @template_desc: the template that should be used for this rule
729  * @func_data: func specific data, may be NULL
730  * @allowed_algos: allowlist of hash algorithms for the IMA xattr
731  *
732  * Measure decision based on func/mask/fsmagic and LSM(subj/obj/type)
733  * conditions.
734  *
735  * Since the IMA policy may be updated multiple times we need to lock the
736  * list when walking it.  Reads are many orders of magnitude more numerous
737  * than writes so ima_match_policy() is classical RCU candidate.
738  */
739 int ima_match_policy(struct mnt_idmap *idmap, struct inode *inode,
740 		     const struct cred *cred, u32 secid, enum ima_hooks func,
741 		     int mask, int flags, int *pcr,
742 		     struct ima_template_desc **template_desc,
743 		     const char *func_data, unsigned int *allowed_algos)
744 {
745 	struct ima_rule_entry *entry;
746 	int action = 0, actmask = flags | (flags << 1);
747 	struct list_head *ima_rules_tmp;
748 
749 	if (template_desc && !*template_desc)
750 		*template_desc = ima_template_desc_current();
751 
752 	rcu_read_lock();
753 	ima_rules_tmp = rcu_dereference(ima_rules);
754 	list_for_each_entry_rcu(entry, ima_rules_tmp, list) {
755 
756 		if (!(entry->action & actmask))
757 			continue;
758 
759 		if (!ima_match_rules(entry, idmap, inode, cred, secid,
760 				     func, mask, func_data))
761 			continue;
762 
763 		action |= entry->flags & IMA_NONACTION_FLAGS;
764 
765 		action |= entry->action & IMA_DO_MASK;
766 		if (entry->action & IMA_APPRAISE) {
767 			action |= get_subaction(entry, func);
768 			action &= ~IMA_HASH;
769 			if (ima_fail_unverifiable_sigs)
770 				action |= IMA_FAIL_UNVERIFIABLE_SIGS;
771 
772 			if (allowed_algos &&
773 			    entry->flags & IMA_VALIDATE_ALGOS)
774 				*allowed_algos = entry->allowed_algos;
775 		}
776 
777 		if (entry->action & IMA_DO_MASK)
778 			actmask &= ~(entry->action | entry->action << 1);
779 		else
780 			actmask &= ~(entry->action | entry->action >> 1);
781 
782 		if ((pcr) && (entry->flags & IMA_PCR))
783 			*pcr = entry->pcr;
784 
785 		if (template_desc && entry->template)
786 			*template_desc = entry->template;
787 
788 		if (!actmask)
789 			break;
790 	}
791 	rcu_read_unlock();
792 
793 	return action;
794 }
795 
796 /**
797  * ima_update_policy_flags() - Update global IMA variables
798  *
799  * Update ima_policy_flag and ima_setxattr_allowed_hash_algorithms
800  * based on the currently loaded policy.
801  *
802  * With ima_policy_flag, the decision to short circuit out of a function
803  * or not call the function in the first place can be made earlier.
804  *
805  * With ima_setxattr_allowed_hash_algorithms, the policy can restrict the
806  * set of hash algorithms accepted when updating the security.ima xattr of
807  * a file.
808  *
809  * Context: called after a policy update and at system initialization.
810  */
811 void ima_update_policy_flags(void)
812 {
813 	struct ima_rule_entry *entry;
814 	int new_policy_flag = 0;
815 	struct list_head *ima_rules_tmp;
816 
817 	rcu_read_lock();
818 	ima_rules_tmp = rcu_dereference(ima_rules);
819 	list_for_each_entry_rcu(entry, ima_rules_tmp, list) {
820 		/*
821 		 * SETXATTR_CHECK rules do not implement a full policy check
822 		 * because rule checking would probably have an important
823 		 * performance impact on setxattr(). As a consequence, only one
824 		 * SETXATTR_CHECK can be active at a given time.
825 		 * Because we want to preserve that property, we set out to use
826 		 * atomic_cmpxchg. Either:
827 		 * - the atomic was non-zero: a setxattr hash policy is
828 		 *   already enforced, we do nothing
829 		 * - the atomic was zero: no setxattr policy was set, enable
830 		 *   the setxattr hash policy
831 		 */
832 		if (entry->func == SETXATTR_CHECK) {
833 			atomic_cmpxchg(&ima_setxattr_allowed_hash_algorithms,
834 				       0, entry->allowed_algos);
835 			/* SETXATTR_CHECK doesn't impact ima_policy_flag */
836 			continue;
837 		}
838 
839 		if (entry->action & IMA_DO_MASK)
840 			new_policy_flag |= entry->action;
841 	}
842 	rcu_read_unlock();
843 
844 	ima_appraise |= (build_ima_appraise | temp_ima_appraise);
845 	if (!ima_appraise)
846 		new_policy_flag &= ~IMA_APPRAISE;
847 
848 	ima_policy_flag = new_policy_flag;
849 }
850 
851 static int ima_appraise_flag(enum ima_hooks func)
852 {
853 	if (func == MODULE_CHECK)
854 		return IMA_APPRAISE_MODULES;
855 	else if (func == FIRMWARE_CHECK)
856 		return IMA_APPRAISE_FIRMWARE;
857 	else if (func == POLICY_CHECK)
858 		return IMA_APPRAISE_POLICY;
859 	else if (func == KEXEC_KERNEL_CHECK)
860 		return IMA_APPRAISE_KEXEC;
861 	return 0;
862 }
863 
864 static void add_rules(struct ima_rule_entry *entries, int count,
865 		      enum policy_rule_list policy_rule)
866 {
867 	int i = 0;
868 
869 	for (i = 0; i < count; i++) {
870 		struct ima_rule_entry *entry;
871 
872 		if (policy_rule & IMA_DEFAULT_POLICY)
873 			list_add_tail(&entries[i].list, &ima_default_rules);
874 
875 		if (policy_rule & IMA_CUSTOM_POLICY) {
876 			entry = kmemdup(&entries[i], sizeof(*entry),
877 					GFP_KERNEL);
878 			if (!entry)
879 				continue;
880 
881 			list_add_tail(&entry->list, &ima_policy_rules);
882 		}
883 		if (entries[i].action == APPRAISE) {
884 			if (entries != build_appraise_rules)
885 				temp_ima_appraise |=
886 					ima_appraise_flag(entries[i].func);
887 			else
888 				build_ima_appraise |=
889 					ima_appraise_flag(entries[i].func);
890 		}
891 	}
892 }
893 
894 static int ima_parse_rule(char *rule, struct ima_rule_entry *entry);
895 
896 static int __init ima_init_arch_policy(void)
897 {
898 	const char * const *arch_rules;
899 	const char * const *rules;
900 	int arch_entries = 0;
901 	int i = 0;
902 
903 	arch_rules = arch_get_ima_policy();
904 	if (!arch_rules)
905 		return arch_entries;
906 
907 	/* Get number of rules */
908 	for (rules = arch_rules; *rules != NULL; rules++)
909 		arch_entries++;
910 
911 	arch_policy_entry = kcalloc(arch_entries + 1,
912 				    sizeof(*arch_policy_entry), GFP_KERNEL);
913 	if (!arch_policy_entry)
914 		return 0;
915 
916 	/* Convert each policy string rules to struct ima_rule_entry format */
917 	for (rules = arch_rules, i = 0; *rules != NULL; rules++) {
918 		char rule[255];
919 		int result;
920 
921 		result = strscpy(rule, *rules, sizeof(rule));
922 
923 		INIT_LIST_HEAD(&arch_policy_entry[i].list);
924 		result = ima_parse_rule(rule, &arch_policy_entry[i]);
925 		if (result) {
926 			pr_warn("Skipping unknown architecture policy rule: %s\n",
927 				rule);
928 			memset(&arch_policy_entry[i], 0,
929 			       sizeof(*arch_policy_entry));
930 			continue;
931 		}
932 		i++;
933 	}
934 	return i;
935 }
936 
937 /**
938  * ima_init_policy - initialize the default measure rules.
939  *
940  * ima_rules points to either the ima_default_rules or the new ima_policy_rules.
941  */
942 void __init ima_init_policy(void)
943 {
944 	int build_appraise_entries, arch_entries;
945 
946 	/* if !ima_policy, we load NO default rules */
947 	if (ima_policy)
948 		add_rules(dont_measure_rules, ARRAY_SIZE(dont_measure_rules),
949 			  IMA_DEFAULT_POLICY);
950 
951 	switch (ima_policy) {
952 	case ORIGINAL_TCB:
953 		add_rules(original_measurement_rules,
954 			  ARRAY_SIZE(original_measurement_rules),
955 			  IMA_DEFAULT_POLICY);
956 		break;
957 	case DEFAULT_TCB:
958 		add_rules(default_measurement_rules,
959 			  ARRAY_SIZE(default_measurement_rules),
960 			  IMA_DEFAULT_POLICY);
961 		break;
962 	default:
963 		break;
964 	}
965 
966 	/*
967 	 * Based on runtime secure boot flags, insert arch specific measurement
968 	 * and appraise rules requiring file signatures for both the initial
969 	 * and custom policies, prior to other appraise rules.
970 	 * (Highest priority)
971 	 */
972 	arch_entries = ima_init_arch_policy();
973 	if (!arch_entries)
974 		pr_info("No architecture policies found\n");
975 	else
976 		add_rules(arch_policy_entry, arch_entries,
977 			  IMA_DEFAULT_POLICY | IMA_CUSTOM_POLICY);
978 
979 	/*
980 	 * Insert the builtin "secure_boot" policy rules requiring file
981 	 * signatures, prior to other appraise rules.
982 	 */
983 	if (ima_use_secure_boot)
984 		add_rules(secure_boot_rules, ARRAY_SIZE(secure_boot_rules),
985 			  IMA_DEFAULT_POLICY);
986 
987 	/*
988 	 * Insert the build time appraise rules requiring file signatures
989 	 * for both the initial and custom policies, prior to other appraise
990 	 * rules. As the secure boot rules includes all of the build time
991 	 * rules, include either one or the other set of rules, but not both.
992 	 */
993 	build_appraise_entries = ARRAY_SIZE(build_appraise_rules);
994 	if (build_appraise_entries) {
995 		if (ima_use_secure_boot)
996 			add_rules(build_appraise_rules, build_appraise_entries,
997 				  IMA_CUSTOM_POLICY);
998 		else
999 			add_rules(build_appraise_rules, build_appraise_entries,
1000 				  IMA_DEFAULT_POLICY | IMA_CUSTOM_POLICY);
1001 	}
1002 
1003 	if (ima_use_appraise_tcb)
1004 		add_rules(default_appraise_rules,
1005 			  ARRAY_SIZE(default_appraise_rules),
1006 			  IMA_DEFAULT_POLICY);
1007 
1008 	if (ima_use_critical_data)
1009 		add_rules(critical_data_rules,
1010 			  ARRAY_SIZE(critical_data_rules),
1011 			  IMA_DEFAULT_POLICY);
1012 
1013 	atomic_set(&ima_setxattr_allowed_hash_algorithms, 0);
1014 
1015 	ima_update_policy_flags();
1016 }
1017 
1018 /* Make sure we have a valid policy, at least containing some rules. */
1019 int ima_check_policy(void)
1020 {
1021 	if (list_empty(&ima_temp_rules))
1022 		return -EINVAL;
1023 	return 0;
1024 }
1025 
1026 /**
1027  * ima_update_policy - update default_rules with new measure rules
1028  *
1029  * Called on file .release to update the default rules with a complete new
1030  * policy.  What we do here is to splice ima_policy_rules and ima_temp_rules so
1031  * they make a queue.  The policy may be updated multiple times and this is the
1032  * RCU updater.
1033  *
1034  * Policy rules are never deleted so ima_policy_flag gets zeroed only once when
1035  * we switch from the default policy to user defined.
1036  */
1037 void ima_update_policy(void)
1038 {
1039 	struct list_head *policy = &ima_policy_rules;
1040 
1041 	list_splice_tail_init_rcu(&ima_temp_rules, policy, synchronize_rcu);
1042 
1043 	if (ima_rules != (struct list_head __rcu *)policy) {
1044 		ima_policy_flag = 0;
1045 
1046 		rcu_assign_pointer(ima_rules, policy);
1047 		/*
1048 		 * IMA architecture specific policy rules are specified
1049 		 * as strings and converted to an array of ima_entry_rules
1050 		 * on boot.  After loading a custom policy, free the
1051 		 * architecture specific rules stored as an array.
1052 		 */
1053 		kfree(arch_policy_entry);
1054 	}
1055 	ima_update_policy_flags();
1056 
1057 	/* Custom IMA policy has been loaded */
1058 	ima_process_queued_keys();
1059 }
1060 
1061 /* Keep the enumeration in sync with the policy_tokens! */
1062 enum policy_opt {
1063 	Opt_measure, Opt_dont_measure,
1064 	Opt_appraise, Opt_dont_appraise,
1065 	Opt_audit, Opt_hash, Opt_dont_hash,
1066 	Opt_obj_user, Opt_obj_role, Opt_obj_type,
1067 	Opt_subj_user, Opt_subj_role, Opt_subj_type,
1068 	Opt_func, Opt_mask, Opt_fsmagic, Opt_fsname, Opt_fsuuid,
1069 	Opt_uid_eq, Opt_euid_eq, Opt_gid_eq, Opt_egid_eq,
1070 	Opt_fowner_eq, Opt_fgroup_eq,
1071 	Opt_uid_gt, Opt_euid_gt, Opt_gid_gt, Opt_egid_gt,
1072 	Opt_fowner_gt, Opt_fgroup_gt,
1073 	Opt_uid_lt, Opt_euid_lt, Opt_gid_lt, Opt_egid_lt,
1074 	Opt_fowner_lt, Opt_fgroup_lt,
1075 	Opt_digest_type,
1076 	Opt_appraise_type, Opt_appraise_flag, Opt_appraise_algos,
1077 	Opt_permit_directio, Opt_pcr, Opt_template, Opt_keyrings,
1078 	Opt_label, Opt_err
1079 };
1080 
1081 static const match_table_t policy_tokens = {
1082 	{Opt_measure, "measure"},
1083 	{Opt_dont_measure, "dont_measure"},
1084 	{Opt_appraise, "appraise"},
1085 	{Opt_dont_appraise, "dont_appraise"},
1086 	{Opt_audit, "audit"},
1087 	{Opt_hash, "hash"},
1088 	{Opt_dont_hash, "dont_hash"},
1089 	{Opt_obj_user, "obj_user=%s"},
1090 	{Opt_obj_role, "obj_role=%s"},
1091 	{Opt_obj_type, "obj_type=%s"},
1092 	{Opt_subj_user, "subj_user=%s"},
1093 	{Opt_subj_role, "subj_role=%s"},
1094 	{Opt_subj_type, "subj_type=%s"},
1095 	{Opt_func, "func=%s"},
1096 	{Opt_mask, "mask=%s"},
1097 	{Opt_fsmagic, "fsmagic=%s"},
1098 	{Opt_fsname, "fsname=%s"},
1099 	{Opt_fsuuid, "fsuuid=%s"},
1100 	{Opt_uid_eq, "uid=%s"},
1101 	{Opt_euid_eq, "euid=%s"},
1102 	{Opt_gid_eq, "gid=%s"},
1103 	{Opt_egid_eq, "egid=%s"},
1104 	{Opt_fowner_eq, "fowner=%s"},
1105 	{Opt_fgroup_eq, "fgroup=%s"},
1106 	{Opt_uid_gt, "uid>%s"},
1107 	{Opt_euid_gt, "euid>%s"},
1108 	{Opt_gid_gt, "gid>%s"},
1109 	{Opt_egid_gt, "egid>%s"},
1110 	{Opt_fowner_gt, "fowner>%s"},
1111 	{Opt_fgroup_gt, "fgroup>%s"},
1112 	{Opt_uid_lt, "uid<%s"},
1113 	{Opt_euid_lt, "euid<%s"},
1114 	{Opt_gid_lt, "gid<%s"},
1115 	{Opt_egid_lt, "egid<%s"},
1116 	{Opt_fowner_lt, "fowner<%s"},
1117 	{Opt_fgroup_lt, "fgroup<%s"},
1118 	{Opt_digest_type, "digest_type=%s"},
1119 	{Opt_appraise_type, "appraise_type=%s"},
1120 	{Opt_appraise_flag, "appraise_flag=%s"},
1121 	{Opt_appraise_algos, "appraise_algos=%s"},
1122 	{Opt_permit_directio, "permit_directio"},
1123 	{Opt_pcr, "pcr=%s"},
1124 	{Opt_template, "template=%s"},
1125 	{Opt_keyrings, "keyrings=%s"},
1126 	{Opt_label, "label=%s"},
1127 	{Opt_err, NULL}
1128 };
1129 
1130 static int ima_lsm_rule_init(struct ima_rule_entry *entry,
1131 			     substring_t *args, int lsm_rule, int audit_type)
1132 {
1133 	int result;
1134 
1135 	if (entry->lsm[lsm_rule].rule)
1136 		return -EINVAL;
1137 
1138 	entry->lsm[lsm_rule].args_p = match_strdup(args);
1139 	if (!entry->lsm[lsm_rule].args_p)
1140 		return -ENOMEM;
1141 
1142 	entry->lsm[lsm_rule].type = audit_type;
1143 	result = ima_filter_rule_init(entry->lsm[lsm_rule].type, Audit_equal,
1144 				      entry->lsm[lsm_rule].args_p,
1145 				      &entry->lsm[lsm_rule].rule,
1146 				      GFP_KERNEL);
1147 	if (!entry->lsm[lsm_rule].rule) {
1148 		pr_warn("rule for LSM \'%s\' is undefined\n",
1149 			entry->lsm[lsm_rule].args_p);
1150 
1151 		if (ima_rules == (struct list_head __rcu *)(&ima_default_rules)) {
1152 			kfree(entry->lsm[lsm_rule].args_p);
1153 			entry->lsm[lsm_rule].args_p = NULL;
1154 			result = -EINVAL;
1155 		} else
1156 			result = 0;
1157 	}
1158 
1159 	return result;
1160 }
1161 
1162 static void ima_log_string_op(struct audit_buffer *ab, char *key, char *value,
1163 			      enum policy_opt rule_operator)
1164 {
1165 	if (!ab)
1166 		return;
1167 
1168 	switch (rule_operator) {
1169 	case Opt_uid_gt:
1170 	case Opt_euid_gt:
1171 	case Opt_gid_gt:
1172 	case Opt_egid_gt:
1173 	case Opt_fowner_gt:
1174 	case Opt_fgroup_gt:
1175 		audit_log_format(ab, "%s>", key);
1176 		break;
1177 	case Opt_uid_lt:
1178 	case Opt_euid_lt:
1179 	case Opt_gid_lt:
1180 	case Opt_egid_lt:
1181 	case Opt_fowner_lt:
1182 	case Opt_fgroup_lt:
1183 		audit_log_format(ab, "%s<", key);
1184 		break;
1185 	default:
1186 		audit_log_format(ab, "%s=", key);
1187 	}
1188 	audit_log_format(ab, "%s ", value);
1189 }
1190 static void ima_log_string(struct audit_buffer *ab, char *key, char *value)
1191 {
1192 	ima_log_string_op(ab, key, value, Opt_err);
1193 }
1194 
1195 /*
1196  * Validating the appended signature included in the measurement list requires
1197  * the file hash calculated without the appended signature (i.e., the 'd-modsig'
1198  * field). Therefore, notify the user if they have the 'modsig' field but not
1199  * the 'd-modsig' field in the template.
1200  */
1201 static void check_template_modsig(const struct ima_template_desc *template)
1202 {
1203 #define MSG "template with 'modsig' field also needs 'd-modsig' field\n"
1204 	bool has_modsig, has_dmodsig;
1205 	static bool checked;
1206 	int i;
1207 
1208 	/* We only need to notify the user once. */
1209 	if (checked)
1210 		return;
1211 
1212 	has_modsig = has_dmodsig = false;
1213 	for (i = 0; i < template->num_fields; i++) {
1214 		if (!strcmp(template->fields[i]->field_id, "modsig"))
1215 			has_modsig = true;
1216 		else if (!strcmp(template->fields[i]->field_id, "d-modsig"))
1217 			has_dmodsig = true;
1218 	}
1219 
1220 	if (has_modsig && !has_dmodsig)
1221 		pr_notice(MSG);
1222 
1223 	checked = true;
1224 #undef MSG
1225 }
1226 
1227 /*
1228  * Warn if the template does not contain the given field.
1229  */
1230 static void check_template_field(const struct ima_template_desc *template,
1231 				 const char *field, const char *msg)
1232 {
1233 	int i;
1234 
1235 	for (i = 0; i < template->num_fields; i++)
1236 		if (!strcmp(template->fields[i]->field_id, field))
1237 			return;
1238 
1239 	pr_notice_once("%s", msg);
1240 }
1241 
1242 static bool ima_validate_rule(struct ima_rule_entry *entry)
1243 {
1244 	/* Ensure that the action is set and is compatible with the flags */
1245 	if (entry->action == UNKNOWN)
1246 		return false;
1247 
1248 	if (entry->action != MEASURE && entry->flags & IMA_PCR)
1249 		return false;
1250 
1251 	if (entry->action != APPRAISE &&
1252 	    entry->flags & (IMA_DIGSIG_REQUIRED | IMA_MODSIG_ALLOWED |
1253 			    IMA_CHECK_BLACKLIST | IMA_VALIDATE_ALGOS))
1254 		return false;
1255 
1256 	/*
1257 	 * The IMA_FUNC bit must be set if and only if there's a valid hook
1258 	 * function specified, and vice versa. Enforcing this property allows
1259 	 * for the NONE case below to validate a rule without an explicit hook
1260 	 * function.
1261 	 */
1262 	if (((entry->flags & IMA_FUNC) && entry->func == NONE) ||
1263 	    (!(entry->flags & IMA_FUNC) && entry->func != NONE))
1264 		return false;
1265 
1266 	/*
1267 	 * Ensure that the hook function is compatible with the other
1268 	 * components of the rule
1269 	 */
1270 	switch (entry->func) {
1271 	case NONE:
1272 	case FILE_CHECK:
1273 	case MMAP_CHECK:
1274 	case MMAP_CHECK_REQPROT:
1275 	case BPRM_CHECK:
1276 	case CREDS_CHECK:
1277 	case POST_SETATTR:
1278 	case FIRMWARE_CHECK:
1279 	case POLICY_CHECK:
1280 		if (entry->flags & ~(IMA_FUNC | IMA_MASK | IMA_FSMAGIC |
1281 				     IMA_UID | IMA_FOWNER | IMA_FSUUID |
1282 				     IMA_INMASK | IMA_EUID | IMA_PCR |
1283 				     IMA_FSNAME | IMA_GID | IMA_EGID |
1284 				     IMA_FGROUP | IMA_DIGSIG_REQUIRED |
1285 				     IMA_PERMIT_DIRECTIO | IMA_VALIDATE_ALGOS |
1286 				     IMA_CHECK_BLACKLIST | IMA_VERITY_REQUIRED))
1287 			return false;
1288 
1289 		break;
1290 	case MODULE_CHECK:
1291 	case KEXEC_KERNEL_CHECK:
1292 	case KEXEC_INITRAMFS_CHECK:
1293 		if (entry->flags & ~(IMA_FUNC | IMA_MASK | IMA_FSMAGIC |
1294 				     IMA_UID | IMA_FOWNER | IMA_FSUUID |
1295 				     IMA_INMASK | IMA_EUID | IMA_PCR |
1296 				     IMA_FSNAME | IMA_GID | IMA_EGID |
1297 				     IMA_FGROUP | IMA_DIGSIG_REQUIRED |
1298 				     IMA_PERMIT_DIRECTIO | IMA_MODSIG_ALLOWED |
1299 				     IMA_CHECK_BLACKLIST | IMA_VALIDATE_ALGOS))
1300 			return false;
1301 
1302 		break;
1303 	case KEXEC_CMDLINE:
1304 		if (entry->action & ~(MEASURE | DONT_MEASURE))
1305 			return false;
1306 
1307 		if (entry->flags & ~(IMA_FUNC | IMA_FSMAGIC | IMA_UID |
1308 				     IMA_FOWNER | IMA_FSUUID | IMA_EUID |
1309 				     IMA_PCR | IMA_FSNAME | IMA_GID | IMA_EGID |
1310 				     IMA_FGROUP))
1311 			return false;
1312 
1313 		break;
1314 	case KEY_CHECK:
1315 		if (entry->action & ~(MEASURE | DONT_MEASURE))
1316 			return false;
1317 
1318 		if (entry->flags & ~(IMA_FUNC | IMA_UID | IMA_GID | IMA_PCR |
1319 				     IMA_KEYRINGS))
1320 			return false;
1321 
1322 		if (ima_rule_contains_lsm_cond(entry))
1323 			return false;
1324 
1325 		break;
1326 	case CRITICAL_DATA:
1327 		if (entry->action & ~(MEASURE | DONT_MEASURE))
1328 			return false;
1329 
1330 		if (entry->flags & ~(IMA_FUNC | IMA_UID | IMA_GID | IMA_PCR |
1331 				     IMA_LABEL))
1332 			return false;
1333 
1334 		if (ima_rule_contains_lsm_cond(entry))
1335 			return false;
1336 
1337 		break;
1338 	case SETXATTR_CHECK:
1339 		/* any action other than APPRAISE is unsupported */
1340 		if (entry->action != APPRAISE)
1341 			return false;
1342 
1343 		/* SETXATTR_CHECK requires an appraise_algos parameter */
1344 		if (!(entry->flags & IMA_VALIDATE_ALGOS))
1345 			return false;
1346 
1347 		/*
1348 		 * full policies are not supported, they would have too
1349 		 * much of a performance impact
1350 		 */
1351 		if (entry->flags & ~(IMA_FUNC | IMA_VALIDATE_ALGOS))
1352 			return false;
1353 
1354 		break;
1355 	default:
1356 		return false;
1357 	}
1358 
1359 	/* Ensure that combinations of flags are compatible with each other */
1360 	if (entry->flags & IMA_CHECK_BLACKLIST &&
1361 	    !(entry->flags & IMA_DIGSIG_REQUIRED))
1362 		return false;
1363 
1364 	/*
1365 	 * Unlike for regular IMA 'appraise' policy rules where security.ima
1366 	 * xattr may contain either a file hash or signature, the security.ima
1367 	 * xattr for fsverity must contain a file signature (sigv3).  Ensure
1368 	 * that 'appraise' rules for fsverity require file signatures by
1369 	 * checking the IMA_DIGSIG_REQUIRED flag is set.
1370 	 */
1371 	if (entry->action == APPRAISE &&
1372 	    (entry->flags & IMA_VERITY_REQUIRED) &&
1373 	    !(entry->flags & IMA_DIGSIG_REQUIRED))
1374 		return false;
1375 
1376 	return true;
1377 }
1378 
1379 static unsigned int ima_parse_appraise_algos(char *arg)
1380 {
1381 	unsigned int res = 0;
1382 	int idx;
1383 	char *token;
1384 
1385 	while ((token = strsep(&arg, ",")) != NULL) {
1386 		idx = match_string(hash_algo_name, HASH_ALGO__LAST, token);
1387 
1388 		if (idx < 0) {
1389 			pr_err("unknown hash algorithm \"%s\"",
1390 			       token);
1391 			return 0;
1392 		}
1393 
1394 		if (!crypto_has_alg(hash_algo_name[idx], 0, 0)) {
1395 			pr_err("unavailable hash algorithm \"%s\", check your kernel configuration",
1396 			       token);
1397 			return 0;
1398 		}
1399 
1400 		/* Add the hash algorithm to the 'allowed' bitfield */
1401 		res |= (1U << idx);
1402 	}
1403 
1404 	return res;
1405 }
1406 
1407 static int ima_parse_rule(char *rule, struct ima_rule_entry *entry)
1408 {
1409 	struct audit_buffer *ab;
1410 	char *from;
1411 	char *p;
1412 	bool eid_token; /* either euid or egid */
1413 	struct ima_template_desc *template_desc;
1414 	int result = 0;
1415 
1416 	ab = integrity_audit_log_start(audit_context(), GFP_KERNEL,
1417 				       AUDIT_INTEGRITY_POLICY_RULE);
1418 
1419 	entry->uid = INVALID_UID;
1420 	entry->gid = INVALID_GID;
1421 	entry->fowner = INVALID_UID;
1422 	entry->fgroup = INVALID_GID;
1423 	entry->uid_op = &uid_eq;
1424 	entry->gid_op = &gid_eq;
1425 	entry->fowner_op = &vfsuid_eq_kuid;
1426 	entry->fgroup_op = &vfsgid_eq_kgid;
1427 	entry->action = UNKNOWN;
1428 	while ((p = strsep(&rule, " \t")) != NULL) {
1429 		substring_t args[MAX_OPT_ARGS];
1430 		int token;
1431 		unsigned long lnum;
1432 
1433 		if (result < 0)
1434 			break;
1435 		if ((*p == '\0') || (*p == ' ') || (*p == '\t'))
1436 			continue;
1437 		token = match_token(p, policy_tokens, args);
1438 		switch (token) {
1439 		case Opt_measure:
1440 			ima_log_string(ab, "action", "measure");
1441 
1442 			if (entry->action != UNKNOWN)
1443 				result = -EINVAL;
1444 
1445 			entry->action = MEASURE;
1446 			break;
1447 		case Opt_dont_measure:
1448 			ima_log_string(ab, "action", "dont_measure");
1449 
1450 			if (entry->action != UNKNOWN)
1451 				result = -EINVAL;
1452 
1453 			entry->action = DONT_MEASURE;
1454 			break;
1455 		case Opt_appraise:
1456 			ima_log_string(ab, "action", "appraise");
1457 
1458 			if (entry->action != UNKNOWN)
1459 				result = -EINVAL;
1460 
1461 			entry->action = APPRAISE;
1462 			break;
1463 		case Opt_dont_appraise:
1464 			ima_log_string(ab, "action", "dont_appraise");
1465 
1466 			if (entry->action != UNKNOWN)
1467 				result = -EINVAL;
1468 
1469 			entry->action = DONT_APPRAISE;
1470 			break;
1471 		case Opt_audit:
1472 			ima_log_string(ab, "action", "audit");
1473 
1474 			if (entry->action != UNKNOWN)
1475 				result = -EINVAL;
1476 
1477 			entry->action = AUDIT;
1478 			break;
1479 		case Opt_hash:
1480 			ima_log_string(ab, "action", "hash");
1481 
1482 			if (entry->action != UNKNOWN)
1483 				result = -EINVAL;
1484 
1485 			entry->action = HASH;
1486 			break;
1487 		case Opt_dont_hash:
1488 			ima_log_string(ab, "action", "dont_hash");
1489 
1490 			if (entry->action != UNKNOWN)
1491 				result = -EINVAL;
1492 
1493 			entry->action = DONT_HASH;
1494 			break;
1495 		case Opt_func:
1496 			ima_log_string(ab, "func", args[0].from);
1497 
1498 			if (entry->func)
1499 				result = -EINVAL;
1500 
1501 			if (strcmp(args[0].from, "FILE_CHECK") == 0)
1502 				entry->func = FILE_CHECK;
1503 			/* PATH_CHECK is for backwards compat */
1504 			else if (strcmp(args[0].from, "PATH_CHECK") == 0)
1505 				entry->func = FILE_CHECK;
1506 			else if (strcmp(args[0].from, "MODULE_CHECK") == 0)
1507 				entry->func = MODULE_CHECK;
1508 			else if (strcmp(args[0].from, "FIRMWARE_CHECK") == 0)
1509 				entry->func = FIRMWARE_CHECK;
1510 			else if ((strcmp(args[0].from, "FILE_MMAP") == 0)
1511 				|| (strcmp(args[0].from, "MMAP_CHECK") == 0))
1512 				entry->func = MMAP_CHECK;
1513 			else if ((strcmp(args[0].from, "MMAP_CHECK_REQPROT") == 0))
1514 				entry->func = MMAP_CHECK_REQPROT;
1515 			else if (strcmp(args[0].from, "BPRM_CHECK") == 0)
1516 				entry->func = BPRM_CHECK;
1517 			else if (strcmp(args[0].from, "CREDS_CHECK") == 0)
1518 				entry->func = CREDS_CHECK;
1519 			else if (strcmp(args[0].from, "KEXEC_KERNEL_CHECK") ==
1520 				 0)
1521 				entry->func = KEXEC_KERNEL_CHECK;
1522 			else if (strcmp(args[0].from, "KEXEC_INITRAMFS_CHECK")
1523 				 == 0)
1524 				entry->func = KEXEC_INITRAMFS_CHECK;
1525 			else if (strcmp(args[0].from, "POLICY_CHECK") == 0)
1526 				entry->func = POLICY_CHECK;
1527 			else if (strcmp(args[0].from, "KEXEC_CMDLINE") == 0)
1528 				entry->func = KEXEC_CMDLINE;
1529 			else if (IS_ENABLED(CONFIG_IMA_MEASURE_ASYMMETRIC_KEYS) &&
1530 				 strcmp(args[0].from, "KEY_CHECK") == 0)
1531 				entry->func = KEY_CHECK;
1532 			else if (strcmp(args[0].from, "CRITICAL_DATA") == 0)
1533 				entry->func = CRITICAL_DATA;
1534 			else if (strcmp(args[0].from, "SETXATTR_CHECK") == 0)
1535 				entry->func = SETXATTR_CHECK;
1536 			else
1537 				result = -EINVAL;
1538 			if (!result)
1539 				entry->flags |= IMA_FUNC;
1540 			break;
1541 		case Opt_mask:
1542 			ima_log_string(ab, "mask", args[0].from);
1543 
1544 			if (entry->mask)
1545 				result = -EINVAL;
1546 
1547 			from = args[0].from;
1548 			if (*from == '^')
1549 				from++;
1550 
1551 			if ((strcmp(from, "MAY_EXEC")) == 0)
1552 				entry->mask = MAY_EXEC;
1553 			else if (strcmp(from, "MAY_WRITE") == 0)
1554 				entry->mask = MAY_WRITE;
1555 			else if (strcmp(from, "MAY_READ") == 0)
1556 				entry->mask = MAY_READ;
1557 			else if (strcmp(from, "MAY_APPEND") == 0)
1558 				entry->mask = MAY_APPEND;
1559 			else
1560 				result = -EINVAL;
1561 			if (!result)
1562 				entry->flags |= (*args[0].from == '^')
1563 				     ? IMA_INMASK : IMA_MASK;
1564 			break;
1565 		case Opt_fsmagic:
1566 			ima_log_string(ab, "fsmagic", args[0].from);
1567 
1568 			if (entry->fsmagic) {
1569 				result = -EINVAL;
1570 				break;
1571 			}
1572 
1573 			result = kstrtoul(args[0].from, 16, &entry->fsmagic);
1574 			if (!result)
1575 				entry->flags |= IMA_FSMAGIC;
1576 			break;
1577 		case Opt_fsname:
1578 			ima_log_string(ab, "fsname", args[0].from);
1579 
1580 			entry->fsname = kstrdup(args[0].from, GFP_KERNEL);
1581 			if (!entry->fsname) {
1582 				result = -ENOMEM;
1583 				break;
1584 			}
1585 			result = 0;
1586 			entry->flags |= IMA_FSNAME;
1587 			break;
1588 		case Opt_keyrings:
1589 			ima_log_string(ab, "keyrings", args[0].from);
1590 
1591 			if (!IS_ENABLED(CONFIG_IMA_MEASURE_ASYMMETRIC_KEYS) ||
1592 			    entry->keyrings) {
1593 				result = -EINVAL;
1594 				break;
1595 			}
1596 
1597 			entry->keyrings = ima_alloc_rule_opt_list(args);
1598 			if (IS_ERR(entry->keyrings)) {
1599 				result = PTR_ERR(entry->keyrings);
1600 				entry->keyrings = NULL;
1601 				break;
1602 			}
1603 
1604 			entry->flags |= IMA_KEYRINGS;
1605 			break;
1606 		case Opt_label:
1607 			ima_log_string(ab, "label", args[0].from);
1608 
1609 			if (entry->label) {
1610 				result = -EINVAL;
1611 				break;
1612 			}
1613 
1614 			entry->label = ima_alloc_rule_opt_list(args);
1615 			if (IS_ERR(entry->label)) {
1616 				result = PTR_ERR(entry->label);
1617 				entry->label = NULL;
1618 				break;
1619 			}
1620 
1621 			entry->flags |= IMA_LABEL;
1622 			break;
1623 		case Opt_fsuuid:
1624 			ima_log_string(ab, "fsuuid", args[0].from);
1625 
1626 			if (!uuid_is_null(&entry->fsuuid)) {
1627 				result = -EINVAL;
1628 				break;
1629 			}
1630 
1631 			result = uuid_parse(args[0].from, &entry->fsuuid);
1632 			if (!result)
1633 				entry->flags |= IMA_FSUUID;
1634 			break;
1635 		case Opt_uid_gt:
1636 		case Opt_euid_gt:
1637 			entry->uid_op = &uid_gt;
1638 			fallthrough;
1639 		case Opt_uid_lt:
1640 		case Opt_euid_lt:
1641 			if ((token == Opt_uid_lt) || (token == Opt_euid_lt))
1642 				entry->uid_op = &uid_lt;
1643 			fallthrough;
1644 		case Opt_uid_eq:
1645 		case Opt_euid_eq:
1646 			eid_token = (token == Opt_euid_eq) ||
1647 				    (token == Opt_euid_gt) ||
1648 				    (token == Opt_euid_lt);
1649 
1650 			ima_log_string_op(ab, eid_token ? "euid" : "uid",
1651 					  args[0].from, token);
1652 
1653 			if (uid_valid(entry->uid)) {
1654 				result = -EINVAL;
1655 				break;
1656 			}
1657 
1658 			result = kstrtoul(args[0].from, 10, &lnum);
1659 			if (!result) {
1660 				entry->uid = make_kuid(current_user_ns(),
1661 						       (uid_t) lnum);
1662 				if (!uid_valid(entry->uid) ||
1663 				    (uid_t)lnum != lnum)
1664 					result = -EINVAL;
1665 				else
1666 					entry->flags |= eid_token
1667 					    ? IMA_EUID : IMA_UID;
1668 			}
1669 			break;
1670 		case Opt_gid_gt:
1671 		case Opt_egid_gt:
1672 			entry->gid_op = &gid_gt;
1673 			fallthrough;
1674 		case Opt_gid_lt:
1675 		case Opt_egid_lt:
1676 			if ((token == Opt_gid_lt) || (token == Opt_egid_lt))
1677 				entry->gid_op = &gid_lt;
1678 			fallthrough;
1679 		case Opt_gid_eq:
1680 		case Opt_egid_eq:
1681 			eid_token = (token == Opt_egid_eq) ||
1682 				    (token == Opt_egid_gt) ||
1683 				    (token == Opt_egid_lt);
1684 
1685 			ima_log_string_op(ab, eid_token ? "egid" : "gid",
1686 					  args[0].from, token);
1687 
1688 			if (gid_valid(entry->gid)) {
1689 				result = -EINVAL;
1690 				break;
1691 			}
1692 
1693 			result = kstrtoul(args[0].from, 10, &lnum);
1694 			if (!result) {
1695 				entry->gid = make_kgid(current_user_ns(),
1696 						       (gid_t)lnum);
1697 				if (!gid_valid(entry->gid) ||
1698 				    (((gid_t)lnum) != lnum))
1699 					result = -EINVAL;
1700 				else
1701 					entry->flags |= eid_token
1702 					    ? IMA_EGID : IMA_GID;
1703 			}
1704 			break;
1705 		case Opt_fowner_gt:
1706 			entry->fowner_op = &vfsuid_gt_kuid;
1707 			fallthrough;
1708 		case Opt_fowner_lt:
1709 			if (token == Opt_fowner_lt)
1710 				entry->fowner_op = &vfsuid_lt_kuid;
1711 			fallthrough;
1712 		case Opt_fowner_eq:
1713 			ima_log_string_op(ab, "fowner", args[0].from, token);
1714 
1715 			if (uid_valid(entry->fowner)) {
1716 				result = -EINVAL;
1717 				break;
1718 			}
1719 
1720 			result = kstrtoul(args[0].from, 10, &lnum);
1721 			if (!result) {
1722 				entry->fowner = make_kuid(current_user_ns(),
1723 							  (uid_t)lnum);
1724 				if (!uid_valid(entry->fowner) ||
1725 				    (((uid_t)lnum) != lnum))
1726 					result = -EINVAL;
1727 				else
1728 					entry->flags |= IMA_FOWNER;
1729 			}
1730 			break;
1731 		case Opt_fgroup_gt:
1732 			entry->fgroup_op = &vfsgid_gt_kgid;
1733 			fallthrough;
1734 		case Opt_fgroup_lt:
1735 			if (token == Opt_fgroup_lt)
1736 				entry->fgroup_op = &vfsgid_lt_kgid;
1737 			fallthrough;
1738 		case Opt_fgroup_eq:
1739 			ima_log_string_op(ab, "fgroup", args[0].from, token);
1740 
1741 			if (gid_valid(entry->fgroup)) {
1742 				result = -EINVAL;
1743 				break;
1744 			}
1745 
1746 			result = kstrtoul(args[0].from, 10, &lnum);
1747 			if (!result) {
1748 				entry->fgroup = make_kgid(current_user_ns(),
1749 							  (gid_t)lnum);
1750 				if (!gid_valid(entry->fgroup) ||
1751 				    (((gid_t)lnum) != lnum))
1752 					result = -EINVAL;
1753 				else
1754 					entry->flags |= IMA_FGROUP;
1755 			}
1756 			break;
1757 		case Opt_obj_user:
1758 			ima_log_string(ab, "obj_user", args[0].from);
1759 			result = ima_lsm_rule_init(entry, args,
1760 						   LSM_OBJ_USER,
1761 						   AUDIT_OBJ_USER);
1762 			break;
1763 		case Opt_obj_role:
1764 			ima_log_string(ab, "obj_role", args[0].from);
1765 			result = ima_lsm_rule_init(entry, args,
1766 						   LSM_OBJ_ROLE,
1767 						   AUDIT_OBJ_ROLE);
1768 			break;
1769 		case Opt_obj_type:
1770 			ima_log_string(ab, "obj_type", args[0].from);
1771 			result = ima_lsm_rule_init(entry, args,
1772 						   LSM_OBJ_TYPE,
1773 						   AUDIT_OBJ_TYPE);
1774 			break;
1775 		case Opt_subj_user:
1776 			ima_log_string(ab, "subj_user", args[0].from);
1777 			result = ima_lsm_rule_init(entry, args,
1778 						   LSM_SUBJ_USER,
1779 						   AUDIT_SUBJ_USER);
1780 			break;
1781 		case Opt_subj_role:
1782 			ima_log_string(ab, "subj_role", args[0].from);
1783 			result = ima_lsm_rule_init(entry, args,
1784 						   LSM_SUBJ_ROLE,
1785 						   AUDIT_SUBJ_ROLE);
1786 			break;
1787 		case Opt_subj_type:
1788 			ima_log_string(ab, "subj_type", args[0].from);
1789 			result = ima_lsm_rule_init(entry, args,
1790 						   LSM_SUBJ_TYPE,
1791 						   AUDIT_SUBJ_TYPE);
1792 			break;
1793 		case Opt_digest_type:
1794 			ima_log_string(ab, "digest_type", args[0].from);
1795 			if (entry->flags & IMA_DIGSIG_REQUIRED)
1796 				result = -EINVAL;
1797 			else if ((strcmp(args[0].from, "verity")) == 0)
1798 				entry->flags |= IMA_VERITY_REQUIRED;
1799 			else
1800 				result = -EINVAL;
1801 			break;
1802 		case Opt_appraise_type:
1803 			ima_log_string(ab, "appraise_type", args[0].from);
1804 
1805 			if ((strcmp(args[0].from, "imasig")) == 0) {
1806 				if (entry->flags & IMA_VERITY_REQUIRED)
1807 					result = -EINVAL;
1808 				else
1809 					entry->flags |= IMA_DIGSIG_REQUIRED | IMA_CHECK_BLACKLIST;
1810 			} else if (strcmp(args[0].from, "sigv3") == 0) {
1811 				/* Only fsverity supports sigv3 for now */
1812 				if (entry->flags & IMA_VERITY_REQUIRED)
1813 					entry->flags |= IMA_DIGSIG_REQUIRED | IMA_CHECK_BLACKLIST;
1814 				else
1815 					result = -EINVAL;
1816 			} else if (IS_ENABLED(CONFIG_IMA_APPRAISE_MODSIG) &&
1817 				 strcmp(args[0].from, "imasig|modsig") == 0) {
1818 				if (entry->flags & IMA_VERITY_REQUIRED)
1819 					result = -EINVAL;
1820 				else
1821 					entry->flags |= IMA_DIGSIG_REQUIRED |
1822 						IMA_MODSIG_ALLOWED | IMA_CHECK_BLACKLIST;
1823 			} else {
1824 				result = -EINVAL;
1825 			}
1826 			break;
1827 		case Opt_appraise_flag:
1828 			ima_log_string(ab, "appraise_flag", args[0].from);
1829 			break;
1830 		case Opt_appraise_algos:
1831 			ima_log_string(ab, "appraise_algos", args[0].from);
1832 
1833 			if (entry->allowed_algos) {
1834 				result = -EINVAL;
1835 				break;
1836 			}
1837 
1838 			entry->allowed_algos =
1839 				ima_parse_appraise_algos(args[0].from);
1840 			/* invalid or empty list of algorithms */
1841 			if (!entry->allowed_algos) {
1842 				result = -EINVAL;
1843 				break;
1844 			}
1845 
1846 			entry->flags |= IMA_VALIDATE_ALGOS;
1847 
1848 			break;
1849 		case Opt_permit_directio:
1850 			entry->flags |= IMA_PERMIT_DIRECTIO;
1851 			break;
1852 		case Opt_pcr:
1853 			ima_log_string(ab, "pcr", args[0].from);
1854 
1855 			result = kstrtoint(args[0].from, 10, &entry->pcr);
1856 			if (result || INVALID_PCR(entry->pcr))
1857 				result = -EINVAL;
1858 			else
1859 				entry->flags |= IMA_PCR;
1860 
1861 			break;
1862 		case Opt_template:
1863 			ima_log_string(ab, "template", args[0].from);
1864 			if (entry->action != MEASURE) {
1865 				result = -EINVAL;
1866 				break;
1867 			}
1868 			template_desc = lookup_template_desc(args[0].from);
1869 			if (!template_desc || entry->template) {
1870 				result = -EINVAL;
1871 				break;
1872 			}
1873 
1874 			/*
1875 			 * template_desc_init_fields() does nothing if
1876 			 * the template is already initialised, so
1877 			 * it's safe to do this unconditionally
1878 			 */
1879 			template_desc_init_fields(template_desc->fmt,
1880 						 &(template_desc->fields),
1881 						 &(template_desc->num_fields));
1882 			entry->template = template_desc;
1883 			break;
1884 		case Opt_err:
1885 			ima_log_string(ab, "UNKNOWN", p);
1886 			result = -EINVAL;
1887 			break;
1888 		}
1889 	}
1890 	if (!result && !ima_validate_rule(entry))
1891 		result = -EINVAL;
1892 	else if (entry->action == APPRAISE)
1893 		temp_ima_appraise |= ima_appraise_flag(entry->func);
1894 
1895 	if (!result && entry->flags & IMA_MODSIG_ALLOWED) {
1896 		template_desc = entry->template ? entry->template :
1897 						  ima_template_desc_current();
1898 		check_template_modsig(template_desc);
1899 	}
1900 
1901 	/* d-ngv2 template field recommended for unsigned fs-verity digests */
1902 	if (!result && entry->action == MEASURE &&
1903 	    entry->flags & IMA_VERITY_REQUIRED) {
1904 		template_desc = entry->template ? entry->template :
1905 						  ima_template_desc_current();
1906 		check_template_field(template_desc, "d-ngv2",
1907 				     "verity rules should include d-ngv2");
1908 	}
1909 
1910 	audit_log_format(ab, "res=%d", !result);
1911 	audit_log_end(ab);
1912 	return result;
1913 }
1914 
1915 /**
1916  * ima_parse_add_rule - add a rule to ima_policy_rules
1917  * @rule: ima measurement policy rule
1918  *
1919  * Avoid locking by allowing just one writer at a time in ima_write_policy()
1920  * Returns the length of the rule parsed, an error code on failure
1921  */
1922 ssize_t ima_parse_add_rule(char *rule)
1923 {
1924 	static const char op[] = "update_policy";
1925 	char *p;
1926 	struct ima_rule_entry *entry;
1927 	ssize_t result, len;
1928 	int audit_info = 0;
1929 
1930 	p = strsep(&rule, "\n");
1931 	len = strlen(p) + 1;
1932 	p += strspn(p, " \t");
1933 
1934 	if (*p == '#' || *p == '\0')
1935 		return len;
1936 
1937 	entry = kzalloc(sizeof(*entry), GFP_KERNEL);
1938 	if (!entry) {
1939 		integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
1940 				    NULL, op, "-ENOMEM", -ENOMEM, audit_info);
1941 		return -ENOMEM;
1942 	}
1943 
1944 	INIT_LIST_HEAD(&entry->list);
1945 
1946 	result = ima_parse_rule(p, entry);
1947 	if (result) {
1948 		ima_free_rule(entry);
1949 		integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
1950 				    NULL, op, "invalid-policy", result,
1951 				    audit_info);
1952 		return result;
1953 	}
1954 
1955 	list_add_tail(&entry->list, &ima_temp_rules);
1956 
1957 	return len;
1958 }
1959 
1960 /**
1961  * ima_delete_rules() - called to cleanup invalid in-flight policy.
1962  *
1963  * We don't need locking as we operate on the temp list, which is
1964  * different from the active one.  There is also only one user of
1965  * ima_delete_rules() at a time.
1966  */
1967 void ima_delete_rules(void)
1968 {
1969 	struct ima_rule_entry *entry, *tmp;
1970 
1971 	temp_ima_appraise = 0;
1972 	list_for_each_entry_safe(entry, tmp, &ima_temp_rules, list) {
1973 		list_del(&entry->list);
1974 		ima_free_rule(entry);
1975 	}
1976 }
1977 
1978 #define __ima_hook_stringify(func, str)	(#func),
1979 
1980 const char *const func_tokens[] = {
1981 	__ima_hooks(__ima_hook_stringify)
1982 };
1983 
1984 #ifdef	CONFIG_IMA_READ_POLICY
1985 enum {
1986 	mask_exec = 0, mask_write, mask_read, mask_append
1987 };
1988 
1989 static const char *const mask_tokens[] = {
1990 	"^MAY_EXEC",
1991 	"^MAY_WRITE",
1992 	"^MAY_READ",
1993 	"^MAY_APPEND"
1994 };
1995 
1996 void *ima_policy_start(struct seq_file *m, loff_t *pos)
1997 {
1998 	loff_t l = *pos;
1999 	struct ima_rule_entry *entry;
2000 	struct list_head *ima_rules_tmp;
2001 
2002 	rcu_read_lock();
2003 	ima_rules_tmp = rcu_dereference(ima_rules);
2004 	list_for_each_entry_rcu(entry, ima_rules_tmp, list) {
2005 		if (!l--) {
2006 			rcu_read_unlock();
2007 			return entry;
2008 		}
2009 	}
2010 	rcu_read_unlock();
2011 	return NULL;
2012 }
2013 
2014 void *ima_policy_next(struct seq_file *m, void *v, loff_t *pos)
2015 {
2016 	struct ima_rule_entry *entry = v;
2017 
2018 	rcu_read_lock();
2019 	entry = list_entry_rcu(entry->list.next, struct ima_rule_entry, list);
2020 	rcu_read_unlock();
2021 	(*pos)++;
2022 
2023 	return (&entry->list == &ima_default_rules ||
2024 		&entry->list == &ima_policy_rules) ? NULL : entry;
2025 }
2026 
2027 void ima_policy_stop(struct seq_file *m, void *v)
2028 {
2029 }
2030 
2031 #define pt(token)	policy_tokens[token].pattern
2032 #define mt(token)	mask_tokens[token]
2033 
2034 /*
2035  * policy_func_show - display the ima_hooks policy rule
2036  */
2037 static void policy_func_show(struct seq_file *m, enum ima_hooks func)
2038 {
2039 	if (func > 0 && func < MAX_CHECK)
2040 		seq_printf(m, "func=%s ", func_tokens[func]);
2041 	else
2042 		seq_printf(m, "func=%d ", func);
2043 }
2044 
2045 static void ima_show_rule_opt_list(struct seq_file *m,
2046 				   const struct ima_rule_opt_list *opt_list)
2047 {
2048 	size_t i;
2049 
2050 	for (i = 0; i < opt_list->count; i++)
2051 		seq_printf(m, "%s%s", i ? "|" : "", opt_list->items[i]);
2052 }
2053 
2054 static void ima_policy_show_appraise_algos(struct seq_file *m,
2055 					   unsigned int allowed_hashes)
2056 {
2057 	int idx, list_size = 0;
2058 
2059 	for (idx = 0; idx < HASH_ALGO__LAST; idx++) {
2060 		if (!(allowed_hashes & (1U << idx)))
2061 			continue;
2062 
2063 		/* only add commas if the list contains multiple entries */
2064 		if (list_size++)
2065 			seq_puts(m, ",");
2066 
2067 		seq_puts(m, hash_algo_name[idx]);
2068 	}
2069 }
2070 
2071 int ima_policy_show(struct seq_file *m, void *v)
2072 {
2073 	struct ima_rule_entry *entry = v;
2074 	int i;
2075 	char tbuf[64] = {0,};
2076 	int offset = 0;
2077 
2078 	rcu_read_lock();
2079 
2080 	/* Do not print rules with inactive LSM labels */
2081 	for (i = 0; i < MAX_LSM_RULES; i++) {
2082 		if (entry->lsm[i].args_p && !entry->lsm[i].rule) {
2083 			rcu_read_unlock();
2084 			return 0;
2085 		}
2086 	}
2087 
2088 	if (entry->action & MEASURE)
2089 		seq_puts(m, pt(Opt_measure));
2090 	if (entry->action & DONT_MEASURE)
2091 		seq_puts(m, pt(Opt_dont_measure));
2092 	if (entry->action & APPRAISE)
2093 		seq_puts(m, pt(Opt_appraise));
2094 	if (entry->action & DONT_APPRAISE)
2095 		seq_puts(m, pt(Opt_dont_appraise));
2096 	if (entry->action & AUDIT)
2097 		seq_puts(m, pt(Opt_audit));
2098 	if (entry->action & HASH)
2099 		seq_puts(m, pt(Opt_hash));
2100 	if (entry->action & DONT_HASH)
2101 		seq_puts(m, pt(Opt_dont_hash));
2102 
2103 	seq_puts(m, " ");
2104 
2105 	if (entry->flags & IMA_FUNC)
2106 		policy_func_show(m, entry->func);
2107 
2108 	if ((entry->flags & IMA_MASK) || (entry->flags & IMA_INMASK)) {
2109 		if (entry->flags & IMA_MASK)
2110 			offset = 1;
2111 		if (entry->mask & MAY_EXEC)
2112 			seq_printf(m, pt(Opt_mask), mt(mask_exec) + offset);
2113 		if (entry->mask & MAY_WRITE)
2114 			seq_printf(m, pt(Opt_mask), mt(mask_write) + offset);
2115 		if (entry->mask & MAY_READ)
2116 			seq_printf(m, pt(Opt_mask), mt(mask_read) + offset);
2117 		if (entry->mask & MAY_APPEND)
2118 			seq_printf(m, pt(Opt_mask), mt(mask_append) + offset);
2119 		seq_puts(m, " ");
2120 	}
2121 
2122 	if (entry->flags & IMA_FSMAGIC) {
2123 		snprintf(tbuf, sizeof(tbuf), "0x%lx", entry->fsmagic);
2124 		seq_printf(m, pt(Opt_fsmagic), tbuf);
2125 		seq_puts(m, " ");
2126 	}
2127 
2128 	if (entry->flags & IMA_FSNAME) {
2129 		snprintf(tbuf, sizeof(tbuf), "%s", entry->fsname);
2130 		seq_printf(m, pt(Opt_fsname), tbuf);
2131 		seq_puts(m, " ");
2132 	}
2133 
2134 	if (entry->flags & IMA_KEYRINGS) {
2135 		seq_puts(m, "keyrings=");
2136 		ima_show_rule_opt_list(m, entry->keyrings);
2137 		seq_puts(m, " ");
2138 	}
2139 
2140 	if (entry->flags & IMA_LABEL) {
2141 		seq_puts(m, "label=");
2142 		ima_show_rule_opt_list(m, entry->label);
2143 		seq_puts(m, " ");
2144 	}
2145 
2146 	if (entry->flags & IMA_PCR) {
2147 		snprintf(tbuf, sizeof(tbuf), "%d", entry->pcr);
2148 		seq_printf(m, pt(Opt_pcr), tbuf);
2149 		seq_puts(m, " ");
2150 	}
2151 
2152 	if (entry->flags & IMA_FSUUID) {
2153 		seq_printf(m, "fsuuid=%pU", &entry->fsuuid);
2154 		seq_puts(m, " ");
2155 	}
2156 
2157 	if (entry->flags & IMA_UID) {
2158 		snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->uid));
2159 		if (entry->uid_op == &uid_gt)
2160 			seq_printf(m, pt(Opt_uid_gt), tbuf);
2161 		else if (entry->uid_op == &uid_lt)
2162 			seq_printf(m, pt(Opt_uid_lt), tbuf);
2163 		else
2164 			seq_printf(m, pt(Opt_uid_eq), tbuf);
2165 		seq_puts(m, " ");
2166 	}
2167 
2168 	if (entry->flags & IMA_EUID) {
2169 		snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->uid));
2170 		if (entry->uid_op == &uid_gt)
2171 			seq_printf(m, pt(Opt_euid_gt), tbuf);
2172 		else if (entry->uid_op == &uid_lt)
2173 			seq_printf(m, pt(Opt_euid_lt), tbuf);
2174 		else
2175 			seq_printf(m, pt(Opt_euid_eq), tbuf);
2176 		seq_puts(m, " ");
2177 	}
2178 
2179 	if (entry->flags & IMA_GID) {
2180 		snprintf(tbuf, sizeof(tbuf), "%d", __kgid_val(entry->gid));
2181 		if (entry->gid_op == &gid_gt)
2182 			seq_printf(m, pt(Opt_gid_gt), tbuf);
2183 		else if (entry->gid_op == &gid_lt)
2184 			seq_printf(m, pt(Opt_gid_lt), tbuf);
2185 		else
2186 			seq_printf(m, pt(Opt_gid_eq), tbuf);
2187 		seq_puts(m, " ");
2188 	}
2189 
2190 	if (entry->flags & IMA_EGID) {
2191 		snprintf(tbuf, sizeof(tbuf), "%d", __kgid_val(entry->gid));
2192 		if (entry->gid_op == &gid_gt)
2193 			seq_printf(m, pt(Opt_egid_gt), tbuf);
2194 		else if (entry->gid_op == &gid_lt)
2195 			seq_printf(m, pt(Opt_egid_lt), tbuf);
2196 		else
2197 			seq_printf(m, pt(Opt_egid_eq), tbuf);
2198 		seq_puts(m, " ");
2199 	}
2200 
2201 	if (entry->flags & IMA_FOWNER) {
2202 		snprintf(tbuf, sizeof(tbuf), "%d", __kuid_val(entry->fowner));
2203 		if (entry->fowner_op == &vfsuid_gt_kuid)
2204 			seq_printf(m, pt(Opt_fowner_gt), tbuf);
2205 		else if (entry->fowner_op == &vfsuid_lt_kuid)
2206 			seq_printf(m, pt(Opt_fowner_lt), tbuf);
2207 		else
2208 			seq_printf(m, pt(Opt_fowner_eq), tbuf);
2209 		seq_puts(m, " ");
2210 	}
2211 
2212 	if (entry->flags & IMA_FGROUP) {
2213 		snprintf(tbuf, sizeof(tbuf), "%d", __kgid_val(entry->fgroup));
2214 		if (entry->fgroup_op == &vfsgid_gt_kgid)
2215 			seq_printf(m, pt(Opt_fgroup_gt), tbuf);
2216 		else if (entry->fgroup_op == &vfsgid_lt_kgid)
2217 			seq_printf(m, pt(Opt_fgroup_lt), tbuf);
2218 		else
2219 			seq_printf(m, pt(Opt_fgroup_eq), tbuf);
2220 		seq_puts(m, " ");
2221 	}
2222 
2223 	if (entry->flags & IMA_VALIDATE_ALGOS) {
2224 		seq_puts(m, "appraise_algos=");
2225 		ima_policy_show_appraise_algos(m, entry->allowed_algos);
2226 		seq_puts(m, " ");
2227 	}
2228 
2229 	for (i = 0; i < MAX_LSM_RULES; i++) {
2230 		if (entry->lsm[i].rule) {
2231 			switch (i) {
2232 			case LSM_OBJ_USER:
2233 				seq_printf(m, pt(Opt_obj_user),
2234 					   entry->lsm[i].args_p);
2235 				break;
2236 			case LSM_OBJ_ROLE:
2237 				seq_printf(m, pt(Opt_obj_role),
2238 					   entry->lsm[i].args_p);
2239 				break;
2240 			case LSM_OBJ_TYPE:
2241 				seq_printf(m, pt(Opt_obj_type),
2242 					   entry->lsm[i].args_p);
2243 				break;
2244 			case LSM_SUBJ_USER:
2245 				seq_printf(m, pt(Opt_subj_user),
2246 					   entry->lsm[i].args_p);
2247 				break;
2248 			case LSM_SUBJ_ROLE:
2249 				seq_printf(m, pt(Opt_subj_role),
2250 					   entry->lsm[i].args_p);
2251 				break;
2252 			case LSM_SUBJ_TYPE:
2253 				seq_printf(m, pt(Opt_subj_type),
2254 					   entry->lsm[i].args_p);
2255 				break;
2256 			}
2257 			seq_puts(m, " ");
2258 		}
2259 	}
2260 	if (entry->template)
2261 		seq_printf(m, "template=%s ", entry->template->name);
2262 	if (entry->flags & IMA_DIGSIG_REQUIRED) {
2263 		if (entry->flags & IMA_VERITY_REQUIRED)
2264 			seq_puts(m, "appraise_type=sigv3 ");
2265 		else if (entry->flags & IMA_MODSIG_ALLOWED)
2266 			seq_puts(m, "appraise_type=imasig|modsig ");
2267 		else
2268 			seq_puts(m, "appraise_type=imasig ");
2269 	}
2270 	if (entry->flags & IMA_VERITY_REQUIRED)
2271 		seq_puts(m, "digest_type=verity ");
2272 	if (entry->flags & IMA_PERMIT_DIRECTIO)
2273 		seq_puts(m, "permit_directio ");
2274 	rcu_read_unlock();
2275 	seq_puts(m, "\n");
2276 	return 0;
2277 }
2278 #endif	/* CONFIG_IMA_READ_POLICY */
2279 
2280 #if defined(CONFIG_IMA_APPRAISE) && defined(CONFIG_INTEGRITY_TRUSTED_KEYRING)
2281 /*
2282  * ima_appraise_signature: whether IMA will appraise a given function using
2283  * an IMA digital signature. This is restricted to cases where the kernel
2284  * has a set of built-in trusted keys in order to avoid an attacker simply
2285  * loading additional keys.
2286  */
2287 bool ima_appraise_signature(enum kernel_read_file_id id)
2288 {
2289 	struct ima_rule_entry *entry;
2290 	bool found = false;
2291 	enum ima_hooks func;
2292 	struct list_head *ima_rules_tmp;
2293 
2294 	if (id >= READING_MAX_ID)
2295 		return false;
2296 
2297 	if (id == READING_KEXEC_IMAGE && !(ima_appraise & IMA_APPRAISE_ENFORCE)
2298 	    && security_locked_down(LOCKDOWN_KEXEC))
2299 		return false;
2300 
2301 	func = read_idmap[id] ?: FILE_CHECK;
2302 
2303 	rcu_read_lock();
2304 	ima_rules_tmp = rcu_dereference(ima_rules);
2305 	list_for_each_entry_rcu(entry, ima_rules_tmp, list) {
2306 		if (entry->action != APPRAISE)
2307 			continue;
2308 
2309 		/*
2310 		 * A generic entry will match, but otherwise require that it
2311 		 * match the func we're looking for
2312 		 */
2313 		if (entry->func && entry->func != func)
2314 			continue;
2315 
2316 		/*
2317 		 * We require this to be a digital signature, not a raw IMA
2318 		 * hash.
2319 		 */
2320 		if (entry->flags & IMA_DIGSIG_REQUIRED)
2321 			found = true;
2322 
2323 		/*
2324 		 * We've found a rule that matches, so break now even if it
2325 		 * didn't require a digital signature - a later rule that does
2326 		 * won't override it, so would be a false positive.
2327 		 */
2328 		break;
2329 	}
2330 
2331 	rcu_read_unlock();
2332 	return found;
2333 }
2334 #endif /* CONFIG_IMA_APPRAISE && CONFIG_INTEGRITY_TRUSTED_KEYRING */
2335