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