xref: /linux/security/integrity/evm/evm_main.c (revision 7a5f1cd22d47f8ca4b760b6334378ae42c1bd24b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2005-2010 IBM Corporation
4  *
5  * Author:
6  * Mimi Zohar <zohar@us.ibm.com>
7  * Kylene Hall <kjhall@us.ibm.com>
8  *
9  * File: evm_main.c
10  *	implements evm_inode_setxattr, evm_inode_post_setxattr,
11  *	evm_inode_removexattr, evm_verifyxattr, and evm_inode_set_acl.
12  */
13 
14 #define pr_fmt(fmt) "EVM: "fmt
15 
16 #include <linux/init.h>
17 #include <linux/audit.h>
18 #include <linux/xattr.h>
19 #include <linux/integrity.h>
20 #include <linux/evm.h>
21 #include <linux/magic.h>
22 #include <linux/posix_acl_xattr.h>
23 #include <linux/lsm_hooks.h>
24 
25 #include <crypto/hash.h>
26 #include <crypto/hash_info.h>
27 #include <crypto/utils.h>
28 #include "evm.h"
29 
30 int evm_initialized;
31 
32 static const char * const integrity_status_msg[] = {
33 	"pass", "pass_immutable", "fail", "fail_immutable", "no_label",
34 	"no_xattrs", "unknown"
35 };
36 int evm_hmac_attrs;
37 
38 static struct xattr_list evm_config_default_xattrnames[] = {
39 	{
40 	 .name = XATTR_NAME_SELINUX,
41 	 .enabled = IS_ENABLED(CONFIG_SECURITY_SELINUX)
42 	},
43 	{
44 	 .name = XATTR_NAME_SMACK,
45 	 .enabled = IS_ENABLED(CONFIG_SECURITY_SMACK)
46 	},
47 	{
48 	 .name = XATTR_NAME_SMACKEXEC,
49 	 .enabled = IS_ENABLED(CONFIG_EVM_EXTRA_SMACK_XATTRS)
50 	},
51 	{
52 	 .name = XATTR_NAME_SMACKTRANSMUTE,
53 	 .enabled = IS_ENABLED(CONFIG_EVM_EXTRA_SMACK_XATTRS)
54 	},
55 	{
56 	 .name = XATTR_NAME_SMACKMMAP,
57 	 .enabled = IS_ENABLED(CONFIG_EVM_EXTRA_SMACK_XATTRS)
58 	},
59 	{
60 	 .name = XATTR_NAME_APPARMOR,
61 	 .enabled = IS_ENABLED(CONFIG_SECURITY_APPARMOR)
62 	},
63 	{
64 	 .name = XATTR_NAME_IMA,
65 	 .enabled = IS_ENABLED(CONFIG_IMA_APPRAISE)
66 	},
67 	{
68 	 .name = XATTR_NAME_CAPS,
69 	 .enabled = true
70 	},
71 };
72 
73 LIST_HEAD(evm_config_xattrnames);
74 
75 static char *evm_cmdline __initdata;
76 core_param(evm, evm_cmdline, charp, 0);
77 
78 static int evm_fixmode __ro_after_init;
79 static void __init evm_set_fixmode(void)
80 {
81 	if (!evm_cmdline)
82 		return;
83 
84 	if (strncmp(evm_cmdline, "fix", 3) == 0) {
85 		if (arch_get_secureboot()) {
86 			pr_info("Secure boot enabled: ignoring evm=fix");
87 			return;
88 		}
89 		evm_fixmode = 1;
90 	} else {
91 		pr_err("invalid \"%s\" mode", evm_cmdline);
92 	}
93 }
94 
95 static void __init evm_init_config(void)
96 {
97 	int i, xattrs;
98 
99 	xattrs = ARRAY_SIZE(evm_config_default_xattrnames);
100 
101 	pr_info("Initialising EVM extended attributes:\n");
102 	for (i = 0; i < xattrs; i++) {
103 		pr_info("%s%s\n", evm_config_default_xattrnames[i].name,
104 			!evm_config_default_xattrnames[i].enabled ?
105 			" (disabled)" : "");
106 		list_add_tail(&evm_config_default_xattrnames[i].list,
107 			      &evm_config_xattrnames);
108 	}
109 
110 #ifdef CONFIG_EVM_ATTR_FSUUID
111 	evm_hmac_attrs |= EVM_ATTR_FSUUID;
112 #endif
113 	pr_info("HMAC attrs: 0x%x\n", evm_hmac_attrs);
114 }
115 
116 static bool evm_key_loaded(void)
117 {
118 	return (bool)(evm_initialized & EVM_KEY_MASK);
119 }
120 
121 /*
122  * This function determines whether or not it is safe to ignore verification
123  * errors, based on the ability of EVM to calculate HMACs. If the HMAC key
124  * is not loaded, and it cannot be loaded in the future due to the
125  * EVM_SETUP_COMPLETE initialization flag, allowing an operation despite the
126  * attrs/xattrs being found invalid will not make them valid.
127  */
128 static bool evm_hmac_disabled(void)
129 {
130 	if (evm_initialized & EVM_INIT_HMAC)
131 		return false;
132 
133 	if (!(evm_initialized & EVM_SETUP_COMPLETE))
134 		return false;
135 
136 	return true;
137 }
138 
139 static bool evm_sigv3_required(void)
140 {
141 	if (evm_initialized & EVM_SIGV3_REQUIRED)
142 		return true;
143 
144 	return false;
145 }
146 
147 static int evm_find_protected_xattrs(struct dentry *dentry)
148 {
149 	struct inode *inode = d_backing_inode(dentry);
150 	struct xattr_list *xattr;
151 	int error;
152 	int count = 0;
153 
154 	if (!(inode->i_opflags & IOP_XATTR))
155 		return -EOPNOTSUPP;
156 
157 	list_for_each_entry_lockless(xattr, &evm_config_xattrnames, list) {
158 		error = __vfs_getxattr(dentry, inode, xattr->name, NULL, 0);
159 		if (error < 0) {
160 			if (error == -ENODATA)
161 				continue;
162 			return error;
163 		}
164 		count++;
165 	}
166 
167 	return count;
168 }
169 
170 static int is_unsupported_hmac_fs(struct dentry *dentry)
171 {
172 	struct inode *inode = d_backing_inode(dentry);
173 
174 	if (inode->i_sb->s_iflags & SB_I_EVM_HMAC_UNSUPPORTED) {
175 		pr_info_once("%s not supported\n", inode->i_sb->s_type->name);
176 		return 1;
177 	}
178 	return 0;
179 }
180 
181 /*
182  * evm_verify_hmac - calculate and compare the HMAC with the EVM xattr
183  *
184  * Compute the HMAC on the dentry's protected set of extended attributes
185  * and compare it against the stored security.evm xattr.
186  *
187  * For performance:
188  * - use the previously retrieved xattr value and length to calculate the
189  *   HMAC.)
190  * - cache the verification result in the iint, when available.
191  *
192  * Returns integrity status
193  */
194 static enum integrity_status evm_verify_hmac(struct dentry *dentry,
195 					     const char *xattr_name,
196 					     char *xattr_value,
197 					     size_t xattr_value_len)
198 {
199 	struct evm_ima_xattr_data *xattr_data = NULL;
200 	struct signature_v2_hdr *hdr;
201 	enum integrity_status evm_status = INTEGRITY_PASS;
202 	struct evm_digest digest;
203 	struct inode *inode = d_backing_inode(dentry);
204 	struct evm_iint_cache *iint = evm_iint_inode(inode);
205 	int rc, xattr_len, evm_immutable = 0;
206 
207 	if (iint && (iint->evm_status == INTEGRITY_PASS ||
208 		     iint->evm_status == INTEGRITY_PASS_IMMUTABLE))
209 		return iint->evm_status;
210 
211 	/*
212 	 * On unsupported filesystems without EVM_INIT_X509 enabled, skip
213 	 * signature verification.
214 	 */
215 	if (!(evm_initialized & EVM_INIT_X509) &&
216 	    is_unsupported_hmac_fs(dentry))
217 		return INTEGRITY_UNKNOWN;
218 
219 	/* if status is not PASS, try to check again - against -ENOMEM */
220 
221 	/* first need to know the sig type */
222 	rc = vfs_getxattr_alloc(&nop_mnt_idmap, dentry, XATTR_NAME_EVM,
223 				(char **)&xattr_data, 0, GFP_NOFS);
224 	if (rc <= 0) {
225 		evm_status = INTEGRITY_FAIL;
226 		if (rc == -ENODATA) {
227 			rc = evm_find_protected_xattrs(dentry);
228 			if (rc > 0)
229 				evm_status = INTEGRITY_NOLABEL;
230 			else if (rc == 0)
231 				evm_status = INTEGRITY_NOXATTRS; /* new file */
232 		} else if (rc == -EOPNOTSUPP) {
233 			evm_status = INTEGRITY_UNKNOWN;
234 		}
235 		goto out;
236 	}
237 
238 	xattr_len = rc;
239 
240 	/* check value type */
241 	switch (xattr_data->type) {
242 	case EVM_XATTR_HMAC:
243 		if (xattr_len != sizeof(struct evm_xattr)) {
244 			evm_status = INTEGRITY_FAIL;
245 			goto out;
246 		}
247 
248 		digest.hdr.algo = HASH_ALGO_SHA1;
249 		rc = evm_calc_hmac(dentry, xattr_name, xattr_value,
250 				   xattr_value_len, &digest, iint);
251 		if (rc)
252 			break;
253 		rc = crypto_memneq(xattr_data->data, digest.digest,
254 				   SHA1_DIGEST_SIZE);
255 		if (rc)
256 			rc = -EINVAL;
257 		break;
258 	case EVM_XATTR_PORTABLE_DIGSIG:
259 		evm_immutable = 1;
260 		fallthrough;
261 	case EVM_IMA_XATTR_DIGSIG:
262 		/* accept xattr with non-empty signature field */
263 		if (xattr_len <= sizeof(struct signature_v2_hdr)) {
264 			evm_status = INTEGRITY_FAIL;
265 			goto out;
266 		}
267 
268 		hdr = (struct signature_v2_hdr *)xattr_data;
269 
270 		if (evm_sigv3_required() && hdr->version != 3) {
271 			evm_status = INTEGRITY_FAIL;
272 			goto out;
273 		}
274 
275 		digest.hdr.algo = hdr->hash_algo;
276 		rc = evm_calc_hash(dentry, xattr_name, xattr_value,
277 				   xattr_value_len, xattr_data->type, &digest,
278 				   iint);
279 		if (rc)
280 			break;
281 		rc = integrity_digsig_verify(INTEGRITY_KEYRING_EVM,
282 					(const char *)xattr_data, xattr_len,
283 					digest.digest, digest.hdr.length,
284 					digest.hdr.algo);
285 		if (!rc) {
286 			if (xattr_data->type == EVM_XATTR_PORTABLE_DIGSIG) {
287 				if (iint)
288 					iint->flags |= EVM_IMMUTABLE_DIGSIG;
289 				evm_status = INTEGRITY_PASS_IMMUTABLE;
290 			} else if (!IS_RDONLY(inode) &&
291 				   !(inode->i_sb->s_readonly_remount) &&
292 				   !IS_IMMUTABLE(inode) &&
293 				   !is_unsupported_hmac_fs(dentry)) {
294 				evm_update_evmxattr(dentry, xattr_name,
295 						    xattr_value,
296 						    xattr_value_len);
297 			}
298 		}
299 		break;
300 	default:
301 		rc = -EINVAL;
302 		break;
303 	}
304 
305 	if (rc) {
306 		if (rc == -ENODATA)
307 			evm_status = INTEGRITY_NOXATTRS;
308 		else if (evm_immutable)
309 			evm_status = INTEGRITY_FAIL_IMMUTABLE;
310 		else
311 			evm_status = INTEGRITY_FAIL;
312 	}
313 	pr_debug("digest: (%d) [%*phN]\n", digest.hdr.length, digest.hdr.length,
314 		  digest.digest);
315 out:
316 	if (iint)
317 		iint->evm_status = evm_status;
318 	kfree(xattr_data);
319 	return evm_status;
320 }
321 
322 static int evm_protected_xattr_common(const char *req_xattr_name,
323 				      bool all_xattrs)
324 {
325 	int namelen;
326 	int found = 0;
327 	struct xattr_list *xattr;
328 
329 	namelen = strlen(req_xattr_name);
330 	list_for_each_entry_lockless(xattr, &evm_config_xattrnames, list) {
331 		if (!all_xattrs && !xattr->enabled)
332 			continue;
333 
334 		if ((strlen(xattr->name) == namelen)
335 		    && (strncmp(req_xattr_name, xattr->name, namelen) == 0)) {
336 			found = 1;
337 			break;
338 		}
339 		if (strncmp(req_xattr_name,
340 			    xattr->name + XATTR_SECURITY_PREFIX_LEN,
341 			    strlen(req_xattr_name)) == 0) {
342 			found = 1;
343 			break;
344 		}
345 	}
346 
347 	return found;
348 }
349 
350 int evm_protected_xattr(const char *req_xattr_name)
351 {
352 	return evm_protected_xattr_common(req_xattr_name, false);
353 }
354 
355 int evm_protected_xattr_if_enabled(const char *req_xattr_name)
356 {
357 	return evm_protected_xattr_common(req_xattr_name, true);
358 }
359 
360 /**
361  * evm_read_protected_xattrs - read EVM protected xattr names, lengths, values
362  * @dentry: dentry of the read xattrs
363  * @buffer: buffer xattr names, lengths or values are copied to
364  * @buffer_size: size of buffer
365  * @type: n: names, l: lengths, v: values
366  * @canonical_fmt: data format (true: little endian, false: native format)
367  *
368  * Read protected xattr names (separated by |), lengths (u32) or values for a
369  * given dentry and return the total size of copied data. If buffer is NULL,
370  * just return the total size.
371  *
372  * Returns the total size on success, a negative value on error.
373  */
374 int evm_read_protected_xattrs(struct dentry *dentry, u8 *buffer,
375 			      int buffer_size, char type, bool canonical_fmt)
376 {
377 	struct xattr_list *xattr;
378 	int rc, size, total_size = 0;
379 
380 	list_for_each_entry_lockless(xattr, &evm_config_xattrnames, list) {
381 		rc = __vfs_getxattr(dentry, d_backing_inode(dentry),
382 				    xattr->name, NULL, 0);
383 		if (rc < 0 && rc == -ENODATA)
384 			continue;
385 		else if (rc < 0)
386 			return rc;
387 
388 		switch (type) {
389 		case 'n':
390 			size = strlen(xattr->name) + 1;
391 			if (buffer) {
392 				if (total_size)
393 					*(buffer + total_size - 1) = '|';
394 
395 				memcpy(buffer + total_size, xattr->name, size);
396 			}
397 			break;
398 		case 'l':
399 			size = sizeof(u32);
400 			if (buffer) {
401 				if (canonical_fmt)
402 					rc = (__force int)cpu_to_le32(rc);
403 
404 				*(u32 *)(buffer + total_size) = rc;
405 			}
406 			break;
407 		case 'v':
408 			size = rc;
409 			if (buffer) {
410 				rc = __vfs_getxattr(dentry,
411 					d_backing_inode(dentry), xattr->name,
412 					buffer + total_size,
413 					buffer_size - total_size);
414 				if (rc < 0)
415 					return rc;
416 			}
417 			break;
418 		default:
419 			return -EINVAL;
420 		}
421 
422 		total_size += size;
423 	}
424 
425 	return total_size;
426 }
427 
428 /**
429  * evm_verifyxattr - verify the integrity of the requested xattr
430  * @dentry: object of the verify xattr
431  * @xattr_name: requested xattr
432  * @xattr_value: requested xattr value
433  * @xattr_value_len: requested xattr value length
434  *
435  * Calculate the HMAC for the given dentry and verify it against the stored
436  * security.evm xattr. For performance, use the xattr value and length
437  * previously retrieved to calculate the HMAC.
438  *
439  * Returns the xattr integrity status.
440  *
441  * This function requires the caller to lock the inode's i_mutex before it
442  * is executed.
443  */
444 enum integrity_status evm_verifyxattr(struct dentry *dentry,
445 				      const char *xattr_name,
446 				      void *xattr_value, size_t xattr_value_len)
447 {
448 	if (!evm_key_loaded() || !evm_protected_xattr(xattr_name))
449 		return INTEGRITY_UNKNOWN;
450 
451 	return evm_verify_hmac(dentry, xattr_name, xattr_value,
452 				 xattr_value_len);
453 }
454 EXPORT_SYMBOL_GPL(evm_verifyxattr);
455 
456 /*
457  * evm_verify_current_integrity - verify the dentry's metadata integrity
458  * @dentry: pointer to the affected dentry
459  *
460  * Verify and return the dentry's metadata integrity. The exceptions are
461  * before EVM is initialized or in 'fix' mode.
462  */
463 static enum integrity_status evm_verify_current_integrity(struct dentry *dentry)
464 {
465 	struct inode *inode = d_backing_inode(dentry);
466 
467 	if (!evm_key_loaded() || !S_ISREG(inode->i_mode) || evm_fixmode)
468 		return INTEGRITY_PASS;
469 	return evm_verify_hmac(dentry, NULL, NULL, 0);
470 }
471 
472 /*
473  * evm_xattr_change - check if passed xattr value differs from current value
474  * @idmap: idmap of the mount
475  * @dentry: pointer to the affected dentry
476  * @xattr_name: requested xattr
477  * @xattr_value: requested xattr value
478  * @xattr_value_len: requested xattr value length
479  *
480  * Check if passed xattr value differs from current value.
481  *
482  * Returns 1 if passed xattr value differs from current value, 0 otherwise.
483  */
484 static int evm_xattr_change(struct mnt_idmap *idmap,
485 			    struct dentry *dentry, const char *xattr_name,
486 			    const void *xattr_value, size_t xattr_value_len)
487 {
488 	char *xattr_data = NULL;
489 	int rc = 0;
490 
491 	rc = vfs_getxattr_alloc(&nop_mnt_idmap, dentry, xattr_name, &xattr_data,
492 				0, GFP_NOFS);
493 	if (rc < 0) {
494 		rc = 1;
495 		goto out;
496 	}
497 
498 	if (rc == xattr_value_len)
499 		rc = !!memcmp(xattr_value, xattr_data, rc);
500 	else
501 		rc = 1;
502 
503 out:
504 	kfree(xattr_data);
505 	return rc;
506 }
507 
508 /*
509  * evm_protect_xattr - protect the EVM extended attribute
510  *
511  * Prevent security.evm from being modified or removed without the
512  * necessary permissions or when the existing value is invalid.
513  *
514  * The posix xattr acls are 'system' prefixed, which normally would not
515  * affect security.evm.  An interesting side affect of writing posix xattr
516  * acls is their modifying of the i_mode, which is included in security.evm.
517  * For posix xattr acls only, permit security.evm, even if it currently
518  * doesn't exist, to be updated unless the EVM signature is immutable.
519  */
520 static int evm_protect_xattr(struct mnt_idmap *idmap,
521 			     struct dentry *dentry, const char *xattr_name,
522 			     const void *xattr_value, size_t xattr_value_len)
523 {
524 	enum integrity_status evm_status;
525 
526 	if (strcmp(xattr_name, XATTR_NAME_EVM) == 0) {
527 		if (!capable(CAP_SYS_ADMIN))
528 			return -EPERM;
529 		if (is_unsupported_hmac_fs(dentry))
530 			return -EPERM;
531 	} else if (!evm_protected_xattr(xattr_name)) {
532 		if (!posix_xattr_acl(xattr_name))
533 			return 0;
534 		if (is_unsupported_hmac_fs(dentry))
535 			return 0;
536 
537 		evm_status = evm_verify_current_integrity(dentry);
538 		if ((evm_status == INTEGRITY_PASS) ||
539 		    (evm_status == INTEGRITY_NOXATTRS))
540 			return 0;
541 		goto out;
542 	} else if (is_unsupported_hmac_fs(dentry))
543 		return 0;
544 
545 	evm_status = evm_verify_current_integrity(dentry);
546 	if (evm_status == INTEGRITY_NOXATTRS) {
547 		struct evm_iint_cache *iint;
548 
549 		/* Exception if the HMAC is not going to be calculated. */
550 		if (evm_hmac_disabled())
551 			return 0;
552 
553 		iint = evm_iint_inode(d_backing_inode(dentry));
554 		if (iint && (iint->flags & EVM_NEW_FILE))
555 			return 0;
556 
557 		/* exception for pseudo filesystems */
558 		if (dentry->d_sb->s_magic == TMPFS_MAGIC
559 		    || dentry->d_sb->s_magic == SYSFS_MAGIC)
560 			return 0;
561 
562 		integrity_audit_msg(AUDIT_INTEGRITY_METADATA,
563 				    dentry->d_inode, dentry->d_name.name,
564 				    "update_metadata",
565 				    integrity_status_msg[evm_status],
566 				    -EPERM, 0);
567 	}
568 out:
569 	/* Exception if the HMAC is not going to be calculated. */
570 	if (evm_hmac_disabled() && (evm_status == INTEGRITY_NOLABEL ||
571 	    evm_status == INTEGRITY_UNKNOWN))
572 		return 0;
573 
574 	/*
575 	 * Writing other xattrs is safe for portable signatures, as portable
576 	 * signatures are immutable and can never be updated.
577 	 */
578 	if (evm_status == INTEGRITY_FAIL_IMMUTABLE)
579 		return 0;
580 
581 	if (evm_status == INTEGRITY_PASS_IMMUTABLE &&
582 	    !evm_xattr_change(idmap, dentry, xattr_name, xattr_value,
583 			      xattr_value_len))
584 		return 0;
585 
586 	if (evm_status != INTEGRITY_PASS &&
587 	    evm_status != INTEGRITY_PASS_IMMUTABLE)
588 		integrity_audit_msg(AUDIT_INTEGRITY_METADATA, d_backing_inode(dentry),
589 				    dentry->d_name.name, "appraise_metadata",
590 				    integrity_status_msg[evm_status],
591 				    -EPERM, 0);
592 	return evm_status == INTEGRITY_PASS ? 0 : -EPERM;
593 }
594 
595 /**
596  * evm_inode_setxattr - protect the EVM extended attribute
597  * @idmap: idmap of the mount
598  * @dentry: pointer to the affected dentry
599  * @xattr_name: pointer to the affected extended attribute name
600  * @xattr_value: pointer to the new extended attribute value
601  * @xattr_value_len: pointer to the new extended attribute value length
602  * @flags: flags to pass into filesystem operations
603  *
604  * Before allowing the 'security.evm' protected xattr to be updated,
605  * verify the existing value is valid.  As only the kernel should have
606  * access to the EVM encrypted key needed to calculate the HMAC, prevent
607  * userspace from writing HMAC value.  Writing 'security.evm' requires
608  * requires CAP_SYS_ADMIN privileges.
609  */
610 static int evm_inode_setxattr(struct mnt_idmap *idmap, struct dentry *dentry,
611 			      const char *xattr_name, const void *xattr_value,
612 			      size_t xattr_value_len, int flags)
613 {
614 	const struct evm_ima_xattr_data *xattr_data = xattr_value;
615 
616 	/* Policy permits modification of the protected xattrs even though
617 	 * there's no HMAC key loaded
618 	 */
619 	if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
620 		return 0;
621 
622 	if (strcmp(xattr_name, XATTR_NAME_EVM) == 0) {
623 		if (!xattr_value_len)
624 			return -EINVAL;
625 		if (xattr_data->type != EVM_IMA_XATTR_DIGSIG &&
626 		    xattr_data->type != EVM_XATTR_PORTABLE_DIGSIG)
627 			return -EPERM;
628 	}
629 	return evm_protect_xattr(idmap, dentry, xattr_name, xattr_value,
630 				 xattr_value_len);
631 }
632 
633 /**
634  * evm_inode_removexattr - protect the EVM extended attribute
635  * @idmap: idmap of the mount
636  * @dentry: pointer to the affected dentry
637  * @xattr_name: pointer to the affected extended attribute name
638  *
639  * Removing 'security.evm' requires CAP_SYS_ADMIN privileges and that
640  * the current value is valid.
641  */
642 static int evm_inode_removexattr(struct mnt_idmap *idmap, struct dentry *dentry,
643 				 const char *xattr_name)
644 {
645 	/* Policy permits modification of the protected xattrs even though
646 	 * there's no HMAC key loaded
647 	 */
648 	if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
649 		return 0;
650 
651 	return evm_protect_xattr(idmap, dentry, xattr_name, NULL, 0);
652 }
653 
654 #ifdef CONFIG_FS_POSIX_ACL
655 static int evm_inode_set_acl_change(struct mnt_idmap *idmap,
656 				    struct dentry *dentry, const char *name,
657 				    struct posix_acl *kacl)
658 {
659 	int rc;
660 
661 	umode_t mode;
662 	struct inode *inode = d_backing_inode(dentry);
663 
664 	if (!kacl)
665 		return 1;
666 
667 	rc = posix_acl_update_mode(idmap, inode, &mode, &kacl);
668 	if (rc || (inode->i_mode != mode))
669 		return 1;
670 
671 	return 0;
672 }
673 #else
674 static inline int evm_inode_set_acl_change(struct mnt_idmap *idmap,
675 					   struct dentry *dentry,
676 					   const char *name,
677 					   struct posix_acl *kacl)
678 {
679 	return 0;
680 }
681 #endif
682 
683 /**
684  * evm_inode_set_acl - protect the EVM extended attribute from posix acls
685  * @idmap: idmap of the idmapped mount
686  * @dentry: pointer to the affected dentry
687  * @acl_name: name of the posix acl
688  * @kacl: pointer to the posix acls
689  *
690  * Prevent modifying posix acls causing the EVM HMAC to be re-calculated
691  * and 'security.evm' xattr updated, unless the existing 'security.evm' is
692  * valid.
693  *
694  * Return: zero on success, -EPERM on failure.
695  */
696 static int evm_inode_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
697 			     const char *acl_name, struct posix_acl *kacl)
698 {
699 	enum integrity_status evm_status;
700 
701 	/* Policy permits modification of the protected xattrs even though
702 	 * there's no HMAC key loaded
703 	 */
704 	if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
705 		return 0;
706 
707 	evm_status = evm_verify_current_integrity(dentry);
708 	if ((evm_status == INTEGRITY_PASS) ||
709 	    (evm_status == INTEGRITY_NOXATTRS))
710 		return 0;
711 
712 	/* Exception if the HMAC is not going to be calculated. */
713 	if (evm_hmac_disabled() && (evm_status == INTEGRITY_NOLABEL ||
714 	    evm_status == INTEGRITY_UNKNOWN))
715 		return 0;
716 
717 	/*
718 	 * Writing other xattrs is safe for portable signatures, as portable
719 	 * signatures are immutable and can never be updated.
720 	 */
721 	if (evm_status == INTEGRITY_FAIL_IMMUTABLE)
722 		return 0;
723 
724 	if (evm_status == INTEGRITY_PASS_IMMUTABLE &&
725 	    !evm_inode_set_acl_change(idmap, dentry, acl_name, kacl))
726 		return 0;
727 
728 	if (evm_status != INTEGRITY_PASS_IMMUTABLE)
729 		integrity_audit_msg(AUDIT_INTEGRITY_METADATA, d_backing_inode(dentry),
730 				    dentry->d_name.name, "appraise_metadata",
731 				    integrity_status_msg[evm_status],
732 				    -EPERM, 0);
733 	return -EPERM;
734 }
735 
736 /**
737  * evm_inode_remove_acl - Protect the EVM extended attribute from posix acls
738  * @idmap: idmap of the mount
739  * @dentry: pointer to the affected dentry
740  * @acl_name: name of the posix acl
741  *
742  * Prevent removing posix acls causing the EVM HMAC to be re-calculated
743  * and 'security.evm' xattr updated, unless the existing 'security.evm' is
744  * valid.
745  *
746  * Return: zero on success, -EPERM on failure.
747  */
748 static int evm_inode_remove_acl(struct mnt_idmap *idmap, struct dentry *dentry,
749 				const char *acl_name)
750 {
751 	return evm_inode_set_acl(idmap, dentry, acl_name, NULL);
752 }
753 
754 static void evm_reset_status(struct inode *inode)
755 {
756 	struct evm_iint_cache *iint;
757 
758 	iint = evm_iint_inode(inode);
759 	if (iint)
760 		iint->evm_status = INTEGRITY_UNKNOWN;
761 }
762 
763 /**
764  * evm_metadata_changed: Detect changes to the metadata
765  * @inode: a file's inode
766  * @metadata_inode: metadata inode
767  *
768  * On a stacked filesystem detect whether the metadata has changed. If this is
769  * the case reset the evm_status associated with the inode that represents the
770  * file.
771  */
772 bool evm_metadata_changed(struct inode *inode, struct inode *metadata_inode)
773 {
774 	struct evm_iint_cache *iint = evm_iint_inode(inode);
775 	bool ret = false;
776 
777 	if (iint) {
778 		ret = (!IS_I_VERSION(metadata_inode) ||
779 		       integrity_inode_attrs_changed(&iint->metadata_inode,
780 						     metadata_inode));
781 		if (ret)
782 			iint->evm_status = INTEGRITY_UNKNOWN;
783 	}
784 
785 	return ret;
786 }
787 
788 /**
789  * evm_revalidate_status - report whether EVM status re-validation is necessary
790  * @xattr_name: pointer to the affected extended attribute name
791  *
792  * Report whether callers of evm_verifyxattr() should re-validate the
793  * EVM status.
794  *
795  * Return true if re-validation is necessary, false otherwise.
796  */
797 bool evm_revalidate_status(const char *xattr_name)
798 {
799 	if (!evm_key_loaded())
800 		return false;
801 
802 	/* evm_inode_post_setattr() passes NULL */
803 	if (!xattr_name)
804 		return true;
805 
806 	if (!evm_protected_xattr(xattr_name) && !posix_xattr_acl(xattr_name) &&
807 	    strcmp(xattr_name, XATTR_NAME_EVM))
808 		return false;
809 
810 	return true;
811 }
812 
813 /**
814  * evm_fix_hmac - Calculate the HMAC and add it to security.evm for fix mode
815  * @dentry: pointer to the affected dentry which doesn't yet have security.evm
816  *          xattr
817  * @xattr_name: pointer to the affected extended attribute name
818  * @xattr_value: pointer to the new extended attribute value
819  * @xattr_value_len: pointer to the new extended attribute value length
820  *
821  * Expects to be called with i_mutex locked.
822  *
823  * Return: 0 on success, -EPERM/-ENOMEM/-EOPNOTSUPP on failure
824  */
825 int evm_fix_hmac(struct dentry *dentry, const char *xattr_name,
826 		 const char *xattr_value, size_t xattr_value_len)
827 
828 {
829 	if (!evm_fixmode || !evm_revalidate_status((xattr_name)))
830 		return -EPERM;
831 
832 	if (!(evm_initialized & EVM_INIT_HMAC))
833 		return -EPERM;
834 
835 	if (is_unsupported_hmac_fs(dentry))
836 		return -EOPNOTSUPP;
837 
838 	return evm_update_evmxattr(dentry, xattr_name, xattr_value, xattr_value_len);
839 }
840 
841 /**
842  * evm_inode_post_setxattr - update 'security.evm' to reflect the changes
843  * @dentry: pointer to the affected dentry
844  * @xattr_name: pointer to the affected extended attribute name
845  * @xattr_value: pointer to the new extended attribute value
846  * @xattr_value_len: pointer to the new extended attribute value length
847  * @flags: flags to pass into filesystem operations
848  *
849  * Update the HMAC stored in 'security.evm' to reflect the change.
850  *
851  * No need to take the i_mutex lock here, as this function is called from
852  * __vfs_setxattr_noperm().  The caller of which has taken the inode's
853  * i_mutex lock.
854  */
855 static void evm_inode_post_setxattr(struct dentry *dentry,
856 				    const char *xattr_name,
857 				    const void *xattr_value,
858 				    size_t xattr_value_len,
859 				    int flags)
860 {
861 	if (!evm_revalidate_status(xattr_name))
862 		return;
863 
864 	evm_reset_status(dentry->d_inode);
865 
866 	if (!strcmp(xattr_name, XATTR_NAME_EVM))
867 		return;
868 
869 	if (!(evm_initialized & EVM_INIT_HMAC))
870 		return;
871 
872 	if (is_unsupported_hmac_fs(dentry))
873 		return;
874 
875 	evm_update_evmxattr(dentry, xattr_name, xattr_value, xattr_value_len);
876 }
877 
878 /**
879  * evm_inode_post_set_acl - Update the EVM extended attribute from posix acls
880  * @dentry: pointer to the affected dentry
881  * @acl_name: name of the posix acl
882  * @kacl: pointer to the posix acls
883  *
884  * Update the 'security.evm' xattr with the EVM HMAC re-calculated after setting
885  * posix acls.
886  */
887 static void evm_inode_post_set_acl(struct dentry *dentry, const char *acl_name,
888 				   struct posix_acl *kacl)
889 {
890 	return evm_inode_post_setxattr(dentry, acl_name, NULL, 0, 0);
891 }
892 
893 /**
894  * evm_inode_post_removexattr - update 'security.evm' after removing the xattr
895  * @dentry: pointer to the affected dentry
896  * @xattr_name: pointer to the affected extended attribute name
897  *
898  * Update the HMAC stored in 'security.evm' to reflect removal of the xattr.
899  *
900  * No need to take the i_mutex lock here, as this function is called from
901  * vfs_removexattr() which takes the i_mutex.
902  */
903 static void evm_inode_post_removexattr(struct dentry *dentry,
904 				       const char *xattr_name)
905 {
906 	if (!evm_revalidate_status(xattr_name))
907 		return;
908 
909 	evm_reset_status(dentry->d_inode);
910 
911 	if (!strcmp(xattr_name, XATTR_NAME_EVM))
912 		return;
913 
914 	if (!(evm_initialized & EVM_INIT_HMAC))
915 		return;
916 
917 	evm_update_evmxattr(dentry, xattr_name, NULL, 0);
918 }
919 
920 /**
921  * evm_inode_post_remove_acl - Update the EVM extended attribute from posix acls
922  * @idmap: idmap of the mount
923  * @dentry: pointer to the affected dentry
924  * @acl_name: name of the posix acl
925  *
926  * Update the 'security.evm' xattr with the EVM HMAC re-calculated after
927  * removing posix acls.
928  */
929 static inline void evm_inode_post_remove_acl(struct mnt_idmap *idmap,
930 					     struct dentry *dentry,
931 					     const char *acl_name)
932 {
933 	evm_inode_post_removexattr(dentry, acl_name);
934 }
935 
936 static int evm_attr_change(struct mnt_idmap *idmap,
937 			   struct dentry *dentry, struct iattr *attr)
938 {
939 	struct inode *inode = d_backing_inode(dentry);
940 	unsigned int ia_valid = attr->ia_valid;
941 
942 	if (!i_uid_needs_update(idmap, attr, inode) &&
943 	    !i_gid_needs_update(idmap, attr, inode) &&
944 	    (!(ia_valid & ATTR_MODE) || attr->ia_mode == inode->i_mode))
945 		return 0;
946 
947 	return 1;
948 }
949 
950 /**
951  * evm_inode_setattr - prevent updating an invalid EVM extended attribute
952  * @idmap: idmap of the mount
953  * @dentry: pointer to the affected dentry
954  * @attr: iattr structure containing the new file attributes
955  *
956  * Permit update of file attributes when files have a valid EVM signature,
957  * except in the case of them having an immutable portable signature.
958  */
959 static int evm_inode_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
960 			     struct iattr *attr)
961 {
962 	unsigned int ia_valid = attr->ia_valid;
963 	enum integrity_status evm_status;
964 
965 	/* Policy permits modification of the protected attrs even though
966 	 * there's no HMAC key loaded
967 	 */
968 	if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
969 		return 0;
970 
971 	if (is_unsupported_hmac_fs(dentry))
972 		return 0;
973 
974 	if (!(ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID)))
975 		return 0;
976 
977 	evm_status = evm_verify_current_integrity(dentry);
978 	/*
979 	 * Writing attrs is safe for portable signatures, as portable signatures
980 	 * are immutable and can never be updated.
981 	 */
982 	if ((evm_status == INTEGRITY_PASS) ||
983 	    (evm_status == INTEGRITY_NOXATTRS) ||
984 	    (evm_status == INTEGRITY_FAIL_IMMUTABLE) ||
985 	    (evm_hmac_disabled() && (evm_status == INTEGRITY_NOLABEL ||
986 	     evm_status == INTEGRITY_UNKNOWN)))
987 		return 0;
988 
989 	if (evm_status == INTEGRITY_PASS_IMMUTABLE &&
990 	    !evm_attr_change(idmap, dentry, attr))
991 		return 0;
992 
993 	integrity_audit_msg(AUDIT_INTEGRITY_METADATA, d_backing_inode(dentry),
994 			    dentry->d_name.name, "appraise_metadata",
995 			    integrity_status_msg[evm_status], -EPERM, 0);
996 	return -EPERM;
997 }
998 
999 /**
1000  * evm_inode_post_setattr - update 'security.evm' after modifying metadata
1001  * @idmap: idmap of the idmapped mount
1002  * @dentry: pointer to the affected dentry
1003  * @ia_valid: for the UID and GID status
1004  *
1005  * For now, update the HMAC stored in 'security.evm' to reflect UID/GID
1006  * changes.
1007  *
1008  * This function is called from notify_change(), which expects the caller
1009  * to lock the inode's i_mutex.
1010  */
1011 static void evm_inode_post_setattr(struct mnt_idmap *idmap,
1012 				   struct dentry *dentry, int ia_valid)
1013 {
1014 	if (!evm_revalidate_status(NULL))
1015 		return;
1016 
1017 	evm_reset_status(dentry->d_inode);
1018 
1019 	if (!(evm_initialized & EVM_INIT_HMAC))
1020 		return;
1021 
1022 	if (is_unsupported_hmac_fs(dentry))
1023 		return;
1024 
1025 	if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID))
1026 		evm_update_evmxattr(dentry, NULL, NULL, 0);
1027 }
1028 
1029 static int evm_inode_copy_up_xattr(struct dentry *src, const char *name)
1030 {
1031 	struct evm_ima_xattr_data *xattr_data = NULL;
1032 	int rc;
1033 
1034 	if (strcmp(name, XATTR_NAME_EVM) != 0)
1035 		return -EOPNOTSUPP;
1036 
1037 	/* first need to know the sig type */
1038 	rc = vfs_getxattr_alloc(&nop_mnt_idmap, src, XATTR_NAME_EVM,
1039 				(char **)&xattr_data, 0, GFP_NOFS);
1040 	if (rc <= 0)
1041 		return -EPERM;
1042 
1043 	if (rc < offsetof(struct evm_ima_xattr_data, type) +
1044 		 sizeof(xattr_data->type))
1045 		return -EPERM;
1046 
1047 	switch (xattr_data->type) {
1048 	case EVM_XATTR_PORTABLE_DIGSIG:
1049 		rc = 0; /* allow copy-up */
1050 		break;
1051 	case EVM_XATTR_HMAC:
1052 	case EVM_IMA_XATTR_DIGSIG:
1053 	default:
1054 		rc = -ECANCELED; /* discard */
1055 	}
1056 
1057 	kfree(xattr_data);
1058 	return rc;
1059 }
1060 
1061 /*
1062  * evm_inode_init_security - initializes security.evm HMAC value
1063  */
1064 int evm_inode_init_security(struct inode *inode, struct inode *dir,
1065 			    const struct qstr *qstr, struct xattr *xattrs,
1066 			    int *xattr_count)
1067 {
1068 	struct evm_xattr *xattr_data;
1069 	struct xattr *xattr, *evm_xattr;
1070 	bool evm_protected_xattrs = false;
1071 	int rc;
1072 
1073 	if (!(evm_initialized & EVM_INIT_HMAC) || !xattrs)
1074 		return 0;
1075 
1076 	/*
1077 	 * security_inode_init_security() makes sure that the xattrs array is
1078 	 * contiguous, there is enough space for security.evm, and that there is
1079 	 * a terminator at the end of the array.
1080 	 */
1081 	for (xattr = xattrs; xattr->name; xattr++) {
1082 		if (evm_protected_xattr(xattr->name))
1083 			evm_protected_xattrs = true;
1084 	}
1085 
1086 	/* EVM xattr not needed. */
1087 	if (!evm_protected_xattrs)
1088 		return 0;
1089 
1090 	evm_xattr = lsm_get_xattr_slot(xattrs, xattr_count);
1091 	/*
1092 	 * Array terminator (xattr name = NULL) must be the first non-filled
1093 	 * xattr slot.
1094 	 */
1095 	WARN_ONCE(evm_xattr != xattr,
1096 		  "%s: xattrs terminator is not the first non-filled slot\n",
1097 		  __func__);
1098 
1099 	xattr_data = kzalloc_obj(*xattr_data, GFP_NOFS);
1100 	if (!xattr_data)
1101 		return -ENOMEM;
1102 
1103 	xattr_data->data.type = EVM_XATTR_HMAC;
1104 	rc = evm_init_hmac(inode, xattrs, xattr_data->digest);
1105 	if (rc < 0)
1106 		goto out;
1107 
1108 	evm_xattr->value = xattr_data;
1109 	evm_xattr->value_len = sizeof(*xattr_data);
1110 	evm_xattr->name = XATTR_EVM_SUFFIX;
1111 	return 0;
1112 out:
1113 	kfree(xattr_data);
1114 	return rc;
1115 }
1116 EXPORT_SYMBOL_GPL(evm_inode_init_security);
1117 
1118 static int evm_inode_alloc_security(struct inode *inode)
1119 {
1120 	struct evm_iint_cache *iint = evm_iint_inode(inode);
1121 
1122 	/* Called by security_inode_alloc(), it cannot be NULL. */
1123 	iint->flags = 0UL;
1124 	iint->evm_status = INTEGRITY_UNKNOWN;
1125 
1126 	return 0;
1127 }
1128 
1129 static void evm_file_release(struct file *file)
1130 {
1131 	struct inode *inode = file_inode(file);
1132 	struct evm_iint_cache *iint = evm_iint_inode(inode);
1133 	fmode_t mode = file->f_mode;
1134 
1135 	if (!S_ISREG(inode->i_mode) || !(mode & FMODE_WRITE))
1136 		return;
1137 
1138 	if (iint && iint->flags & EVM_NEW_FILE &&
1139 	    atomic_read(&inode->i_writecount) == 1)
1140 		iint->flags &= ~EVM_NEW_FILE;
1141 }
1142 
1143 static void evm_post_path_mknod(struct mnt_idmap *idmap, struct dentry *dentry)
1144 {
1145 	struct inode *inode = d_backing_inode(dentry);
1146 	struct evm_iint_cache *iint = evm_iint_inode(inode);
1147 
1148 	if (!S_ISREG(inode->i_mode))
1149 		return;
1150 
1151 	if (iint)
1152 		iint->flags |= EVM_NEW_FILE;
1153 }
1154 
1155 #ifdef CONFIG_EVM_LOAD_X509
1156 void __init evm_load_x509(void)
1157 {
1158 	int rc;
1159 
1160 	rc = integrity_load_x509(INTEGRITY_KEYRING_EVM, CONFIG_EVM_X509_PATH);
1161 	if (!rc)
1162 		evm_initialized |= EVM_INIT_X509;
1163 }
1164 #endif
1165 
1166 static int __init init_evm(void)
1167 {
1168 	int error;
1169 	struct list_head *pos, *q;
1170 
1171 	evm_init_config();
1172 
1173 	evm_set_fixmode();
1174 
1175 	error = integrity_init_keyring(INTEGRITY_KEYRING_EVM);
1176 	if (error)
1177 		goto error;
1178 
1179 	error = evm_init_secfs();
1180 	if (error < 0) {
1181 		pr_info("Error registering secfs\n");
1182 		goto error;
1183 	}
1184 
1185 error:
1186 	if (error != 0) {
1187 		if (!list_empty(&evm_config_xattrnames)) {
1188 			list_for_each_safe(pos, q, &evm_config_xattrnames)
1189 				list_del(pos);
1190 		}
1191 	}
1192 
1193 	return error;
1194 }
1195 
1196 static struct security_hook_list evm_hooks[] __ro_after_init = {
1197 	LSM_HOOK_INIT(inode_setattr, evm_inode_setattr),
1198 	LSM_HOOK_INIT(inode_post_setattr, evm_inode_post_setattr),
1199 	LSM_HOOK_INIT(inode_copy_up_xattr, evm_inode_copy_up_xattr),
1200 	LSM_HOOK_INIT(inode_setxattr, evm_inode_setxattr),
1201 	LSM_HOOK_INIT(inode_post_setxattr, evm_inode_post_setxattr),
1202 	LSM_HOOK_INIT(inode_set_acl, evm_inode_set_acl),
1203 	LSM_HOOK_INIT(inode_post_set_acl, evm_inode_post_set_acl),
1204 	LSM_HOOK_INIT(inode_remove_acl, evm_inode_remove_acl),
1205 	LSM_HOOK_INIT(inode_post_remove_acl, evm_inode_post_remove_acl),
1206 	LSM_HOOK_INIT(inode_removexattr, evm_inode_removexattr),
1207 	LSM_HOOK_INIT(inode_post_removexattr, evm_inode_post_removexattr),
1208 	LSM_HOOK_INIT(inode_init_security, evm_inode_init_security),
1209 	LSM_HOOK_INIT(inode_alloc_security, evm_inode_alloc_security),
1210 	LSM_HOOK_INIT(file_release, evm_file_release),
1211 	LSM_HOOK_INIT(path_post_mknod, evm_post_path_mknod),
1212 };
1213 
1214 static const struct lsm_id evm_lsmid = {
1215 	.name = "evm",
1216 	.id = LSM_ID_EVM,
1217 };
1218 
1219 static int __init init_evm_lsm(void)
1220 {
1221 	security_add_hooks(evm_hooks, ARRAY_SIZE(evm_hooks), &evm_lsmid);
1222 	return 0;
1223 }
1224 
1225 struct lsm_blob_sizes evm_blob_sizes __ro_after_init = {
1226 	.lbs_inode = sizeof(struct evm_iint_cache),
1227 	.lbs_xattr_count = 1,
1228 };
1229 
1230 DEFINE_LSM(evm) = {
1231 	.id = &evm_lsmid,
1232 	.init = init_evm_lsm,
1233 	.order = LSM_ORDER_LAST,
1234 	.blobs = &evm_blob_sizes,
1235 	.initcall_late = init_evm,
1236 };
1237