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/crypto.h>
18 #include <linux/audit.h>
19 #include <linux/xattr.h>
20 #include <linux/integrity.h>
21 #include <linux/evm.h>
22 #include <linux/magic.h>
23 #include <linux/posix_acl_xattr.h>
24 
25 #include <crypto/hash.h>
26 #include <crypto/hash_info.h>
27 #include <crypto/algapi.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 int evm_fixmode __ro_after_init;
76 static int __init evm_set_fixmode(char *str)
77 {
78 	if (strncmp(str, "fix", 3) == 0)
79 		evm_fixmode = 1;
80 	else
81 		pr_err("invalid \"%s\" mode", str);
82 
83 	return 1;
84 }
85 __setup("evm=", evm_set_fixmode);
86 
87 static void __init evm_init_config(void)
88 {
89 	int i, xattrs;
90 
91 	xattrs = ARRAY_SIZE(evm_config_default_xattrnames);
92 
93 	pr_info("Initialising EVM extended attributes:\n");
94 	for (i = 0; i < xattrs; i++) {
95 		pr_info("%s%s\n", evm_config_default_xattrnames[i].name,
96 			!evm_config_default_xattrnames[i].enabled ?
97 			" (disabled)" : "");
98 		list_add_tail(&evm_config_default_xattrnames[i].list,
99 			      &evm_config_xattrnames);
100 	}
101 
102 #ifdef CONFIG_EVM_ATTR_FSUUID
103 	evm_hmac_attrs |= EVM_ATTR_FSUUID;
104 #endif
105 	pr_info("HMAC attrs: 0x%x\n", evm_hmac_attrs);
106 }
107 
108 static bool evm_key_loaded(void)
109 {
110 	return (bool)(evm_initialized & EVM_KEY_MASK);
111 }
112 
113 /*
114  * This function determines whether or not it is safe to ignore verification
115  * errors, based on the ability of EVM to calculate HMACs. If the HMAC key
116  * is not loaded, and it cannot be loaded in the future due to the
117  * EVM_SETUP_COMPLETE initialization flag, allowing an operation despite the
118  * attrs/xattrs being found invalid will not make them valid.
119  */
120 static bool evm_hmac_disabled(void)
121 {
122 	if (evm_initialized & EVM_INIT_HMAC)
123 		return false;
124 
125 	if (!(evm_initialized & EVM_SETUP_COMPLETE))
126 		return false;
127 
128 	return true;
129 }
130 
131 static int evm_find_protected_xattrs(struct dentry *dentry)
132 {
133 	struct inode *inode = d_backing_inode(dentry);
134 	struct xattr_list *xattr;
135 	int error;
136 	int count = 0;
137 
138 	if (!(inode->i_opflags & IOP_XATTR))
139 		return -EOPNOTSUPP;
140 
141 	list_for_each_entry_lockless(xattr, &evm_config_xattrnames, list) {
142 		error = __vfs_getxattr(dentry, inode, xattr->name, NULL, 0);
143 		if (error < 0) {
144 			if (error == -ENODATA)
145 				continue;
146 			return error;
147 		}
148 		count++;
149 	}
150 
151 	return count;
152 }
153 
154 /*
155  * evm_verify_hmac - calculate and compare the HMAC with the EVM xattr
156  *
157  * Compute the HMAC on the dentry's protected set of extended attributes
158  * and compare it against the stored security.evm xattr.
159  *
160  * For performance:
161  * - use the previoulsy retrieved xattr value and length to calculate the
162  *   HMAC.)
163  * - cache the verification result in the iint, when available.
164  *
165  * Returns integrity status
166  */
167 static enum integrity_status evm_verify_hmac(struct dentry *dentry,
168 					     const char *xattr_name,
169 					     char *xattr_value,
170 					     size_t xattr_value_len,
171 					     struct integrity_iint_cache *iint)
172 {
173 	struct evm_ima_xattr_data *xattr_data = NULL;
174 	struct signature_v2_hdr *hdr;
175 	enum integrity_status evm_status = INTEGRITY_PASS;
176 	struct evm_digest digest;
177 	struct inode *inode;
178 	int rc, xattr_len, evm_immutable = 0;
179 
180 	if (iint && (iint->evm_status == INTEGRITY_PASS ||
181 		     iint->evm_status == INTEGRITY_PASS_IMMUTABLE))
182 		return iint->evm_status;
183 
184 	/* if status is not PASS, try to check again - against -ENOMEM */
185 
186 	/* first need to know the sig type */
187 	rc = vfs_getxattr_alloc(&nop_mnt_idmap, dentry, XATTR_NAME_EVM,
188 				(char **)&xattr_data, 0, GFP_NOFS);
189 	if (rc <= 0) {
190 		evm_status = INTEGRITY_FAIL;
191 		if (rc == -ENODATA) {
192 			rc = evm_find_protected_xattrs(dentry);
193 			if (rc > 0)
194 				evm_status = INTEGRITY_NOLABEL;
195 			else if (rc == 0)
196 				evm_status = INTEGRITY_NOXATTRS; /* new file */
197 		} else if (rc == -EOPNOTSUPP) {
198 			evm_status = INTEGRITY_UNKNOWN;
199 		}
200 		goto out;
201 	}
202 
203 	xattr_len = rc;
204 
205 	/* check value type */
206 	switch (xattr_data->type) {
207 	case EVM_XATTR_HMAC:
208 		if (xattr_len != sizeof(struct evm_xattr)) {
209 			evm_status = INTEGRITY_FAIL;
210 			goto out;
211 		}
212 
213 		digest.hdr.algo = HASH_ALGO_SHA1;
214 		rc = evm_calc_hmac(dentry, xattr_name, xattr_value,
215 				   xattr_value_len, &digest);
216 		if (rc)
217 			break;
218 		rc = crypto_memneq(xattr_data->data, digest.digest,
219 				   SHA1_DIGEST_SIZE);
220 		if (rc)
221 			rc = -EINVAL;
222 		break;
223 	case EVM_XATTR_PORTABLE_DIGSIG:
224 		evm_immutable = 1;
225 		fallthrough;
226 	case EVM_IMA_XATTR_DIGSIG:
227 		/* accept xattr with non-empty signature field */
228 		if (xattr_len <= sizeof(struct signature_v2_hdr)) {
229 			evm_status = INTEGRITY_FAIL;
230 			goto out;
231 		}
232 
233 		hdr = (struct signature_v2_hdr *)xattr_data;
234 		digest.hdr.algo = hdr->hash_algo;
235 		rc = evm_calc_hash(dentry, xattr_name, xattr_value,
236 				   xattr_value_len, xattr_data->type, &digest);
237 		if (rc)
238 			break;
239 		rc = integrity_digsig_verify(INTEGRITY_KEYRING_EVM,
240 					(const char *)xattr_data, xattr_len,
241 					digest.digest, digest.hdr.length);
242 		if (!rc) {
243 			inode = d_backing_inode(dentry);
244 
245 			if (xattr_data->type == EVM_XATTR_PORTABLE_DIGSIG) {
246 				if (iint)
247 					iint->flags |= EVM_IMMUTABLE_DIGSIG;
248 				evm_status = INTEGRITY_PASS_IMMUTABLE;
249 			} else if (!IS_RDONLY(inode) &&
250 				   !(inode->i_sb->s_readonly_remount) &&
251 				   !IS_IMMUTABLE(inode)) {
252 				evm_update_evmxattr(dentry, xattr_name,
253 						    xattr_value,
254 						    xattr_value_len);
255 			}
256 		}
257 		break;
258 	default:
259 		rc = -EINVAL;
260 		break;
261 	}
262 
263 	if (rc) {
264 		if (rc == -ENODATA)
265 			evm_status = INTEGRITY_NOXATTRS;
266 		else if (evm_immutable)
267 			evm_status = INTEGRITY_FAIL_IMMUTABLE;
268 		else
269 			evm_status = INTEGRITY_FAIL;
270 	}
271 	pr_debug("digest: (%d) [%*phN]\n", digest.hdr.length, digest.hdr.length,
272 		  digest.digest);
273 out:
274 	if (iint)
275 		iint->evm_status = evm_status;
276 	kfree(xattr_data);
277 	return evm_status;
278 }
279 
280 static int evm_protected_xattr_common(const char *req_xattr_name,
281 				      bool all_xattrs)
282 {
283 	int namelen;
284 	int found = 0;
285 	struct xattr_list *xattr;
286 
287 	namelen = strlen(req_xattr_name);
288 	list_for_each_entry_lockless(xattr, &evm_config_xattrnames, list) {
289 		if (!all_xattrs && !xattr->enabled)
290 			continue;
291 
292 		if ((strlen(xattr->name) == namelen)
293 		    && (strncmp(req_xattr_name, xattr->name, namelen) == 0)) {
294 			found = 1;
295 			break;
296 		}
297 		if (strncmp(req_xattr_name,
298 			    xattr->name + XATTR_SECURITY_PREFIX_LEN,
299 			    strlen(req_xattr_name)) == 0) {
300 			found = 1;
301 			break;
302 		}
303 	}
304 
305 	return found;
306 }
307 
308 static int evm_protected_xattr(const char *req_xattr_name)
309 {
310 	return evm_protected_xattr_common(req_xattr_name, false);
311 }
312 
313 int evm_protected_xattr_if_enabled(const char *req_xattr_name)
314 {
315 	return evm_protected_xattr_common(req_xattr_name, true);
316 }
317 
318 /**
319  * evm_read_protected_xattrs - read EVM protected xattr names, lengths, values
320  * @dentry: dentry of the read xattrs
321  * @buffer: buffer xattr names, lengths or values are copied to
322  * @buffer_size: size of buffer
323  * @type: n: names, l: lengths, v: values
324  * @canonical_fmt: data format (true: little endian, false: native format)
325  *
326  * Read protected xattr names (separated by |), lengths (u32) or values for a
327  * given dentry and return the total size of copied data. If buffer is NULL,
328  * just return the total size.
329  *
330  * Returns the total size on success, a negative value on error.
331  */
332 int evm_read_protected_xattrs(struct dentry *dentry, u8 *buffer,
333 			      int buffer_size, char type, bool canonical_fmt)
334 {
335 	struct xattr_list *xattr;
336 	int rc, size, total_size = 0;
337 
338 	list_for_each_entry_lockless(xattr, &evm_config_xattrnames, list) {
339 		rc = __vfs_getxattr(dentry, d_backing_inode(dentry),
340 				    xattr->name, NULL, 0);
341 		if (rc < 0 && rc == -ENODATA)
342 			continue;
343 		else if (rc < 0)
344 			return rc;
345 
346 		switch (type) {
347 		case 'n':
348 			size = strlen(xattr->name) + 1;
349 			if (buffer) {
350 				if (total_size)
351 					*(buffer + total_size - 1) = '|';
352 
353 				memcpy(buffer + total_size, xattr->name, size);
354 			}
355 			break;
356 		case 'l':
357 			size = sizeof(u32);
358 			if (buffer) {
359 				if (canonical_fmt)
360 					rc = (__force int)cpu_to_le32(rc);
361 
362 				*(u32 *)(buffer + total_size) = rc;
363 			}
364 			break;
365 		case 'v':
366 			size = rc;
367 			if (buffer) {
368 				rc = __vfs_getxattr(dentry,
369 					d_backing_inode(dentry), xattr->name,
370 					buffer + total_size,
371 					buffer_size - total_size);
372 				if (rc < 0)
373 					return rc;
374 			}
375 			break;
376 		default:
377 			return -EINVAL;
378 		}
379 
380 		total_size += size;
381 	}
382 
383 	return total_size;
384 }
385 
386 /**
387  * evm_verifyxattr - verify the integrity of the requested xattr
388  * @dentry: object of the verify xattr
389  * @xattr_name: requested xattr
390  * @xattr_value: requested xattr value
391  * @xattr_value_len: requested xattr value length
392  * @iint: inode integrity metadata
393  *
394  * Calculate the HMAC for the given dentry and verify it against the stored
395  * security.evm xattr. For performance, use the xattr value and length
396  * previously retrieved to calculate the HMAC.
397  *
398  * Returns the xattr integrity status.
399  *
400  * This function requires the caller to lock the inode's i_mutex before it
401  * is executed.
402  */
403 enum integrity_status evm_verifyxattr(struct dentry *dentry,
404 				      const char *xattr_name,
405 				      void *xattr_value, size_t xattr_value_len,
406 				      struct integrity_iint_cache *iint)
407 {
408 	if (!evm_key_loaded() || !evm_protected_xattr(xattr_name))
409 		return INTEGRITY_UNKNOWN;
410 
411 	if (!iint) {
412 		iint = integrity_iint_find(d_backing_inode(dentry));
413 		if (!iint)
414 			return INTEGRITY_UNKNOWN;
415 	}
416 	return evm_verify_hmac(dentry, xattr_name, xattr_value,
417 				 xattr_value_len, iint);
418 }
419 EXPORT_SYMBOL_GPL(evm_verifyxattr);
420 
421 /*
422  * evm_verify_current_integrity - verify the dentry's metadata integrity
423  * @dentry: pointer to the affected dentry
424  *
425  * Verify and return the dentry's metadata integrity. The exceptions are
426  * before EVM is initialized or in 'fix' mode.
427  */
428 static enum integrity_status evm_verify_current_integrity(struct dentry *dentry)
429 {
430 	struct inode *inode = d_backing_inode(dentry);
431 
432 	if (!evm_key_loaded() || !S_ISREG(inode->i_mode) || evm_fixmode)
433 		return INTEGRITY_PASS;
434 	return evm_verify_hmac(dentry, NULL, NULL, 0, NULL);
435 }
436 
437 /*
438  * evm_xattr_change - check if passed xattr value differs from current value
439  * @idmap: idmap of the mount
440  * @dentry: pointer to the affected dentry
441  * @xattr_name: requested xattr
442  * @xattr_value: requested xattr value
443  * @xattr_value_len: requested xattr value length
444  *
445  * Check if passed xattr value differs from current value.
446  *
447  * Returns 1 if passed xattr value differs from current value, 0 otherwise.
448  */
449 static int evm_xattr_change(struct mnt_idmap *idmap,
450 			    struct dentry *dentry, const char *xattr_name,
451 			    const void *xattr_value, size_t xattr_value_len)
452 {
453 	char *xattr_data = NULL;
454 	int rc = 0;
455 
456 	rc = vfs_getxattr_alloc(&nop_mnt_idmap, dentry, xattr_name, &xattr_data,
457 				0, GFP_NOFS);
458 	if (rc < 0) {
459 		rc = 1;
460 		goto out;
461 	}
462 
463 	if (rc == xattr_value_len)
464 		rc = !!memcmp(xattr_value, xattr_data, rc);
465 	else
466 		rc = 1;
467 
468 out:
469 	kfree(xattr_data);
470 	return rc;
471 }
472 
473 /*
474  * evm_protect_xattr - protect the EVM extended attribute
475  *
476  * Prevent security.evm from being modified or removed without the
477  * necessary permissions or when the existing value is invalid.
478  *
479  * The posix xattr acls are 'system' prefixed, which normally would not
480  * affect security.evm.  An interesting side affect of writing posix xattr
481  * acls is their modifying of the i_mode, which is included in security.evm.
482  * For posix xattr acls only, permit security.evm, even if it currently
483  * doesn't exist, to be updated unless the EVM signature is immutable.
484  */
485 static int evm_protect_xattr(struct mnt_idmap *idmap,
486 			     struct dentry *dentry, const char *xattr_name,
487 			     const void *xattr_value, size_t xattr_value_len)
488 {
489 	enum integrity_status evm_status;
490 
491 	if (strcmp(xattr_name, XATTR_NAME_EVM) == 0) {
492 		if (!capable(CAP_SYS_ADMIN))
493 			return -EPERM;
494 	} else if (!evm_protected_xattr(xattr_name)) {
495 		if (!posix_xattr_acl(xattr_name))
496 			return 0;
497 		evm_status = evm_verify_current_integrity(dentry);
498 		if ((evm_status == INTEGRITY_PASS) ||
499 		    (evm_status == INTEGRITY_NOXATTRS))
500 			return 0;
501 		goto out;
502 	}
503 
504 	evm_status = evm_verify_current_integrity(dentry);
505 	if (evm_status == INTEGRITY_NOXATTRS) {
506 		struct integrity_iint_cache *iint;
507 
508 		/* Exception if the HMAC is not going to be calculated. */
509 		if (evm_hmac_disabled())
510 			return 0;
511 
512 		iint = integrity_iint_find(d_backing_inode(dentry));
513 		if (iint && (iint->flags & IMA_NEW_FILE))
514 			return 0;
515 
516 		/* exception for pseudo filesystems */
517 		if (dentry->d_sb->s_magic == TMPFS_MAGIC
518 		    || dentry->d_sb->s_magic == SYSFS_MAGIC)
519 			return 0;
520 
521 		integrity_audit_msg(AUDIT_INTEGRITY_METADATA,
522 				    dentry->d_inode, dentry->d_name.name,
523 				    "update_metadata",
524 				    integrity_status_msg[evm_status],
525 				    -EPERM, 0);
526 	}
527 out:
528 	/* Exception if the HMAC is not going to be calculated. */
529 	if (evm_hmac_disabled() && (evm_status == INTEGRITY_NOLABEL ||
530 	    evm_status == INTEGRITY_UNKNOWN))
531 		return 0;
532 
533 	/*
534 	 * Writing other xattrs is safe for portable signatures, as portable
535 	 * signatures are immutable and can never be updated.
536 	 */
537 	if (evm_status == INTEGRITY_FAIL_IMMUTABLE)
538 		return 0;
539 
540 	if (evm_status == INTEGRITY_PASS_IMMUTABLE &&
541 	    !evm_xattr_change(idmap, dentry, xattr_name, xattr_value,
542 			      xattr_value_len))
543 		return 0;
544 
545 	if (evm_status != INTEGRITY_PASS &&
546 	    evm_status != INTEGRITY_PASS_IMMUTABLE)
547 		integrity_audit_msg(AUDIT_INTEGRITY_METADATA, d_backing_inode(dentry),
548 				    dentry->d_name.name, "appraise_metadata",
549 				    integrity_status_msg[evm_status],
550 				    -EPERM, 0);
551 	return evm_status == INTEGRITY_PASS ? 0 : -EPERM;
552 }
553 
554 /**
555  * evm_inode_setxattr - protect the EVM extended attribute
556  * @idmap: idmap of the mount
557  * @dentry: pointer to the affected dentry
558  * @xattr_name: pointer to the affected extended attribute name
559  * @xattr_value: pointer to the new extended attribute value
560  * @xattr_value_len: pointer to the new extended attribute value length
561  *
562  * Before allowing the 'security.evm' protected xattr to be updated,
563  * verify the existing value is valid.  As only the kernel should have
564  * access to the EVM encrypted key needed to calculate the HMAC, prevent
565  * userspace from writing HMAC value.  Writing 'security.evm' requires
566  * requires CAP_SYS_ADMIN privileges.
567  */
568 int evm_inode_setxattr(struct mnt_idmap *idmap, struct dentry *dentry,
569 		       const char *xattr_name, const void *xattr_value,
570 		       size_t xattr_value_len)
571 {
572 	const struct evm_ima_xattr_data *xattr_data = xattr_value;
573 
574 	/* Policy permits modification of the protected xattrs even though
575 	 * there's no HMAC key loaded
576 	 */
577 	if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
578 		return 0;
579 
580 	if (strcmp(xattr_name, XATTR_NAME_EVM) == 0) {
581 		if (!xattr_value_len)
582 			return -EINVAL;
583 		if (xattr_data->type != EVM_IMA_XATTR_DIGSIG &&
584 		    xattr_data->type != EVM_XATTR_PORTABLE_DIGSIG)
585 			return -EPERM;
586 	}
587 	return evm_protect_xattr(idmap, dentry, xattr_name, xattr_value,
588 				 xattr_value_len);
589 }
590 
591 /**
592  * evm_inode_removexattr - protect the EVM extended attribute
593  * @idmap: idmap of the mount
594  * @dentry: pointer to the affected dentry
595  * @xattr_name: pointer to the affected extended attribute name
596  *
597  * Removing 'security.evm' requires CAP_SYS_ADMIN privileges and that
598  * the current value is valid.
599  */
600 int evm_inode_removexattr(struct mnt_idmap *idmap,
601 			  struct dentry *dentry, const char *xattr_name)
602 {
603 	/* Policy permits modification of the protected xattrs even though
604 	 * there's no HMAC key loaded
605 	 */
606 	if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
607 		return 0;
608 
609 	return evm_protect_xattr(idmap, dentry, xattr_name, NULL, 0);
610 }
611 
612 #ifdef CONFIG_FS_POSIX_ACL
613 static int evm_inode_set_acl_change(struct mnt_idmap *idmap,
614 				    struct dentry *dentry, const char *name,
615 				    struct posix_acl *kacl)
616 {
617 	int rc;
618 
619 	umode_t mode;
620 	struct inode *inode = d_backing_inode(dentry);
621 
622 	if (!kacl)
623 		return 1;
624 
625 	rc = posix_acl_update_mode(idmap, inode, &mode, &kacl);
626 	if (rc || (inode->i_mode != mode))
627 		return 1;
628 
629 	return 0;
630 }
631 #else
632 static inline int evm_inode_set_acl_change(struct mnt_idmap *idmap,
633 					   struct dentry *dentry,
634 					   const char *name,
635 					   struct posix_acl *kacl)
636 {
637 	return 0;
638 }
639 #endif
640 
641 /**
642  * evm_inode_set_acl - protect the EVM extended attribute from posix acls
643  * @idmap: idmap of the idmapped mount
644  * @dentry: pointer to the affected dentry
645  * @acl_name: name of the posix acl
646  * @kacl: pointer to the posix acls
647  *
648  * Prevent modifying posix acls causing the EVM HMAC to be re-calculated
649  * and 'security.evm' xattr updated, unless the existing 'security.evm' is
650  * valid.
651  */
652 int evm_inode_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
653 		      const char *acl_name, struct posix_acl *kacl)
654 {
655 	enum integrity_status evm_status;
656 
657 	/* Policy permits modification of the protected xattrs even though
658 	 * there's no HMAC key loaded
659 	 */
660 	if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
661 		return 0;
662 
663 	evm_status = evm_verify_current_integrity(dentry);
664 	if ((evm_status == INTEGRITY_PASS) ||
665 	    (evm_status == INTEGRITY_NOXATTRS))
666 		return 0;
667 
668 	/* Exception if the HMAC is not going to be calculated. */
669 	if (evm_hmac_disabled() && (evm_status == INTEGRITY_NOLABEL ||
670 	    evm_status == INTEGRITY_UNKNOWN))
671 		return 0;
672 
673 	/*
674 	 * Writing other xattrs is safe for portable signatures, as portable
675 	 * signatures are immutable and can never be updated.
676 	 */
677 	if (evm_status == INTEGRITY_FAIL_IMMUTABLE)
678 		return 0;
679 
680 	if (evm_status == INTEGRITY_PASS_IMMUTABLE &&
681 	    !evm_inode_set_acl_change(idmap, dentry, acl_name, kacl))
682 		return 0;
683 
684 	if (evm_status != INTEGRITY_PASS_IMMUTABLE)
685 		integrity_audit_msg(AUDIT_INTEGRITY_METADATA, d_backing_inode(dentry),
686 				    dentry->d_name.name, "appraise_metadata",
687 				    integrity_status_msg[evm_status],
688 				    -EPERM, 0);
689 	return -EPERM;
690 }
691 
692 static void evm_reset_status(struct inode *inode)
693 {
694 	struct integrity_iint_cache *iint;
695 
696 	iint = integrity_iint_find(inode);
697 	if (iint)
698 		iint->evm_status = INTEGRITY_UNKNOWN;
699 }
700 
701 /**
702  * evm_revalidate_status - report whether EVM status re-validation is necessary
703  * @xattr_name: pointer to the affected extended attribute name
704  *
705  * Report whether callers of evm_verifyxattr() should re-validate the
706  * EVM status.
707  *
708  * Return true if re-validation is necessary, false otherwise.
709  */
710 bool evm_revalidate_status(const char *xattr_name)
711 {
712 	if (!evm_key_loaded())
713 		return false;
714 
715 	/* evm_inode_post_setattr() passes NULL */
716 	if (!xattr_name)
717 		return true;
718 
719 	if (!evm_protected_xattr(xattr_name) && !posix_xattr_acl(xattr_name) &&
720 	    strcmp(xattr_name, XATTR_NAME_EVM))
721 		return false;
722 
723 	return true;
724 }
725 
726 /**
727  * evm_inode_post_setxattr - update 'security.evm' to reflect the changes
728  * @dentry: pointer to the affected dentry
729  * @xattr_name: pointer to the affected extended attribute name
730  * @xattr_value: pointer to the new extended attribute value
731  * @xattr_value_len: pointer to the new extended attribute value length
732  *
733  * Update the HMAC stored in 'security.evm' to reflect the change.
734  *
735  * No need to take the i_mutex lock here, as this function is called from
736  * __vfs_setxattr_noperm().  The caller of which has taken the inode's
737  * i_mutex lock.
738  */
739 void evm_inode_post_setxattr(struct dentry *dentry, const char *xattr_name,
740 			     const void *xattr_value, size_t xattr_value_len)
741 {
742 	if (!evm_revalidate_status(xattr_name))
743 		return;
744 
745 	evm_reset_status(dentry->d_inode);
746 
747 	if (!strcmp(xattr_name, XATTR_NAME_EVM))
748 		return;
749 
750 	if (!(evm_initialized & EVM_INIT_HMAC))
751 		return;
752 
753 	evm_update_evmxattr(dentry, xattr_name, xattr_value, xattr_value_len);
754 }
755 
756 /**
757  * evm_inode_post_removexattr - update 'security.evm' after removing the xattr
758  * @dentry: pointer to the affected dentry
759  * @xattr_name: pointer to the affected extended attribute name
760  *
761  * Update the HMAC stored in 'security.evm' to reflect removal of the xattr.
762  *
763  * No need to take the i_mutex lock here, as this function is called from
764  * vfs_removexattr() which takes the i_mutex.
765  */
766 void evm_inode_post_removexattr(struct dentry *dentry, const char *xattr_name)
767 {
768 	if (!evm_revalidate_status(xattr_name))
769 		return;
770 
771 	evm_reset_status(dentry->d_inode);
772 
773 	if (!strcmp(xattr_name, XATTR_NAME_EVM))
774 		return;
775 
776 	if (!(evm_initialized & EVM_INIT_HMAC))
777 		return;
778 
779 	evm_update_evmxattr(dentry, xattr_name, NULL, 0);
780 }
781 
782 static int evm_attr_change(struct mnt_idmap *idmap,
783 			   struct dentry *dentry, struct iattr *attr)
784 {
785 	struct inode *inode = d_backing_inode(dentry);
786 	unsigned int ia_valid = attr->ia_valid;
787 
788 	if (!i_uid_needs_update(idmap, attr, inode) &&
789 	    !i_gid_needs_update(idmap, attr, inode) &&
790 	    (!(ia_valid & ATTR_MODE) || attr->ia_mode == inode->i_mode))
791 		return 0;
792 
793 	return 1;
794 }
795 
796 /**
797  * evm_inode_setattr - prevent updating an invalid EVM extended attribute
798  * @idmap: idmap of the mount
799  * @dentry: pointer to the affected dentry
800  * @attr: iattr structure containing the new file attributes
801  *
802  * Permit update of file attributes when files have a valid EVM signature,
803  * except in the case of them having an immutable portable signature.
804  */
805 int evm_inode_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
806 		      struct iattr *attr)
807 {
808 	unsigned int ia_valid = attr->ia_valid;
809 	enum integrity_status evm_status;
810 
811 	/* Policy permits modification of the protected attrs even though
812 	 * there's no HMAC key loaded
813 	 */
814 	if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
815 		return 0;
816 
817 	if (!(ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID)))
818 		return 0;
819 	evm_status = evm_verify_current_integrity(dentry);
820 	/*
821 	 * Writing attrs is safe for portable signatures, as portable signatures
822 	 * are immutable and can never be updated.
823 	 */
824 	if ((evm_status == INTEGRITY_PASS) ||
825 	    (evm_status == INTEGRITY_NOXATTRS) ||
826 	    (evm_status == INTEGRITY_FAIL_IMMUTABLE) ||
827 	    (evm_hmac_disabled() && (evm_status == INTEGRITY_NOLABEL ||
828 	     evm_status == INTEGRITY_UNKNOWN)))
829 		return 0;
830 
831 	if (evm_status == INTEGRITY_PASS_IMMUTABLE &&
832 	    !evm_attr_change(idmap, dentry, attr))
833 		return 0;
834 
835 	integrity_audit_msg(AUDIT_INTEGRITY_METADATA, d_backing_inode(dentry),
836 			    dentry->d_name.name, "appraise_metadata",
837 			    integrity_status_msg[evm_status], -EPERM, 0);
838 	return -EPERM;
839 }
840 
841 /**
842  * evm_inode_post_setattr - update 'security.evm' after modifying metadata
843  * @dentry: pointer to the affected dentry
844  * @ia_valid: for the UID and GID status
845  *
846  * For now, update the HMAC stored in 'security.evm' to reflect UID/GID
847  * changes.
848  *
849  * This function is called from notify_change(), which expects the caller
850  * to lock the inode's i_mutex.
851  */
852 void evm_inode_post_setattr(struct dentry *dentry, int ia_valid)
853 {
854 	if (!evm_revalidate_status(NULL))
855 		return;
856 
857 	evm_reset_status(dentry->d_inode);
858 
859 	if (!(evm_initialized & EVM_INIT_HMAC))
860 		return;
861 
862 	if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID))
863 		evm_update_evmxattr(dentry, NULL, NULL, 0);
864 }
865 
866 /*
867  * evm_inode_init_security - initializes security.evm HMAC value
868  */
869 int evm_inode_init_security(struct inode *inode,
870 				 const struct xattr *lsm_xattr,
871 				 struct xattr *evm_xattr)
872 {
873 	struct evm_xattr *xattr_data;
874 	int rc;
875 
876 	if (!(evm_initialized & EVM_INIT_HMAC) ||
877 	    !evm_protected_xattr(lsm_xattr->name))
878 		return 0;
879 
880 	xattr_data = kzalloc(sizeof(*xattr_data), GFP_NOFS);
881 	if (!xattr_data)
882 		return -ENOMEM;
883 
884 	xattr_data->data.type = EVM_XATTR_HMAC;
885 	rc = evm_init_hmac(inode, lsm_xattr, xattr_data->digest);
886 	if (rc < 0)
887 		goto out;
888 
889 	evm_xattr->value = xattr_data;
890 	evm_xattr->value_len = sizeof(*xattr_data);
891 	evm_xattr->name = XATTR_EVM_SUFFIX;
892 	return 0;
893 out:
894 	kfree(xattr_data);
895 	return rc;
896 }
897 EXPORT_SYMBOL_GPL(evm_inode_init_security);
898 
899 #ifdef CONFIG_EVM_LOAD_X509
900 void __init evm_load_x509(void)
901 {
902 	int rc;
903 
904 	rc = integrity_load_x509(INTEGRITY_KEYRING_EVM, CONFIG_EVM_X509_PATH);
905 	if (!rc)
906 		evm_initialized |= EVM_INIT_X509;
907 }
908 #endif
909 
910 static int __init init_evm(void)
911 {
912 	int error;
913 	struct list_head *pos, *q;
914 
915 	evm_init_config();
916 
917 	error = integrity_init_keyring(INTEGRITY_KEYRING_EVM);
918 	if (error)
919 		goto error;
920 
921 	error = evm_init_secfs();
922 	if (error < 0) {
923 		pr_info("Error registering secfs\n");
924 		goto error;
925 	}
926 
927 error:
928 	if (error != 0) {
929 		if (!list_empty(&evm_config_xattrnames)) {
930 			list_for_each_safe(pos, q, &evm_config_xattrnames)
931 				list_del(pos);
932 		}
933 	}
934 
935 	return error;
936 }
937 
938 late_initcall(init_evm);
939