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