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/init.h>
9#include <linux/file.h>
10#include <linux/fs.h>
11#include <linux/xattr.h>
12#include <linux/magic.h>
13#include <linux/ima.h>
14#include <linux/evm.h>
15#include <keys/system_keyring.h>
16
17#include "ima.h"
18
19static int __init default_appraise_setup(char *str)
20{
21#ifdef CONFIG_IMA_APPRAISE_BOOTPARAM
22	bool sb_state = arch_ima_get_secureboot();
23	int appraisal_state = ima_appraise;
24
25	if (strncmp(str, "off", 3) == 0)
26		appraisal_state = 0;
27	else if (strncmp(str, "log", 3) == 0)
28		appraisal_state = IMA_APPRAISE_LOG;
29	else if (strncmp(str, "fix", 3) == 0)
30		appraisal_state = IMA_APPRAISE_FIX;
31	else if (strncmp(str, "enforce", 7) == 0)
32		appraisal_state = IMA_APPRAISE_ENFORCE;
33	else
34		pr_err("invalid \"%s\" appraise option", str);
35
36	/* If appraisal state was changed, but secure boot is enabled,
37	 * keep its default */
38	if (sb_state) {
39		if (!(appraisal_state & IMA_APPRAISE_ENFORCE))
40			pr_info("Secure boot enabled: ignoring ima_appraise=%s option",
41				str);
42	} else {
43		ima_appraise = appraisal_state;
44	}
45#endif
46	return 1;
47}
48
49__setup("ima_appraise=", default_appraise_setup);
50
51/*
52 * is_ima_appraise_enabled - return appraise status
53 *
54 * Only return enabled, if not in ima_appraise="fix" or "log" modes.
55 */
56bool is_ima_appraise_enabled(void)
57{
58	return ima_appraise & IMA_APPRAISE_ENFORCE;
59}
60
61/*
62 * ima_must_appraise - set appraise flag
63 *
64 * Return 1 to appraise or hash
65 */
66int ima_must_appraise(struct inode *inode, int mask, enum ima_hooks func)
67{
68	u32 secid;
69
70	if (!ima_appraise)
71		return 0;
72
73	security_task_getsecid(current, &secid);
74	return ima_match_policy(inode, current_cred(), secid, func, mask,
75				IMA_APPRAISE | IMA_HASH, NULL, NULL, NULL);
76}
77
78static int ima_fix_xattr(struct dentry *dentry,
79			 struct integrity_iint_cache *iint)
80{
81	int rc, offset;
82	u8 algo = iint->ima_hash->algo;
83
84	if (algo <= HASH_ALGO_SHA1) {
85		offset = 1;
86		iint->ima_hash->xattr.sha1.type = IMA_XATTR_DIGEST;
87	} else {
88		offset = 0;
89		iint->ima_hash->xattr.ng.type = IMA_XATTR_DIGEST_NG;
90		iint->ima_hash->xattr.ng.algo = algo;
91	}
92	rc = __vfs_setxattr_noperm(dentry, XATTR_NAME_IMA,
93				   &iint->ima_hash->xattr.data[offset],
94				   (sizeof(iint->ima_hash->xattr) - offset) +
95				   iint->ima_hash->length, 0);
96	return rc;
97}
98
99/* Return specific func appraised cached result */
100enum integrity_status ima_get_cache_status(struct integrity_iint_cache *iint,
101					   enum ima_hooks func)
102{
103	switch (func) {
104	case MMAP_CHECK:
105		return iint->ima_mmap_status;
106	case BPRM_CHECK:
107		return iint->ima_bprm_status;
108	case CREDS_CHECK:
109		return iint->ima_creds_status;
110	case FILE_CHECK:
111	case POST_SETATTR:
112		return iint->ima_file_status;
113	case MODULE_CHECK ... MAX_CHECK - 1:
114	default:
115		return iint->ima_read_status;
116	}
117}
118
119static void ima_set_cache_status(struct integrity_iint_cache *iint,
120				 enum ima_hooks func,
121				 enum integrity_status status)
122{
123	switch (func) {
124	case MMAP_CHECK:
125		iint->ima_mmap_status = status;
126		break;
127	case BPRM_CHECK:
128		iint->ima_bprm_status = status;
129		break;
130	case CREDS_CHECK:
131		iint->ima_creds_status = status;
132		break;
133	case FILE_CHECK:
134	case POST_SETATTR:
135		iint->ima_file_status = status;
136		break;
137	case MODULE_CHECK ... MAX_CHECK - 1:
138	default:
139		iint->ima_read_status = status;
140		break;
141	}
142}
143
144static void ima_cache_flags(struct integrity_iint_cache *iint,
145			     enum ima_hooks func)
146{
147	switch (func) {
148	case MMAP_CHECK:
149		iint->flags |= (IMA_MMAP_APPRAISED | IMA_APPRAISED);
150		break;
151	case BPRM_CHECK:
152		iint->flags |= (IMA_BPRM_APPRAISED | IMA_APPRAISED);
153		break;
154	case CREDS_CHECK:
155		iint->flags |= (IMA_CREDS_APPRAISED | IMA_APPRAISED);
156		break;
157	case FILE_CHECK:
158	case POST_SETATTR:
159		iint->flags |= (IMA_FILE_APPRAISED | IMA_APPRAISED);
160		break;
161	case MODULE_CHECK ... MAX_CHECK - 1:
162	default:
163		iint->flags |= (IMA_READ_APPRAISED | IMA_APPRAISED);
164		break;
165	}
166}
167
168enum hash_algo ima_get_hash_algo(struct evm_ima_xattr_data *xattr_value,
169				 int xattr_len)
170{
171	struct signature_v2_hdr *sig;
172	enum hash_algo ret;
173
174	if (!xattr_value || xattr_len < 2)
175		/* return default hash algo */
176		return ima_hash_algo;
177
178	switch (xattr_value->type) {
179	case EVM_IMA_XATTR_DIGSIG:
180		sig = (typeof(sig))xattr_value;
181		if (sig->version != 2 || xattr_len <= sizeof(*sig))
182			return ima_hash_algo;
183		return sig->hash_algo;
184		break;
185	case IMA_XATTR_DIGEST_NG:
186		/* first byte contains algorithm id */
187		ret = xattr_value->data[0];
188		if (ret < HASH_ALGO__LAST)
189			return ret;
190		break;
191	case IMA_XATTR_DIGEST:
192		/* this is for backward compatibility */
193		if (xattr_len == 21) {
194			unsigned int zero = 0;
195			if (!memcmp(&xattr_value->data[16], &zero, 4))
196				return HASH_ALGO_MD5;
197			else
198				return HASH_ALGO_SHA1;
199		} else if (xattr_len == 17)
200			return HASH_ALGO_MD5;
201		break;
202	}
203
204	/* return default hash algo */
205	return ima_hash_algo;
206}
207
208int ima_read_xattr(struct dentry *dentry,
209		   struct evm_ima_xattr_data **xattr_value)
210{
211	ssize_t ret;
212
213	ret = vfs_getxattr_alloc(dentry, XATTR_NAME_IMA, (char **)xattr_value,
214				 0, GFP_NOFS);
215	if (ret == -EOPNOTSUPP)
216		ret = 0;
217	return ret;
218}
219
220/*
221 * xattr_verify - verify xattr digest or signature
222 *
223 * Verify whether the hash or signature matches the file contents.
224 *
225 * Return 0 on success, error code otherwise.
226 */
227static int xattr_verify(enum ima_hooks func, struct integrity_iint_cache *iint,
228			struct evm_ima_xattr_data *xattr_value, int xattr_len,
229			enum integrity_status *status, const char **cause)
230{
231	int rc = -EINVAL, hash_start = 0;
232
233	switch (xattr_value->type) {
234	case IMA_XATTR_DIGEST_NG:
235		/* first byte contains algorithm id */
236		hash_start = 1;
237		fallthrough;
238	case IMA_XATTR_DIGEST:
239		if (iint->flags & IMA_DIGSIG_REQUIRED) {
240			*cause = "IMA-signature-required";
241			*status = INTEGRITY_FAIL;
242			break;
243		}
244		clear_bit(IMA_DIGSIG, &iint->atomic_flags);
245		if (xattr_len - sizeof(xattr_value->type) - hash_start >=
246				iint->ima_hash->length)
247			/*
248			 * xattr length may be longer. md5 hash in previous
249			 * version occupied 20 bytes in xattr, instead of 16
250			 */
251			rc = memcmp(&xattr_value->data[hash_start],
252				    iint->ima_hash->digest,
253				    iint->ima_hash->length);
254		else
255			rc = -EINVAL;
256		if (rc) {
257			*cause = "invalid-hash";
258			*status = INTEGRITY_FAIL;
259			break;
260		}
261		*status = INTEGRITY_PASS;
262		break;
263	case EVM_IMA_XATTR_DIGSIG:
264		set_bit(IMA_DIGSIG, &iint->atomic_flags);
265		rc = integrity_digsig_verify(INTEGRITY_KEYRING_IMA,
266					     (const char *)xattr_value,
267					     xattr_len,
268					     iint->ima_hash->digest,
269					     iint->ima_hash->length);
270		if (rc == -EOPNOTSUPP) {
271			*status = INTEGRITY_UNKNOWN;
272			break;
273		}
274		if (IS_ENABLED(CONFIG_INTEGRITY_PLATFORM_KEYRING) && rc &&
275		    func == KEXEC_KERNEL_CHECK)
276			rc = integrity_digsig_verify(INTEGRITY_KEYRING_PLATFORM,
277						     (const char *)xattr_value,
278						     xattr_len,
279						     iint->ima_hash->digest,
280						     iint->ima_hash->length);
281		if (rc) {
282			*cause = "invalid-signature";
283			*status = INTEGRITY_FAIL;
284		} else {
285			*status = INTEGRITY_PASS;
286		}
287		break;
288	default:
289		*status = INTEGRITY_UNKNOWN;
290		*cause = "unknown-ima-data";
291		break;
292	}
293
294	return rc;
295}
296
297/*
298 * modsig_verify - verify modsig signature
299 *
300 * Verify whether the signature matches the file contents.
301 *
302 * Return 0 on success, error code otherwise.
303 */
304static int modsig_verify(enum ima_hooks func, const struct modsig *modsig,
305			 enum integrity_status *status, const char **cause)
306{
307	int rc;
308
309	rc = integrity_modsig_verify(INTEGRITY_KEYRING_IMA, modsig);
310	if (IS_ENABLED(CONFIG_INTEGRITY_PLATFORM_KEYRING) && rc &&
311	    func == KEXEC_KERNEL_CHECK)
312		rc = integrity_modsig_verify(INTEGRITY_KEYRING_PLATFORM,
313					     modsig);
314	if (rc) {
315		*cause = "invalid-signature";
316		*status = INTEGRITY_FAIL;
317	} else {
318		*status = INTEGRITY_PASS;
319	}
320
321	return rc;
322}
323
324/*
325 * ima_check_blacklist - determine if the binary is blacklisted.
326 *
327 * Add the hash of the blacklisted binary to the measurement list, based
328 * on policy.
329 *
330 * Returns -EPERM if the hash is blacklisted.
331 */
332int ima_check_blacklist(struct integrity_iint_cache *iint,
333			const struct modsig *modsig, int pcr)
334{
335	enum hash_algo hash_algo;
336	const u8 *digest = NULL;
337	u32 digestsize = 0;
338	int rc = 0;
339
340	if (!(iint->flags & IMA_CHECK_BLACKLIST))
341		return 0;
342
343	if (iint->flags & IMA_MODSIG_ALLOWED && modsig) {
344		ima_get_modsig_digest(modsig, &hash_algo, &digest, &digestsize);
345
346		rc = is_binary_blacklisted(digest, digestsize);
347		if ((rc == -EPERM) && (iint->flags & IMA_MEASURE))
348			process_buffer_measurement(NULL, digest, digestsize,
349						   "blacklisted-hash", NONE,
350						   pcr, NULL);
351	}
352
353	return rc;
354}
355
356/*
357 * ima_appraise_measurement - appraise file measurement
358 *
359 * Call evm_verifyxattr() to verify the integrity of 'security.ima'.
360 * Assuming success, compare the xattr hash with the collected measurement.
361 *
362 * Return 0 on success, error code otherwise
363 */
364int ima_appraise_measurement(enum ima_hooks func,
365			     struct integrity_iint_cache *iint,
366			     struct file *file, const unsigned char *filename,
367			     struct evm_ima_xattr_data *xattr_value,
368			     int xattr_len, const struct modsig *modsig)
369{
370	static const char op[] = "appraise_data";
371	const char *cause = "unknown";
372	struct dentry *dentry = file_dentry(file);
373	struct inode *inode = d_backing_inode(dentry);
374	enum integrity_status status = INTEGRITY_UNKNOWN;
375	int rc = xattr_len;
376	bool try_modsig = iint->flags & IMA_MODSIG_ALLOWED && modsig;
377
378	/* If not appraising a modsig, we need an xattr. */
379	if (!(inode->i_opflags & IOP_XATTR) && !try_modsig)
380		return INTEGRITY_UNKNOWN;
381
382	/* If reading the xattr failed and there's no modsig, error out. */
383	if (rc <= 0 && !try_modsig) {
384		if (rc && rc != -ENODATA)
385			goto out;
386
387		cause = iint->flags & IMA_DIGSIG_REQUIRED ?
388				"IMA-signature-required" : "missing-hash";
389		status = INTEGRITY_NOLABEL;
390		if (file->f_mode & FMODE_CREATED)
391			iint->flags |= IMA_NEW_FILE;
392		if ((iint->flags & IMA_NEW_FILE) &&
393		    (!(iint->flags & IMA_DIGSIG_REQUIRED) ||
394		     (inode->i_size == 0)))
395			status = INTEGRITY_PASS;
396		goto out;
397	}
398
399	status = evm_verifyxattr(dentry, XATTR_NAME_IMA, xattr_value,
400				 rc < 0 ? 0 : rc, iint);
401	switch (status) {
402	case INTEGRITY_PASS:
403	case INTEGRITY_PASS_IMMUTABLE:
404	case INTEGRITY_UNKNOWN:
405		break;
406	case INTEGRITY_NOXATTRS:	/* No EVM protected xattrs. */
407		/* It's fine not to have xattrs when using a modsig. */
408		if (try_modsig)
409			break;
410		fallthrough;
411	case INTEGRITY_NOLABEL:		/* No security.evm xattr. */
412		cause = "missing-HMAC";
413		goto out;
414	case INTEGRITY_FAIL:		/* Invalid HMAC/signature. */
415		cause = "invalid-HMAC";
416		goto out;
417	default:
418		WARN_ONCE(true, "Unexpected integrity status %d\n", status);
419	}
420
421	if (xattr_value)
422		rc = xattr_verify(func, iint, xattr_value, xattr_len, &status,
423				  &cause);
424
425	/*
426	 * If we have a modsig and either no imasig or the imasig's key isn't
427	 * known, then try verifying the modsig.
428	 */
429	if (try_modsig &&
430	    (!xattr_value || xattr_value->type == IMA_XATTR_DIGEST_NG ||
431	     rc == -ENOKEY))
432		rc = modsig_verify(func, modsig, &status, &cause);
433
434out:
435	/*
436	 * File signatures on some filesystems can not be properly verified.
437	 * When such filesystems are mounted by an untrusted mounter or on a
438	 * system not willing to accept such a risk, fail the file signature
439	 * verification.
440	 */
441	if ((inode->i_sb->s_iflags & SB_I_IMA_UNVERIFIABLE_SIGNATURE) &&
442	    ((inode->i_sb->s_iflags & SB_I_UNTRUSTED_MOUNTER) ||
443	     (iint->flags & IMA_FAIL_UNVERIFIABLE_SIGS))) {
444		status = INTEGRITY_FAIL;
445		cause = "unverifiable-signature";
446		integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, filename,
447				    op, cause, rc, 0);
448	} else if (status != INTEGRITY_PASS) {
449		/* Fix mode, but don't replace file signatures. */
450		if ((ima_appraise & IMA_APPRAISE_FIX) && !try_modsig &&
451		    (!xattr_value ||
452		     xattr_value->type != EVM_IMA_XATTR_DIGSIG)) {
453			if (!ima_fix_xattr(dentry, iint))
454				status = INTEGRITY_PASS;
455		}
456
457		/* Permit new files with file signatures, but without data. */
458		if (inode->i_size == 0 && iint->flags & IMA_NEW_FILE &&
459		    xattr_value && xattr_value->type == EVM_IMA_XATTR_DIGSIG) {
460			status = INTEGRITY_PASS;
461		}
462
463		integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, filename,
464				    op, cause, rc, 0);
465	} else {
466		ima_cache_flags(iint, func);
467	}
468
469	ima_set_cache_status(iint, func, status);
470	return status;
471}
472
473/*
474 * ima_update_xattr - update 'security.ima' hash value
475 */
476void ima_update_xattr(struct integrity_iint_cache *iint, struct file *file)
477{
478	struct dentry *dentry = file_dentry(file);
479	int rc = 0;
480
481	/* do not collect and update hash for digital signatures */
482	if (test_bit(IMA_DIGSIG, &iint->atomic_flags))
483		return;
484
485	if ((iint->ima_file_status != INTEGRITY_PASS) &&
486	    !(iint->flags & IMA_HASH))
487		return;
488
489	rc = ima_collect_measurement(iint, file, NULL, 0, ima_hash_algo, NULL);
490	if (rc < 0)
491		return;
492
493	inode_lock(file_inode(file));
494	ima_fix_xattr(dentry, iint);
495	inode_unlock(file_inode(file));
496}
497
498/**
499 * ima_inode_post_setattr - reflect file metadata changes
500 * @dentry: pointer to the affected dentry
501 *
502 * Changes to a dentry's metadata might result in needing to appraise.
503 *
504 * This function is called from notify_change(), which expects the caller
505 * to lock the inode's i_mutex.
506 */
507void ima_inode_post_setattr(struct dentry *dentry)
508{
509	struct inode *inode = d_backing_inode(dentry);
510	struct integrity_iint_cache *iint;
511	int action;
512
513	if (!(ima_policy_flag & IMA_APPRAISE) || !S_ISREG(inode->i_mode)
514	    || !(inode->i_opflags & IOP_XATTR))
515		return;
516
517	action = ima_must_appraise(inode, MAY_ACCESS, POST_SETATTR);
518	if (!action)
519		__vfs_removexattr(dentry, XATTR_NAME_IMA);
520	iint = integrity_iint_find(inode);
521	if (iint) {
522		set_bit(IMA_CHANGE_ATTR, &iint->atomic_flags);
523		if (!action)
524			clear_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
525	}
526}
527
528/*
529 * ima_protect_xattr - protect 'security.ima'
530 *
531 * Ensure that not just anyone can modify or remove 'security.ima'.
532 */
533static int ima_protect_xattr(struct dentry *dentry, const char *xattr_name,
534			     const void *xattr_value, size_t xattr_value_len)
535{
536	if (strcmp(xattr_name, XATTR_NAME_IMA) == 0) {
537		if (!capable(CAP_SYS_ADMIN))
538			return -EPERM;
539		return 1;
540	}
541	return 0;
542}
543
544static void ima_reset_appraise_flags(struct inode *inode, int digsig)
545{
546	struct integrity_iint_cache *iint;
547
548	if (!(ima_policy_flag & IMA_APPRAISE) || !S_ISREG(inode->i_mode))
549		return;
550
551	iint = integrity_iint_find(inode);
552	if (!iint)
553		return;
554	iint->measured_pcrs = 0;
555	set_bit(IMA_CHANGE_XATTR, &iint->atomic_flags);
556	if (digsig)
557		set_bit(IMA_DIGSIG, &iint->atomic_flags);
558	else
559		clear_bit(IMA_DIGSIG, &iint->atomic_flags);
560}
561
562int ima_inode_setxattr(struct dentry *dentry, const char *xattr_name,
563		       const void *xattr_value, size_t xattr_value_len)
564{
565	const struct evm_ima_xattr_data *xvalue = xattr_value;
566	int result;
567
568	result = ima_protect_xattr(dentry, xattr_name, xattr_value,
569				   xattr_value_len);
570	if (result == 1) {
571		if (!xattr_value_len || (xvalue->type >= IMA_XATTR_LAST))
572			return -EINVAL;
573		ima_reset_appraise_flags(d_backing_inode(dentry),
574			xvalue->type == EVM_IMA_XATTR_DIGSIG);
575		result = 0;
576	}
577	return result;
578}
579
580int ima_inode_removexattr(struct dentry *dentry, const char *xattr_name)
581{
582	int result;
583
584	result = ima_protect_xattr(dentry, xattr_name, NULL, 0);
585	if (result == 1) {
586		ima_reset_appraise_flags(d_backing_inode(dentry), 0);
587		result = 0;
588	}
589	return result;
590}
591