xref: /linux/security/integrity/ima/ima_appraise.c (revision 151ebcf0797b1a3ba53c8843dc21748c80e098c7)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2011 IBM Corporation
4  *
5  * Author:
6  * Mimi Zohar <zohar@us.ibm.com>
7  */
8 #include <linux/module.h>
9 #include <linux/init.h>
10 #include <linux/file.h>
11 #include <linux/fs.h>
12 #include <linux/xattr.h>
13 #include <linux/magic.h>
14 #include <linux/ima.h>
15 #include <linux/evm.h>
16 #include <linux/fsverity.h>
17 #include <keys/system_keyring.h>
18 #include <uapi/linux/fsverity.h>
19 
20 #include "ima.h"
21 
22 #ifdef CONFIG_IMA_APPRAISE_BOOTPARAM
23 static char *ima_appraise_cmdline_default __initdata;
24 core_param(ima_appraise, ima_appraise_cmdline_default, charp, 0);
25 
26 void __init ima_appraise_parse_cmdline(void)
27 {
28 	const char *str = ima_appraise_cmdline_default;
29 	bool sb_state = arch_ima_get_secureboot();
30 	int appraisal_state = ima_appraise;
31 
32 	if (!str)
33 		return;
34 
35 	if (strncmp(str, "off", 3) == 0)
36 		appraisal_state = 0;
37 	else if (strncmp(str, "log", 3) == 0)
38 		appraisal_state = IMA_APPRAISE_LOG;
39 	else if (strncmp(str, "fix", 3) == 0)
40 		appraisal_state = IMA_APPRAISE_FIX;
41 	else if (strncmp(str, "enforce", 7) == 0)
42 		appraisal_state = IMA_APPRAISE_ENFORCE;
43 	else
44 		pr_err("invalid \"%s\" appraise option", str);
45 
46 	/* If appraisal state was changed, but secure boot is enabled,
47 	 * keep its default */
48 	if (sb_state) {
49 		if (!(appraisal_state & IMA_APPRAISE_ENFORCE))
50 			pr_info("Secure boot enabled: ignoring ima_appraise=%s option",
51 				str);
52 	} else {
53 		ima_appraise = appraisal_state;
54 	}
55 }
56 #endif
57 
58 /*
59  * is_ima_appraise_enabled - return appraise status
60  *
61  * Only return enabled, if not in ima_appraise="fix" or "log" modes.
62  */
63 bool is_ima_appraise_enabled(void)
64 {
65 	return ima_appraise & IMA_APPRAISE_ENFORCE;
66 }
67 
68 /*
69  * ima_must_appraise - set appraise flag
70  *
71  * Return 1 to appraise or hash
72  */
73 int ima_must_appraise(struct mnt_idmap *idmap, struct inode *inode,
74 		      int mask, enum ima_hooks func)
75 {
76 	u32 secid;
77 
78 	if (!ima_appraise)
79 		return 0;
80 
81 	security_current_getsecid_subj(&secid);
82 	return ima_match_policy(idmap, inode, current_cred(), secid,
83 				func, mask, IMA_APPRAISE | IMA_HASH, NULL,
84 				NULL, NULL, NULL);
85 }
86 
87 static int ima_fix_xattr(struct dentry *dentry, struct ima_iint_cache *iint)
88 {
89 	int rc, offset;
90 	u8 algo = iint->ima_hash->algo;
91 
92 	if (algo <= HASH_ALGO_SHA1) {
93 		offset = 1;
94 		iint->ima_hash->xattr.sha1.type = IMA_XATTR_DIGEST;
95 	} else {
96 		offset = 0;
97 		iint->ima_hash->xattr.ng.type = IMA_XATTR_DIGEST_NG;
98 		iint->ima_hash->xattr.ng.algo = algo;
99 	}
100 	rc = __vfs_setxattr_noperm(&nop_mnt_idmap, dentry, XATTR_NAME_IMA,
101 				   &iint->ima_hash->xattr.data[offset],
102 				   (sizeof(iint->ima_hash->xattr) - offset) +
103 				   iint->ima_hash->length, 0);
104 	return rc;
105 }
106 
107 /* Return specific func appraised cached result */
108 enum integrity_status ima_get_cache_status(struct ima_iint_cache *iint,
109 					   enum ima_hooks func)
110 {
111 	switch (func) {
112 	case MMAP_CHECK:
113 	case MMAP_CHECK_REQPROT:
114 		return iint->ima_mmap_status;
115 	case BPRM_CHECK:
116 		return iint->ima_bprm_status;
117 	case CREDS_CHECK:
118 		return iint->ima_creds_status;
119 	case FILE_CHECK:
120 	case POST_SETATTR:
121 		return iint->ima_file_status;
122 	case MODULE_CHECK ... MAX_CHECK - 1:
123 	default:
124 		return iint->ima_read_status;
125 	}
126 }
127 
128 static void ima_set_cache_status(struct ima_iint_cache *iint,
129 				 enum ima_hooks func,
130 				 enum integrity_status status)
131 {
132 	switch (func) {
133 	case MMAP_CHECK:
134 	case MMAP_CHECK_REQPROT:
135 		iint->ima_mmap_status = status;
136 		break;
137 	case BPRM_CHECK:
138 		iint->ima_bprm_status = status;
139 		break;
140 	case CREDS_CHECK:
141 		iint->ima_creds_status = status;
142 		break;
143 	case FILE_CHECK:
144 	case POST_SETATTR:
145 		iint->ima_file_status = status;
146 		break;
147 	case MODULE_CHECK ... MAX_CHECK - 1:
148 	default:
149 		iint->ima_read_status = status;
150 		break;
151 	}
152 }
153 
154 static void ima_cache_flags(struct ima_iint_cache *iint, enum ima_hooks func)
155 {
156 	switch (func) {
157 	case MMAP_CHECK:
158 	case MMAP_CHECK_REQPROT:
159 		iint->flags |= (IMA_MMAP_APPRAISED | IMA_APPRAISED);
160 		break;
161 	case BPRM_CHECK:
162 		iint->flags |= (IMA_BPRM_APPRAISED | IMA_APPRAISED);
163 		break;
164 	case CREDS_CHECK:
165 		iint->flags |= (IMA_CREDS_APPRAISED | IMA_APPRAISED);
166 		break;
167 	case FILE_CHECK:
168 	case POST_SETATTR:
169 		iint->flags |= (IMA_FILE_APPRAISED | IMA_APPRAISED);
170 		break;
171 	case MODULE_CHECK ... MAX_CHECK - 1:
172 	default:
173 		iint->flags |= (IMA_READ_APPRAISED | IMA_APPRAISED);
174 		break;
175 	}
176 }
177 
178 enum hash_algo ima_get_hash_algo(const struct evm_ima_xattr_data *xattr_value,
179 				 int xattr_len)
180 {
181 	struct signature_v2_hdr *sig;
182 	enum hash_algo ret;
183 
184 	if (!xattr_value || xattr_len < 2)
185 		/* return default hash algo */
186 		return ima_hash_algo;
187 
188 	switch (xattr_value->type) {
189 	case IMA_VERITY_DIGSIG:
190 		sig = (typeof(sig))xattr_value;
191 		if (sig->version != 3 || xattr_len <= sizeof(*sig) ||
192 		    sig->hash_algo >= HASH_ALGO__LAST)
193 			return ima_hash_algo;
194 		return sig->hash_algo;
195 	case EVM_IMA_XATTR_DIGSIG:
196 		sig = (typeof(sig))xattr_value;
197 		if (sig->version != 2 || xattr_len <= sizeof(*sig)
198 		    || sig->hash_algo >= HASH_ALGO__LAST)
199 			return ima_hash_algo;
200 		return sig->hash_algo;
201 	case IMA_XATTR_DIGEST_NG:
202 		/* first byte contains algorithm id */
203 		ret = xattr_value->data[0];
204 		if (ret < HASH_ALGO__LAST)
205 			return ret;
206 		break;
207 	case IMA_XATTR_DIGEST:
208 		/* this is for backward compatibility */
209 		if (xattr_len == 21) {
210 			unsigned int zero = 0;
211 			if (!memcmp(&xattr_value->data[16], &zero, 4))
212 				return HASH_ALGO_MD5;
213 			else
214 				return HASH_ALGO_SHA1;
215 		} else if (xattr_len == 17)
216 			return HASH_ALGO_MD5;
217 		break;
218 	}
219 
220 	/* return default hash algo */
221 	return ima_hash_algo;
222 }
223 
224 int ima_read_xattr(struct dentry *dentry,
225 		   struct evm_ima_xattr_data **xattr_value, int xattr_len)
226 {
227 	int ret;
228 
229 	ret = vfs_getxattr_alloc(&nop_mnt_idmap, dentry, XATTR_NAME_IMA,
230 				 (char **)xattr_value, xattr_len, GFP_NOFS);
231 	if (ret == -EOPNOTSUPP)
232 		ret = 0;
233 	return ret;
234 }
235 
236 /*
237  * calc_file_id_hash - calculate the hash of the ima_file_id struct data
238  * @type: xattr type [enum evm_ima_xattr_type]
239  * @algo: hash algorithm [enum hash_algo]
240  * @digest: pointer to the digest to be hashed
241  * @hash: (out) pointer to the hash
242  *
243  * IMA signature version 3 disambiguates the data that is signed by
244  * indirectly signing the hash of the ima_file_id structure data.
245  *
246  * Signing the ima_file_id struct is currently only supported for
247  * IMA_VERITY_DIGSIG type xattrs.
248  *
249  * Return 0 on success, error code otherwise.
250  */
251 static int calc_file_id_hash(enum evm_ima_xattr_type type,
252 			     enum hash_algo algo, const u8 *digest,
253 			     struct ima_digest_data *hash)
254 {
255 	struct ima_file_id file_id = {
256 		.hash_type = IMA_VERITY_DIGSIG, .hash_algorithm = algo};
257 	unsigned int unused = HASH_MAX_DIGESTSIZE - hash_digest_size[algo];
258 
259 	if (type != IMA_VERITY_DIGSIG)
260 		return -EINVAL;
261 
262 	memcpy(file_id.hash, digest, hash_digest_size[algo]);
263 
264 	hash->algo = algo;
265 	hash->length = hash_digest_size[algo];
266 
267 	return ima_calc_buffer_hash(&file_id, sizeof(file_id) - unused, hash);
268 }
269 
270 /*
271  * xattr_verify - verify xattr digest or signature
272  *
273  * Verify whether the hash or signature matches the file contents.
274  *
275  * Return 0 on success, error code otherwise.
276  */
277 static int xattr_verify(enum ima_hooks func, struct ima_iint_cache *iint,
278 			struct evm_ima_xattr_data *xattr_value, int xattr_len,
279 			enum integrity_status *status, const char **cause)
280 {
281 	struct ima_max_digest_data hash;
282 	struct signature_v2_hdr *sig;
283 	int rc = -EINVAL, hash_start = 0;
284 	int mask;
285 
286 	switch (xattr_value->type) {
287 	case IMA_XATTR_DIGEST_NG:
288 		/* first byte contains algorithm id */
289 		hash_start = 1;
290 		fallthrough;
291 	case IMA_XATTR_DIGEST:
292 		if (*status != INTEGRITY_PASS_IMMUTABLE) {
293 			if (iint->flags & IMA_DIGSIG_REQUIRED) {
294 				if (iint->flags & IMA_VERITY_REQUIRED)
295 					*cause = "verity-signature-required";
296 				else
297 					*cause = "IMA-signature-required";
298 				*status = INTEGRITY_FAIL;
299 				break;
300 			}
301 			clear_bit(IMA_DIGSIG, &iint->atomic_flags);
302 		} else {
303 			set_bit(IMA_DIGSIG, &iint->atomic_flags);
304 		}
305 		if (xattr_len - sizeof(xattr_value->type) - hash_start >=
306 				iint->ima_hash->length)
307 			/*
308 			 * xattr length may be longer. md5 hash in previous
309 			 * version occupied 20 bytes in xattr, instead of 16
310 			 */
311 			rc = memcmp(&xattr_value->data[hash_start],
312 				    iint->ima_hash->digest,
313 				    iint->ima_hash->length);
314 		else
315 			rc = -EINVAL;
316 		if (rc) {
317 			*cause = "invalid-hash";
318 			*status = INTEGRITY_FAIL;
319 			break;
320 		}
321 		*status = INTEGRITY_PASS;
322 		break;
323 	case EVM_IMA_XATTR_DIGSIG:
324 		set_bit(IMA_DIGSIG, &iint->atomic_flags);
325 
326 		mask = IMA_DIGSIG_REQUIRED | IMA_VERITY_REQUIRED;
327 		if ((iint->flags & mask) == mask) {
328 			*cause = "verity-signature-required";
329 			*status = INTEGRITY_FAIL;
330 			break;
331 		}
332 
333 		sig = (typeof(sig))xattr_value;
334 		if (sig->version >= 3) {
335 			*cause = "invalid-signature-version";
336 			*status = INTEGRITY_FAIL;
337 			break;
338 		}
339 		rc = integrity_digsig_verify(INTEGRITY_KEYRING_IMA,
340 					     (const char *)xattr_value,
341 					     xattr_len,
342 					     iint->ima_hash->digest,
343 					     iint->ima_hash->length);
344 		if (rc == -EOPNOTSUPP) {
345 			*status = INTEGRITY_UNKNOWN;
346 			break;
347 		}
348 		if (IS_ENABLED(CONFIG_INTEGRITY_PLATFORM_KEYRING) && rc &&
349 		    func == KEXEC_KERNEL_CHECK)
350 			rc = integrity_digsig_verify(INTEGRITY_KEYRING_PLATFORM,
351 						     (const char *)xattr_value,
352 						     xattr_len,
353 						     iint->ima_hash->digest,
354 						     iint->ima_hash->length);
355 		if (rc) {
356 			*cause = "invalid-signature";
357 			*status = INTEGRITY_FAIL;
358 		} else {
359 			*status = INTEGRITY_PASS;
360 		}
361 		break;
362 	case IMA_VERITY_DIGSIG:
363 		set_bit(IMA_DIGSIG, &iint->atomic_flags);
364 
365 		if (iint->flags & IMA_DIGSIG_REQUIRED) {
366 			if (!(iint->flags & IMA_VERITY_REQUIRED)) {
367 				*cause = "IMA-signature-required";
368 				*status = INTEGRITY_FAIL;
369 				break;
370 			}
371 		}
372 
373 		sig = (typeof(sig))xattr_value;
374 		if (sig->version != 3) {
375 			*cause = "invalid-signature-version";
376 			*status = INTEGRITY_FAIL;
377 			break;
378 		}
379 
380 		rc = calc_file_id_hash(IMA_VERITY_DIGSIG, iint->ima_hash->algo,
381 				       iint->ima_hash->digest,
382 				       container_of(&hash.hdr,
383 					       struct ima_digest_data, hdr));
384 		if (rc) {
385 			*cause = "sigv3-hashing-error";
386 			*status = INTEGRITY_FAIL;
387 			break;
388 		}
389 
390 		rc = integrity_digsig_verify(INTEGRITY_KEYRING_IMA,
391 					     (const char *)xattr_value,
392 					     xattr_len, hash.digest,
393 					     hash.hdr.length);
394 		if (rc) {
395 			*cause = "invalid-verity-signature";
396 			*status = INTEGRITY_FAIL;
397 		} else {
398 			*status = INTEGRITY_PASS;
399 		}
400 
401 		break;
402 	default:
403 		*status = INTEGRITY_UNKNOWN;
404 		*cause = "unknown-ima-data";
405 		break;
406 	}
407 
408 	return rc;
409 }
410 
411 /*
412  * modsig_verify - verify modsig signature
413  *
414  * Verify whether the signature matches the file contents.
415  *
416  * Return 0 on success, error code otherwise.
417  */
418 static int modsig_verify(enum ima_hooks func, const struct modsig *modsig,
419 			 enum integrity_status *status, const char **cause)
420 {
421 	int rc;
422 
423 	rc = integrity_modsig_verify(INTEGRITY_KEYRING_IMA, modsig);
424 	if (IS_ENABLED(CONFIG_INTEGRITY_PLATFORM_KEYRING) && rc &&
425 	    func == KEXEC_KERNEL_CHECK)
426 		rc = integrity_modsig_verify(INTEGRITY_KEYRING_PLATFORM,
427 					     modsig);
428 	if (rc) {
429 		*cause = "invalid-signature";
430 		*status = INTEGRITY_FAIL;
431 	} else {
432 		*status = INTEGRITY_PASS;
433 	}
434 
435 	return rc;
436 }
437 
438 /*
439  * ima_check_blacklist - determine if the binary is blacklisted.
440  *
441  * Add the hash of the blacklisted binary to the measurement list, based
442  * on policy.
443  *
444  * Returns -EPERM if the hash is blacklisted.
445  */
446 int ima_check_blacklist(struct ima_iint_cache *iint,
447 			const struct modsig *modsig, int pcr)
448 {
449 	enum hash_algo hash_algo;
450 	const u8 *digest = NULL;
451 	u32 digestsize = 0;
452 	int rc = 0;
453 
454 	if (!(iint->flags & IMA_CHECK_BLACKLIST))
455 		return 0;
456 
457 	if (iint->flags & IMA_MODSIG_ALLOWED && modsig) {
458 		ima_get_modsig_digest(modsig, &hash_algo, &digest, &digestsize);
459 
460 		rc = is_binary_blacklisted(digest, digestsize);
461 	} else if (iint->flags & IMA_DIGSIG_REQUIRED && iint->ima_hash)
462 		rc = is_binary_blacklisted(iint->ima_hash->digest, iint->ima_hash->length);
463 
464 	if ((rc == -EPERM) && (iint->flags & IMA_MEASURE))
465 		process_buffer_measurement(&nop_mnt_idmap, NULL, digest, digestsize,
466 					   "blacklisted-hash", NONE,
467 					   pcr, NULL, false, NULL, 0);
468 
469 	return rc;
470 }
471 
472 /*
473  * ima_appraise_measurement - appraise file measurement
474  *
475  * Call evm_verifyxattr() to verify the integrity of 'security.ima'.
476  * Assuming success, compare the xattr hash with the collected measurement.
477  *
478  * Return 0 on success, error code otherwise
479  */
480 int ima_appraise_measurement(enum ima_hooks func, struct ima_iint_cache *iint,
481 			     struct file *file, const unsigned char *filename,
482 			     struct evm_ima_xattr_data *xattr_value,
483 			     int xattr_len, const struct modsig *modsig)
484 {
485 	static const char op[] = "appraise_data";
486 	const char *cause = "unknown";
487 	struct dentry *dentry = file_dentry(file);
488 	struct inode *inode = d_backing_inode(dentry);
489 	enum integrity_status status = INTEGRITY_UNKNOWN;
490 	int rc = xattr_len;
491 	bool try_modsig = iint->flags & IMA_MODSIG_ALLOWED && modsig;
492 
493 	/* If not appraising a modsig, we need an xattr. */
494 	if (!(inode->i_opflags & IOP_XATTR) && !try_modsig)
495 		return INTEGRITY_UNKNOWN;
496 
497 	/* If reading the xattr failed and there's no modsig, error out. */
498 	if (rc <= 0 && !try_modsig) {
499 		if (rc && rc != -ENODATA)
500 			goto out;
501 
502 		if (iint->flags & IMA_DIGSIG_REQUIRED) {
503 			if (iint->flags & IMA_VERITY_REQUIRED)
504 				cause = "verity-signature-required";
505 			else
506 				cause = "IMA-signature-required";
507 		} else {
508 			cause = "missing-hash";
509 		}
510 
511 		status = INTEGRITY_NOLABEL;
512 		if (file->f_mode & FMODE_CREATED)
513 			iint->flags |= IMA_NEW_FILE;
514 		if ((iint->flags & IMA_NEW_FILE) &&
515 		    (!(iint->flags & IMA_DIGSIG_REQUIRED) ||
516 		     (inode->i_size == 0)))
517 			status = INTEGRITY_PASS;
518 		goto out;
519 	}
520 
521 	status = evm_verifyxattr(dentry, XATTR_NAME_IMA, xattr_value,
522 				 rc < 0 ? 0 : rc);
523 	switch (status) {
524 	case INTEGRITY_PASS:
525 	case INTEGRITY_PASS_IMMUTABLE:
526 	case INTEGRITY_UNKNOWN:
527 		break;
528 	case INTEGRITY_NOXATTRS:	/* No EVM protected xattrs. */
529 		/* It's fine not to have xattrs when using a modsig. */
530 		if (try_modsig)
531 			break;
532 		fallthrough;
533 	case INTEGRITY_NOLABEL:		/* No security.evm xattr. */
534 		cause = "missing-HMAC";
535 		goto out;
536 	case INTEGRITY_FAIL_IMMUTABLE:
537 		set_bit(IMA_DIGSIG, &iint->atomic_flags);
538 		cause = "invalid-fail-immutable";
539 		goto out;
540 	case INTEGRITY_FAIL:		/* Invalid HMAC/signature. */
541 		cause = "invalid-HMAC";
542 		goto out;
543 	default:
544 		WARN_ONCE(true, "Unexpected integrity status %d\n", status);
545 	}
546 
547 	if (xattr_value)
548 		rc = xattr_verify(func, iint, xattr_value, xattr_len, &status,
549 				  &cause);
550 
551 	/*
552 	 * If we have a modsig and either no imasig or the imasig's key isn't
553 	 * known, then try verifying the modsig.
554 	 */
555 	if (try_modsig &&
556 	    (!xattr_value || xattr_value->type == IMA_XATTR_DIGEST_NG ||
557 	     rc == -ENOKEY))
558 		rc = modsig_verify(func, modsig, &status, &cause);
559 
560 out:
561 	/*
562 	 * File signatures on some filesystems can not be properly verified.
563 	 * When such filesystems are mounted by an untrusted mounter or on a
564 	 * system not willing to accept such a risk, fail the file signature
565 	 * verification.
566 	 */
567 	if ((inode->i_sb->s_iflags & SB_I_IMA_UNVERIFIABLE_SIGNATURE) &&
568 	    ((inode->i_sb->s_iflags & SB_I_UNTRUSTED_MOUNTER) ||
569 	     (iint->flags & IMA_FAIL_UNVERIFIABLE_SIGS))) {
570 		status = INTEGRITY_FAIL;
571 		cause = "unverifiable-signature";
572 		integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, filename,
573 				    op, cause, rc, 0);
574 	} else if (status != INTEGRITY_PASS) {
575 		/* Fix mode, but don't replace file signatures. */
576 		if ((ima_appraise & IMA_APPRAISE_FIX) && !try_modsig &&
577 		    (!xattr_value ||
578 		     xattr_value->type != EVM_IMA_XATTR_DIGSIG)) {
579 			if (!ima_fix_xattr(dentry, iint))
580 				status = INTEGRITY_PASS;
581 		}
582 
583 		/*
584 		 * Permit new files with file/EVM portable signatures, but
585 		 * without data.
586 		 */
587 		if (inode->i_size == 0 && iint->flags & IMA_NEW_FILE &&
588 		    test_bit(IMA_DIGSIG, &iint->atomic_flags)) {
589 			status = INTEGRITY_PASS;
590 		}
591 
592 		integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, filename,
593 				    op, cause, rc, 0);
594 	} else {
595 		ima_cache_flags(iint, func);
596 	}
597 
598 	ima_set_cache_status(iint, func, status);
599 	return status;
600 }
601 
602 /*
603  * ima_update_xattr - update 'security.ima' hash value
604  */
605 void ima_update_xattr(struct ima_iint_cache *iint, struct file *file)
606 {
607 	struct dentry *dentry = file_dentry(file);
608 	int rc = 0;
609 
610 	/* do not collect and update hash for digital signatures */
611 	if (test_bit(IMA_DIGSIG, &iint->atomic_flags))
612 		return;
613 
614 	if ((iint->ima_file_status != INTEGRITY_PASS) &&
615 	    !(iint->flags & IMA_HASH))
616 		return;
617 
618 	rc = ima_collect_measurement(iint, file, NULL, 0, ima_hash_algo, NULL);
619 	if (rc < 0)
620 		return;
621 
622 	inode_lock(file_inode(file));
623 	ima_fix_xattr(dentry, iint);
624 	inode_unlock(file_inode(file));
625 }
626 
627 /**
628  * ima_inode_post_setattr - reflect file metadata changes
629  * @idmap:  idmap of the mount the inode was found from
630  * @dentry: pointer to the affected dentry
631  * @ia_valid: for the UID and GID status
632  *
633  * Changes to a dentry's metadata might result in needing to appraise.
634  *
635  * This function is called from notify_change(), which expects the caller
636  * to lock the inode's i_mutex.
637  */
638 static void ima_inode_post_setattr(struct mnt_idmap *idmap,
639 				   struct dentry *dentry, int ia_valid)
640 {
641 	struct inode *inode = d_backing_inode(dentry);
642 	struct ima_iint_cache *iint;
643 	int action;
644 
645 	if (!(ima_policy_flag & IMA_APPRAISE) || !S_ISREG(inode->i_mode)
646 	    || !(inode->i_opflags & IOP_XATTR))
647 		return;
648 
649 	action = ima_must_appraise(idmap, inode, MAY_ACCESS, POST_SETATTR);
650 	iint = ima_iint_find(inode);
651 	if (iint) {
652 		set_bit(IMA_CHANGE_ATTR, &iint->atomic_flags);
653 		if (!action)
654 			clear_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
655 	}
656 }
657 
658 /*
659  * ima_protect_xattr - protect 'security.ima'
660  *
661  * Ensure that not just anyone can modify or remove 'security.ima'.
662  */
663 static int ima_protect_xattr(struct dentry *dentry, const char *xattr_name,
664 			     const void *xattr_value, size_t xattr_value_len)
665 {
666 	if (strcmp(xattr_name, XATTR_NAME_IMA) == 0) {
667 		if (!capable(CAP_SYS_ADMIN))
668 			return -EPERM;
669 		return 1;
670 	}
671 	return 0;
672 }
673 
674 static void ima_reset_appraise_flags(struct inode *inode, int digsig)
675 {
676 	struct ima_iint_cache *iint;
677 
678 	if (!(ima_policy_flag & IMA_APPRAISE) || !S_ISREG(inode->i_mode))
679 		return;
680 
681 	iint = ima_iint_find(inode);
682 	if (!iint)
683 		return;
684 	iint->measured_pcrs = 0;
685 	set_bit(IMA_CHANGE_XATTR, &iint->atomic_flags);
686 	if (digsig)
687 		set_bit(IMA_DIGSIG, &iint->atomic_flags);
688 	else
689 		clear_bit(IMA_DIGSIG, &iint->atomic_flags);
690 }
691 
692 /**
693  * validate_hash_algo() - Block setxattr with unsupported hash algorithms
694  * @dentry: object of the setxattr()
695  * @xattr_value: userland supplied xattr value
696  * @xattr_value_len: length of xattr_value
697  *
698  * The xattr value is mapped to its hash algorithm, and this algorithm
699  * must be built in the kernel for the setxattr to be allowed.
700  *
701  * Emit an audit message when the algorithm is invalid.
702  *
703  * Return: 0 on success, else an error.
704  */
705 static int validate_hash_algo(struct dentry *dentry,
706 			      const struct evm_ima_xattr_data *xattr_value,
707 			      size_t xattr_value_len)
708 {
709 	char *path = NULL, *pathbuf = NULL;
710 	enum hash_algo xattr_hash_algo;
711 	const char *errmsg = "unavailable-hash-algorithm";
712 	unsigned int allowed_hashes;
713 
714 	xattr_hash_algo = ima_get_hash_algo(xattr_value, xattr_value_len);
715 
716 	allowed_hashes = atomic_read(&ima_setxattr_allowed_hash_algorithms);
717 
718 	if (allowed_hashes) {
719 		/* success if the algorithm is allowed in the ima policy */
720 		if (allowed_hashes & (1U << xattr_hash_algo))
721 			return 0;
722 
723 		/*
724 		 * We use a different audit message when the hash algorithm
725 		 * is denied by a policy rule, instead of not being built
726 		 * in the kernel image
727 		 */
728 		errmsg = "denied-hash-algorithm";
729 	} else {
730 		if (likely(xattr_hash_algo == ima_hash_algo))
731 			return 0;
732 
733 		/* allow any xattr using an algorithm built in the kernel */
734 		if (crypto_has_alg(hash_algo_name[xattr_hash_algo], 0, 0))
735 			return 0;
736 	}
737 
738 	pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
739 	if (!pathbuf)
740 		return -EACCES;
741 
742 	path = dentry_path(dentry, pathbuf, PATH_MAX);
743 
744 	integrity_audit_msg(AUDIT_INTEGRITY_DATA, d_inode(dentry), path,
745 			    "set_data", errmsg, -EACCES, 0);
746 
747 	kfree(pathbuf);
748 
749 	return -EACCES;
750 }
751 
752 static int ima_inode_setxattr(struct mnt_idmap *idmap, struct dentry *dentry,
753 			      const char *xattr_name, const void *xattr_value,
754 			      size_t xattr_value_len, int flags)
755 {
756 	const struct evm_ima_xattr_data *xvalue = xattr_value;
757 	int digsig = 0;
758 	int result;
759 	int err;
760 
761 	result = ima_protect_xattr(dentry, xattr_name, xattr_value,
762 				   xattr_value_len);
763 	if (result == 1) {
764 		if (!xattr_value_len || (xvalue->type >= IMA_XATTR_LAST))
765 			return -EINVAL;
766 
767 		err = validate_hash_algo(dentry, xvalue, xattr_value_len);
768 		if (err)
769 			return err;
770 
771 		digsig = (xvalue->type == EVM_IMA_XATTR_DIGSIG);
772 	} else if (!strcmp(xattr_name, XATTR_NAME_EVM) && xattr_value_len > 0) {
773 		digsig = (xvalue->type == EVM_XATTR_PORTABLE_DIGSIG);
774 	}
775 	if (result == 1 || evm_revalidate_status(xattr_name)) {
776 		ima_reset_appraise_flags(d_backing_inode(dentry), digsig);
777 		if (result == 1)
778 			result = 0;
779 	}
780 	return result;
781 }
782 
783 static int ima_inode_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
784 			     const char *acl_name, struct posix_acl *kacl)
785 {
786 	if (evm_revalidate_status(acl_name))
787 		ima_reset_appraise_flags(d_backing_inode(dentry), 0);
788 
789 	return 0;
790 }
791 
792 static int ima_inode_removexattr(struct mnt_idmap *idmap, struct dentry *dentry,
793 				 const char *xattr_name)
794 {
795 	int result;
796 
797 	result = ima_protect_xattr(dentry, xattr_name, NULL, 0);
798 	if (result == 1 || evm_revalidate_status(xattr_name)) {
799 		ima_reset_appraise_flags(d_backing_inode(dentry), 0);
800 		if (result == 1)
801 			result = 0;
802 	}
803 	return result;
804 }
805 
806 static int ima_inode_remove_acl(struct mnt_idmap *idmap, struct dentry *dentry,
807 				const char *acl_name)
808 {
809 	return ima_inode_set_acl(idmap, dentry, acl_name, NULL);
810 }
811 
812 static struct security_hook_list ima_appraise_hooks[] __ro_after_init = {
813 	LSM_HOOK_INIT(inode_post_setattr, ima_inode_post_setattr),
814 	LSM_HOOK_INIT(inode_setxattr, ima_inode_setxattr),
815 	LSM_HOOK_INIT(inode_set_acl, ima_inode_set_acl),
816 	LSM_HOOK_INIT(inode_removexattr, ima_inode_removexattr),
817 	LSM_HOOK_INIT(inode_remove_acl, ima_inode_remove_acl),
818 };
819 
820 void __init init_ima_appraise_lsm(const struct lsm_id *lsmid)
821 {
822 	security_add_hooks(ima_appraise_hooks, ARRAY_SIZE(ima_appraise_hooks),
823 			   lsmid);
824 }
825