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