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