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, and evm_verifyxattr
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(&init_user_ns, 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  * @inode: inode of the read xattrs
322  * @buffer: buffer xattr names, lengths or values are copied to
323  * @buffer_size: size of buffer
324  * @type: n: names, l: lengths, v: values
325  * @canonical_fmt: data format (true: little endian, false: native format)
326  *
327  * Read protected xattr names (separated by |), lengths (u32) or values for a
328  * given dentry and return the total size of copied data. If buffer is NULL,
329  * just return the total size.
330  *
331  * Returns the total size on success, a negative value on error.
332  */
333 int evm_read_protected_xattrs(struct dentry *dentry, u8 *buffer,
334 			      int buffer_size, char type, bool canonical_fmt)
335 {
336 	struct xattr_list *xattr;
337 	int rc, size, total_size = 0;
338 
339 	list_for_each_entry_lockless(xattr, &evm_config_xattrnames, list) {
340 		rc = __vfs_getxattr(dentry, d_backing_inode(dentry),
341 				    xattr->name, NULL, 0);
342 		if (rc < 0 && rc == -ENODATA)
343 			continue;
344 		else if (rc < 0)
345 			return rc;
346 
347 		switch (type) {
348 		case 'n':
349 			size = strlen(xattr->name) + 1;
350 			if (buffer) {
351 				if (total_size)
352 					*(buffer + total_size - 1) = '|';
353 
354 				memcpy(buffer + total_size, xattr->name, size);
355 			}
356 			break;
357 		case 'l':
358 			size = sizeof(u32);
359 			if (buffer) {
360 				if (canonical_fmt)
361 					rc = (__force int)cpu_to_le32(rc);
362 
363 				*(u32 *)(buffer + total_size) = rc;
364 			}
365 			break;
366 		case 'v':
367 			size = rc;
368 			if (buffer) {
369 				rc = __vfs_getxattr(dentry,
370 					d_backing_inode(dentry), xattr->name,
371 					buffer + total_size,
372 					buffer_size - total_size);
373 				if (rc < 0)
374 					return rc;
375 			}
376 			break;
377 		default:
378 			return -EINVAL;
379 		}
380 
381 		total_size += size;
382 	}
383 
384 	return total_size;
385 }
386 
387 /**
388  * evm_verifyxattr - verify the integrity of the requested xattr
389  * @dentry: object of the verify xattr
390  * @xattr_name: requested xattr
391  * @xattr_value: requested xattr value
392  * @xattr_value_len: requested xattr value length
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_acl_change - check if passed ACL changes the inode mode
439  * @mnt_userns: user namespace of the idmapped 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 ACL changes the inode mode, which is protected by EVM.
446  *
447  * Returns 1 if passed ACL causes inode mode change, 0 otherwise.
448  */
449 static int evm_xattr_acl_change(struct user_namespace *mnt_userns,
450 				struct dentry *dentry, const char *xattr_name,
451 				const void *xattr_value, size_t xattr_value_len)
452 {
453 #ifdef CONFIG_FS_POSIX_ACL
454 	umode_t mode;
455 	struct posix_acl *acl = NULL, *acl_res;
456 	struct inode *inode = d_backing_inode(dentry);
457 	int rc;
458 
459 	/*
460 	 * An earlier comment here mentioned that the idmappings for
461 	 * ACL_{GROUP,USER} don't matter since EVM is only interested in the
462 	 * mode stored as part of POSIX ACLs. Nonetheless, if it must translate
463 	 * from the uapi POSIX ACL representation to the VFS internal POSIX ACL
464 	 * representation it should do so correctly. There's no guarantee that
465 	 * we won't change POSIX ACLs in a way that ACL_{GROUP,USER} matters
466 	 * for the mode at some point and it's difficult to keep track of all
467 	 * the LSM and integrity modules and what they do to POSIX ACLs.
468 	 *
469 	 * Frankly, EVM shouldn't try to interpret the uapi struct for POSIX
470 	 * ACLs it received. It requires knowledge that only the VFS is
471 	 * guaranteed to have.
472 	 */
473 	acl = vfs_set_acl_prepare(mnt_userns, i_user_ns(inode),
474 				  xattr_value, xattr_value_len);
475 	if (IS_ERR_OR_NULL(acl))
476 		return 1;
477 
478 	acl_res = acl;
479 	/*
480 	 * Passing mnt_userns is necessary to correctly determine the GID in
481 	 * an idmapped mount, as the GID is used to clear the setgid bit in
482 	 * the inode mode.
483 	 */
484 	rc = posix_acl_update_mode(mnt_userns, inode, &mode, &acl_res);
485 
486 	posix_acl_release(acl);
487 
488 	if (rc)
489 		return 1;
490 
491 	if (inode->i_mode != mode)
492 		return 1;
493 #endif
494 	return 0;
495 }
496 
497 /*
498  * evm_xattr_change - check if passed xattr value differs from current value
499  * @mnt_userns: user namespace of the idmapped mount
500  * @dentry: pointer to the affected dentry
501  * @xattr_name: requested xattr
502  * @xattr_value: requested xattr value
503  * @xattr_value_len: requested xattr value length
504  *
505  * Check if passed xattr value differs from current value.
506  *
507  * Returns 1 if passed xattr value differs from current value, 0 otherwise.
508  */
509 static int evm_xattr_change(struct user_namespace *mnt_userns,
510 			    struct dentry *dentry, const char *xattr_name,
511 			    const void *xattr_value, size_t xattr_value_len)
512 {
513 	char *xattr_data = NULL;
514 	int rc = 0;
515 
516 	if (posix_xattr_acl(xattr_name))
517 		return evm_xattr_acl_change(mnt_userns, dentry, xattr_name,
518 					    xattr_value, xattr_value_len);
519 
520 	rc = vfs_getxattr_alloc(&init_user_ns, dentry, xattr_name, &xattr_data,
521 				0, GFP_NOFS);
522 	if (rc < 0)
523 		return 1;
524 
525 	if (rc == xattr_value_len)
526 		rc = !!memcmp(xattr_value, xattr_data, rc);
527 	else
528 		rc = 1;
529 
530 	kfree(xattr_data);
531 	return rc;
532 }
533 
534 /*
535  * evm_protect_xattr - protect the EVM extended attribute
536  *
537  * Prevent security.evm from being modified or removed without the
538  * necessary permissions or when the existing value is invalid.
539  *
540  * The posix xattr acls are 'system' prefixed, which normally would not
541  * affect security.evm.  An interesting side affect of writing posix xattr
542  * acls is their modifying of the i_mode, which is included in security.evm.
543  * For posix xattr acls only, permit security.evm, even if it currently
544  * doesn't exist, to be updated unless the EVM signature is immutable.
545  */
546 static int evm_protect_xattr(struct user_namespace *mnt_userns,
547 			     struct dentry *dentry, const char *xattr_name,
548 			     const void *xattr_value, size_t xattr_value_len)
549 {
550 	enum integrity_status evm_status;
551 
552 	if (strcmp(xattr_name, XATTR_NAME_EVM) == 0) {
553 		if (!capable(CAP_SYS_ADMIN))
554 			return -EPERM;
555 	} else if (!evm_protected_xattr(xattr_name)) {
556 		if (!posix_xattr_acl(xattr_name))
557 			return 0;
558 		evm_status = evm_verify_current_integrity(dentry);
559 		if ((evm_status == INTEGRITY_PASS) ||
560 		    (evm_status == INTEGRITY_NOXATTRS))
561 			return 0;
562 		goto out;
563 	}
564 
565 	evm_status = evm_verify_current_integrity(dentry);
566 	if (evm_status == INTEGRITY_NOXATTRS) {
567 		struct integrity_iint_cache *iint;
568 
569 		/* Exception if the HMAC is not going to be calculated. */
570 		if (evm_hmac_disabled())
571 			return 0;
572 
573 		iint = integrity_iint_find(d_backing_inode(dentry));
574 		if (iint && (iint->flags & IMA_NEW_FILE))
575 			return 0;
576 
577 		/* exception for pseudo filesystems */
578 		if (dentry->d_sb->s_magic == TMPFS_MAGIC
579 		    || dentry->d_sb->s_magic == SYSFS_MAGIC)
580 			return 0;
581 
582 		integrity_audit_msg(AUDIT_INTEGRITY_METADATA,
583 				    dentry->d_inode, dentry->d_name.name,
584 				    "update_metadata",
585 				    integrity_status_msg[evm_status],
586 				    -EPERM, 0);
587 	}
588 out:
589 	/* Exception if the HMAC is not going to be calculated. */
590 	if (evm_hmac_disabled() && (evm_status == INTEGRITY_NOLABEL ||
591 	    evm_status == INTEGRITY_UNKNOWN))
592 		return 0;
593 
594 	/*
595 	 * Writing other xattrs is safe for portable signatures, as portable
596 	 * signatures are immutable and can never be updated.
597 	 */
598 	if (evm_status == INTEGRITY_FAIL_IMMUTABLE)
599 		return 0;
600 
601 	if (evm_status == INTEGRITY_PASS_IMMUTABLE &&
602 	    !evm_xattr_change(mnt_userns, dentry, xattr_name, xattr_value,
603 			      xattr_value_len))
604 		return 0;
605 
606 	if (evm_status != INTEGRITY_PASS &&
607 	    evm_status != INTEGRITY_PASS_IMMUTABLE)
608 		integrity_audit_msg(AUDIT_INTEGRITY_METADATA, d_backing_inode(dentry),
609 				    dentry->d_name.name, "appraise_metadata",
610 				    integrity_status_msg[evm_status],
611 				    -EPERM, 0);
612 	return evm_status == INTEGRITY_PASS ? 0 : -EPERM;
613 }
614 
615 /**
616  * evm_inode_setxattr - protect the EVM extended attribute
617  * @mnt_userns: user namespace of the idmapped mount
618  * @dentry: pointer to the affected dentry
619  * @xattr_name: pointer to the affected extended attribute name
620  * @xattr_value: pointer to the new extended attribute value
621  * @xattr_value_len: pointer to the new extended attribute value length
622  *
623  * Before allowing the 'security.evm' protected xattr to be updated,
624  * verify the existing value is valid.  As only the kernel should have
625  * access to the EVM encrypted key needed to calculate the HMAC, prevent
626  * userspace from writing HMAC value.  Writing 'security.evm' requires
627  * requires CAP_SYS_ADMIN privileges.
628  */
629 int evm_inode_setxattr(struct user_namespace *mnt_userns, struct dentry *dentry,
630 		       const char *xattr_name, const void *xattr_value,
631 		       size_t xattr_value_len)
632 {
633 	const struct evm_ima_xattr_data *xattr_data = xattr_value;
634 
635 	/* Policy permits modification of the protected xattrs even though
636 	 * there's no HMAC key loaded
637 	 */
638 	if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
639 		return 0;
640 
641 	if (strcmp(xattr_name, XATTR_NAME_EVM) == 0) {
642 		if (!xattr_value_len)
643 			return -EINVAL;
644 		if (xattr_data->type != EVM_IMA_XATTR_DIGSIG &&
645 		    xattr_data->type != EVM_XATTR_PORTABLE_DIGSIG)
646 			return -EPERM;
647 	}
648 	return evm_protect_xattr(mnt_userns, dentry, xattr_name, xattr_value,
649 				 xattr_value_len);
650 }
651 
652 /**
653  * evm_inode_removexattr - protect the EVM extended attribute
654  * @mnt_userns: user namespace of the idmapped mount
655  * @dentry: pointer to the affected dentry
656  * @xattr_name: pointer to the affected extended attribute name
657  *
658  * Removing 'security.evm' requires CAP_SYS_ADMIN privileges and that
659  * the current value is valid.
660  */
661 int evm_inode_removexattr(struct user_namespace *mnt_userns,
662 			  struct dentry *dentry, const char *xattr_name)
663 {
664 	/* Policy permits modification of the protected xattrs even though
665 	 * there's no HMAC key loaded
666 	 */
667 	if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
668 		return 0;
669 
670 	return evm_protect_xattr(mnt_userns, dentry, xattr_name, NULL, 0);
671 }
672 
673 static void evm_reset_status(struct inode *inode)
674 {
675 	struct integrity_iint_cache *iint;
676 
677 	iint = integrity_iint_find(inode);
678 	if (iint)
679 		iint->evm_status = INTEGRITY_UNKNOWN;
680 }
681 
682 /**
683  * evm_revalidate_status - report whether EVM status re-validation is necessary
684  * @xattr_name: pointer to the affected extended attribute name
685  *
686  * Report whether callers of evm_verifyxattr() should re-validate the
687  * EVM status.
688  *
689  * Return true if re-validation is necessary, false otherwise.
690  */
691 bool evm_revalidate_status(const char *xattr_name)
692 {
693 	if (!evm_key_loaded())
694 		return false;
695 
696 	/* evm_inode_post_setattr() passes NULL */
697 	if (!xattr_name)
698 		return true;
699 
700 	if (!evm_protected_xattr(xattr_name) && !posix_xattr_acl(xattr_name) &&
701 	    strcmp(xattr_name, XATTR_NAME_EVM))
702 		return false;
703 
704 	return true;
705 }
706 
707 /**
708  * evm_inode_post_setxattr - update 'security.evm' to reflect the changes
709  * @dentry: pointer to the affected dentry
710  * @xattr_name: pointer to the affected extended attribute name
711  * @xattr_value: pointer to the new extended attribute value
712  * @xattr_value_len: pointer to the new extended attribute value length
713  *
714  * Update the HMAC stored in 'security.evm' to reflect the change.
715  *
716  * No need to take the i_mutex lock here, as this function is called from
717  * __vfs_setxattr_noperm().  The caller of which has taken the inode's
718  * i_mutex lock.
719  */
720 void evm_inode_post_setxattr(struct dentry *dentry, const char *xattr_name,
721 			     const void *xattr_value, size_t xattr_value_len)
722 {
723 	if (!evm_revalidate_status(xattr_name))
724 		return;
725 
726 	evm_reset_status(dentry->d_inode);
727 
728 	if (!strcmp(xattr_name, XATTR_NAME_EVM))
729 		return;
730 
731 	if (!(evm_initialized & EVM_INIT_HMAC))
732 		return;
733 
734 	evm_update_evmxattr(dentry, xattr_name, xattr_value, xattr_value_len);
735 }
736 
737 /**
738  * evm_inode_post_removexattr - update 'security.evm' after removing the xattr
739  * @dentry: pointer to the affected dentry
740  * @xattr_name: pointer to the affected extended attribute name
741  *
742  * Update the HMAC stored in 'security.evm' to reflect removal of the xattr.
743  *
744  * No need to take the i_mutex lock here, as this function is called from
745  * vfs_removexattr() which takes the i_mutex.
746  */
747 void evm_inode_post_removexattr(struct dentry *dentry, const char *xattr_name)
748 {
749 	if (!evm_revalidate_status(xattr_name))
750 		return;
751 
752 	evm_reset_status(dentry->d_inode);
753 
754 	if (!strcmp(xattr_name, XATTR_NAME_EVM))
755 		return;
756 
757 	if (!(evm_initialized & EVM_INIT_HMAC))
758 		return;
759 
760 	evm_update_evmxattr(dentry, xattr_name, NULL, 0);
761 }
762 
763 static int evm_attr_change(struct user_namespace *mnt_userns,
764 			   struct dentry *dentry, struct iattr *attr)
765 {
766 	struct inode *inode = d_backing_inode(dentry);
767 	unsigned int ia_valid = attr->ia_valid;
768 
769 	if (!i_uid_needs_update(mnt_userns, attr, inode) &&
770 	    !i_gid_needs_update(mnt_userns, attr, inode) &&
771 	    (!(ia_valid & ATTR_MODE) || attr->ia_mode == inode->i_mode))
772 		return 0;
773 
774 	return 1;
775 }
776 
777 /**
778  * evm_inode_setattr - prevent updating an invalid EVM extended attribute
779  * @dentry: pointer to the affected dentry
780  *
781  * Permit update of file attributes when files have a valid EVM signature,
782  * except in the case of them having an immutable portable signature.
783  */
784 int evm_inode_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
785 		      struct iattr *attr)
786 {
787 	unsigned int ia_valid = attr->ia_valid;
788 	enum integrity_status evm_status;
789 
790 	/* Policy permits modification of the protected attrs even though
791 	 * there's no HMAC key loaded
792 	 */
793 	if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
794 		return 0;
795 
796 	if (!(ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID)))
797 		return 0;
798 	evm_status = evm_verify_current_integrity(dentry);
799 	/*
800 	 * Writing attrs is safe for portable signatures, as portable signatures
801 	 * are immutable and can never be updated.
802 	 */
803 	if ((evm_status == INTEGRITY_PASS) ||
804 	    (evm_status == INTEGRITY_NOXATTRS) ||
805 	    (evm_status == INTEGRITY_FAIL_IMMUTABLE) ||
806 	    (evm_hmac_disabled() && (evm_status == INTEGRITY_NOLABEL ||
807 	     evm_status == INTEGRITY_UNKNOWN)))
808 		return 0;
809 
810 	if (evm_status == INTEGRITY_PASS_IMMUTABLE &&
811 	    !evm_attr_change(mnt_userns, dentry, attr))
812 		return 0;
813 
814 	integrity_audit_msg(AUDIT_INTEGRITY_METADATA, d_backing_inode(dentry),
815 			    dentry->d_name.name, "appraise_metadata",
816 			    integrity_status_msg[evm_status], -EPERM, 0);
817 	return -EPERM;
818 }
819 
820 /**
821  * evm_inode_post_setattr - update 'security.evm' after modifying metadata
822  * @dentry: pointer to the affected dentry
823  * @ia_valid: for the UID and GID status
824  *
825  * For now, update the HMAC stored in 'security.evm' to reflect UID/GID
826  * changes.
827  *
828  * This function is called from notify_change(), which expects the caller
829  * to lock the inode's i_mutex.
830  */
831 void evm_inode_post_setattr(struct dentry *dentry, int ia_valid)
832 {
833 	if (!evm_revalidate_status(NULL))
834 		return;
835 
836 	evm_reset_status(dentry->d_inode);
837 
838 	if (!(evm_initialized & EVM_INIT_HMAC))
839 		return;
840 
841 	if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID))
842 		evm_update_evmxattr(dentry, NULL, NULL, 0);
843 }
844 
845 /*
846  * evm_inode_init_security - initializes security.evm HMAC value
847  */
848 int evm_inode_init_security(struct inode *inode,
849 				 const struct xattr *lsm_xattr,
850 				 struct xattr *evm_xattr)
851 {
852 	struct evm_xattr *xattr_data;
853 	int rc;
854 
855 	if (!(evm_initialized & EVM_INIT_HMAC) ||
856 	    !evm_protected_xattr(lsm_xattr->name))
857 		return 0;
858 
859 	xattr_data = kzalloc(sizeof(*xattr_data), GFP_NOFS);
860 	if (!xattr_data)
861 		return -ENOMEM;
862 
863 	xattr_data->data.type = EVM_XATTR_HMAC;
864 	rc = evm_init_hmac(inode, lsm_xattr, xattr_data->digest);
865 	if (rc < 0)
866 		goto out;
867 
868 	evm_xattr->value = xattr_data;
869 	evm_xattr->value_len = sizeof(*xattr_data);
870 	evm_xattr->name = XATTR_EVM_SUFFIX;
871 	return 0;
872 out:
873 	kfree(xattr_data);
874 	return rc;
875 }
876 EXPORT_SYMBOL_GPL(evm_inode_init_security);
877 
878 #ifdef CONFIG_EVM_LOAD_X509
879 void __init evm_load_x509(void)
880 {
881 	int rc;
882 
883 	rc = integrity_load_x509(INTEGRITY_KEYRING_EVM, CONFIG_EVM_X509_PATH);
884 	if (!rc)
885 		evm_initialized |= EVM_INIT_X509;
886 }
887 #endif
888 
889 static int __init init_evm(void)
890 {
891 	int error;
892 	struct list_head *pos, *q;
893 
894 	evm_init_config();
895 
896 	error = integrity_init_keyring(INTEGRITY_KEYRING_EVM);
897 	if (error)
898 		goto error;
899 
900 	error = evm_init_secfs();
901 	if (error < 0) {
902 		pr_info("Error registering secfs\n");
903 		goto error;
904 	}
905 
906 error:
907 	if (error != 0) {
908 		if (!list_empty(&evm_config_xattrnames)) {
909 			list_for_each_safe(pos, q, &evm_config_xattrnames)
910 				list_del(pos);
911 		}
912 	}
913 
914 	return error;
915 }
916 
917 late_initcall(init_evm);
918