xref: /linux/security/integrity/ima/ima_main.c (revision e6a901a00822659181c93c86d8bbc2a17779fddc)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Integrity Measurement Architecture
4  *
5  * Copyright (C) 2005,2006,2007,2008 IBM Corporation
6  *
7  * Authors:
8  * Reiner Sailer <sailer@watson.ibm.com>
9  * Serge Hallyn <serue@us.ibm.com>
10  * Kylene Hall <kylene@us.ibm.com>
11  * Mimi Zohar <zohar@us.ibm.com>
12  *
13  * File: ima_main.c
14  *	implements the IMA hooks: ima_bprm_check, ima_file_mmap,
15  *	and ima_file_check.
16  */
17 
18 #include <linux/module.h>
19 #include <linux/file.h>
20 #include <linux/binfmts.h>
21 #include <linux/kernel_read_file.h>
22 #include <linux/mount.h>
23 #include <linux/mman.h>
24 #include <linux/slab.h>
25 #include <linux/xattr.h>
26 #include <linux/ima.h>
27 #include <linux/fs.h>
28 #include <linux/iversion.h>
29 
30 #include "ima.h"
31 
32 #ifdef CONFIG_IMA_APPRAISE
33 int ima_appraise = IMA_APPRAISE_ENFORCE;
34 #else
35 int ima_appraise;
36 #endif
37 
38 int __ro_after_init ima_hash_algo = HASH_ALGO_SHA1;
39 static int hash_setup_done;
40 
41 static struct notifier_block ima_lsm_policy_notifier = {
42 	.notifier_call = ima_lsm_policy_change,
43 };
44 
45 static int __init hash_setup(char *str)
46 {
47 	struct ima_template_desc *template_desc = ima_template_desc_current();
48 	int i;
49 
50 	if (hash_setup_done)
51 		return 1;
52 
53 	if (strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) == 0) {
54 		if (strncmp(str, "sha1", 4) == 0) {
55 			ima_hash_algo = HASH_ALGO_SHA1;
56 		} else if (strncmp(str, "md5", 3) == 0) {
57 			ima_hash_algo = HASH_ALGO_MD5;
58 		} else {
59 			pr_err("invalid hash algorithm \"%s\" for template \"%s\"",
60 				str, IMA_TEMPLATE_IMA_NAME);
61 			return 1;
62 		}
63 		goto out;
64 	}
65 
66 	i = match_string(hash_algo_name, HASH_ALGO__LAST, str);
67 	if (i < 0) {
68 		pr_err("invalid hash algorithm \"%s\"", str);
69 		return 1;
70 	}
71 
72 	ima_hash_algo = i;
73 out:
74 	hash_setup_done = 1;
75 	return 1;
76 }
77 __setup("ima_hash=", hash_setup);
78 
79 enum hash_algo ima_get_current_hash_algo(void)
80 {
81 	return ima_hash_algo;
82 }
83 
84 /* Prevent mmap'ing a file execute that is already mmap'ed write */
85 static int mmap_violation_check(enum ima_hooks func, struct file *file,
86 				char **pathbuf, const char **pathname,
87 				char *filename)
88 {
89 	struct inode *inode;
90 	int rc = 0;
91 
92 	if ((func == MMAP_CHECK || func == MMAP_CHECK_REQPROT) &&
93 	    mapping_writably_mapped(file->f_mapping)) {
94 		rc = -ETXTBSY;
95 		inode = file_inode(file);
96 
97 		if (!*pathbuf)	/* ima_rdwr_violation possibly pre-fetched */
98 			*pathname = ima_d_path(&file->f_path, pathbuf,
99 					       filename);
100 		integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, *pathname,
101 				    "mmap_file", "mmapped_writers", rc, 0);
102 	}
103 	return rc;
104 }
105 
106 /*
107  * ima_rdwr_violation_check
108  *
109  * Only invalidate the PCR for measured files:
110  *	- Opening a file for write when already open for read,
111  *	  results in a time of measure, time of use (ToMToU) error.
112  *	- Opening a file for read when already open for write,
113  *	  could result in a file measurement error.
114  *
115  */
116 static void ima_rdwr_violation_check(struct file *file,
117 				     struct ima_iint_cache *iint,
118 				     int must_measure,
119 				     char **pathbuf,
120 				     const char **pathname,
121 				     char *filename)
122 {
123 	struct inode *inode = file_inode(file);
124 	fmode_t mode = file->f_mode;
125 	bool send_tomtou = false, send_writers = false;
126 
127 	if (mode & FMODE_WRITE) {
128 		if (atomic_read(&inode->i_readcount) && IS_IMA(inode)) {
129 			if (!iint)
130 				iint = ima_iint_find(inode);
131 			/* IMA_MEASURE is set from reader side */
132 			if (iint && test_bit(IMA_MUST_MEASURE,
133 						&iint->atomic_flags))
134 				send_tomtou = true;
135 		}
136 	} else {
137 		if (must_measure)
138 			set_bit(IMA_MUST_MEASURE, &iint->atomic_flags);
139 		if (inode_is_open_for_write(inode) && must_measure)
140 			send_writers = true;
141 	}
142 
143 	if (!send_tomtou && !send_writers)
144 		return;
145 
146 	*pathname = ima_d_path(&file->f_path, pathbuf, filename);
147 
148 	if (send_tomtou)
149 		ima_add_violation(file, *pathname, iint,
150 				  "invalid_pcr", "ToMToU");
151 	if (send_writers)
152 		ima_add_violation(file, *pathname, iint,
153 				  "invalid_pcr", "open_writers");
154 }
155 
156 static void ima_check_last_writer(struct ima_iint_cache *iint,
157 				  struct inode *inode, struct file *file)
158 {
159 	fmode_t mode = file->f_mode;
160 	bool update;
161 
162 	if (!(mode & FMODE_WRITE))
163 		return;
164 
165 	mutex_lock(&iint->mutex);
166 	if (atomic_read(&inode->i_writecount) == 1) {
167 		struct kstat stat;
168 
169 		update = test_and_clear_bit(IMA_UPDATE_XATTR,
170 					    &iint->atomic_flags);
171 		if ((iint->flags & IMA_NEW_FILE) ||
172 		    vfs_getattr_nosec(&file->f_path, &stat,
173 				      STATX_CHANGE_COOKIE,
174 				      AT_STATX_SYNC_AS_STAT) ||
175 		    !(stat.result_mask & STATX_CHANGE_COOKIE) ||
176 		    stat.change_cookie != iint->version) {
177 			iint->flags &= ~(IMA_DONE_MASK | IMA_NEW_FILE);
178 			iint->measured_pcrs = 0;
179 			if (update)
180 				ima_update_xattr(iint, file);
181 		}
182 	}
183 	mutex_unlock(&iint->mutex);
184 }
185 
186 /**
187  * ima_file_free - called on __fput()
188  * @file: pointer to file structure being freed
189  *
190  * Flag files that changed, based on i_version
191  */
192 static void ima_file_free(struct file *file)
193 {
194 	struct inode *inode = file_inode(file);
195 	struct ima_iint_cache *iint;
196 
197 	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
198 		return;
199 
200 	iint = ima_iint_find(inode);
201 	if (!iint)
202 		return;
203 
204 	ima_check_last_writer(iint, inode, file);
205 }
206 
207 static int process_measurement(struct file *file, const struct cred *cred,
208 			       u32 secid, char *buf, loff_t size, int mask,
209 			       enum ima_hooks func)
210 {
211 	struct inode *backing_inode, *inode = file_inode(file);
212 	struct ima_iint_cache *iint = NULL;
213 	struct ima_template_desc *template_desc = NULL;
214 	char *pathbuf = NULL;
215 	char filename[NAME_MAX];
216 	const char *pathname = NULL;
217 	int rc = 0, action, must_appraise = 0;
218 	int pcr = CONFIG_IMA_MEASURE_PCR_IDX;
219 	struct evm_ima_xattr_data *xattr_value = NULL;
220 	struct modsig *modsig = NULL;
221 	int xattr_len = 0;
222 	bool violation_check;
223 	enum hash_algo hash_algo;
224 	unsigned int allowed_algos = 0;
225 
226 	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
227 		return 0;
228 
229 	/* Return an IMA_MEASURE, IMA_APPRAISE, IMA_AUDIT action
230 	 * bitmask based on the appraise/audit/measurement policy.
231 	 * Included is the appraise submask.
232 	 */
233 	action = ima_get_action(file_mnt_idmap(file), inode, cred, secid,
234 				mask, func, &pcr, &template_desc, NULL,
235 				&allowed_algos);
236 	violation_check = ((func == FILE_CHECK || func == MMAP_CHECK ||
237 			    func == MMAP_CHECK_REQPROT) &&
238 			   (ima_policy_flag & IMA_MEASURE));
239 	if (!action && !violation_check)
240 		return 0;
241 
242 	must_appraise = action & IMA_APPRAISE;
243 
244 	/*  Is the appraise rule hook specific?  */
245 	if (action & IMA_FILE_APPRAISE)
246 		func = FILE_CHECK;
247 
248 	inode_lock(inode);
249 
250 	if (action) {
251 		iint = ima_inode_get(inode);
252 		if (!iint)
253 			rc = -ENOMEM;
254 	}
255 
256 	if (!rc && violation_check)
257 		ima_rdwr_violation_check(file, iint, action & IMA_MEASURE,
258 					 &pathbuf, &pathname, filename);
259 
260 	inode_unlock(inode);
261 
262 	if (rc)
263 		goto out;
264 	if (!action)
265 		goto out;
266 
267 	mutex_lock(&iint->mutex);
268 
269 	if (test_and_clear_bit(IMA_CHANGE_ATTR, &iint->atomic_flags))
270 		/* reset appraisal flags if ima_inode_post_setattr was called */
271 		iint->flags &= ~(IMA_APPRAISE | IMA_APPRAISED |
272 				 IMA_APPRAISE_SUBMASK | IMA_APPRAISED_SUBMASK |
273 				 IMA_NONACTION_FLAGS);
274 
275 	/*
276 	 * Re-evaulate the file if either the xattr has changed or the
277 	 * kernel has no way of detecting file change on the filesystem.
278 	 * (Limited to privileged mounted filesystems.)
279 	 */
280 	if (test_and_clear_bit(IMA_CHANGE_XATTR, &iint->atomic_flags) ||
281 	    ((inode->i_sb->s_iflags & SB_I_IMA_UNVERIFIABLE_SIGNATURE) &&
282 	     !(inode->i_sb->s_iflags & SB_I_UNTRUSTED_MOUNTER) &&
283 	     !(action & IMA_FAIL_UNVERIFIABLE_SIGS))) {
284 		iint->flags &= ~IMA_DONE_MASK;
285 		iint->measured_pcrs = 0;
286 	}
287 
288 	/* Detect and re-evaluate changes made to the backing file. */
289 	backing_inode = d_real_inode(file_dentry(file));
290 	if (backing_inode != inode &&
291 	    (action & IMA_DO_MASK) && (iint->flags & IMA_DONE_MASK)) {
292 		if (!IS_I_VERSION(backing_inode) ||
293 		    backing_inode->i_sb->s_dev != iint->real_dev ||
294 		    backing_inode->i_ino != iint->real_ino ||
295 		    !inode_eq_iversion(backing_inode, iint->version)) {
296 			iint->flags &= ~IMA_DONE_MASK;
297 			iint->measured_pcrs = 0;
298 		}
299 	}
300 
301 	/* Determine if already appraised/measured based on bitmask
302 	 * (IMA_MEASURE, IMA_MEASURED, IMA_XXXX_APPRAISE, IMA_XXXX_APPRAISED,
303 	 *  IMA_AUDIT, IMA_AUDITED)
304 	 */
305 	iint->flags |= action;
306 	action &= IMA_DO_MASK;
307 	action &= ~((iint->flags & (IMA_DONE_MASK ^ IMA_MEASURED)) >> 1);
308 
309 	/* If target pcr is already measured, unset IMA_MEASURE action */
310 	if ((action & IMA_MEASURE) && (iint->measured_pcrs & (0x1 << pcr)))
311 		action ^= IMA_MEASURE;
312 
313 	/* HASH sets the digital signature and update flags, nothing else */
314 	if ((action & IMA_HASH) &&
315 	    !(test_bit(IMA_DIGSIG, &iint->atomic_flags))) {
316 		xattr_len = ima_read_xattr(file_dentry(file),
317 					   &xattr_value, xattr_len);
318 		if ((xattr_value && xattr_len > 2) &&
319 		    (xattr_value->type == EVM_IMA_XATTR_DIGSIG))
320 			set_bit(IMA_DIGSIG, &iint->atomic_flags);
321 		iint->flags |= IMA_HASHED;
322 		action ^= IMA_HASH;
323 		set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
324 	}
325 
326 	/* Nothing to do, just return existing appraised status */
327 	if (!action) {
328 		if (must_appraise) {
329 			rc = mmap_violation_check(func, file, &pathbuf,
330 						  &pathname, filename);
331 			if (!rc)
332 				rc = ima_get_cache_status(iint, func);
333 		}
334 		goto out_locked;
335 	}
336 
337 	if ((action & IMA_APPRAISE_SUBMASK) ||
338 	    strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) != 0) {
339 		/* read 'security.ima' */
340 		xattr_len = ima_read_xattr(file_dentry(file),
341 					   &xattr_value, xattr_len);
342 
343 		/*
344 		 * Read the appended modsig if allowed by the policy, and allow
345 		 * an additional measurement list entry, if needed, based on the
346 		 * template format and whether the file was already measured.
347 		 */
348 		if (iint->flags & IMA_MODSIG_ALLOWED) {
349 			rc = ima_read_modsig(func, buf, size, &modsig);
350 
351 			if (!rc && ima_template_has_modsig(template_desc) &&
352 			    iint->flags & IMA_MEASURED)
353 				action |= IMA_MEASURE;
354 		}
355 	}
356 
357 	hash_algo = ima_get_hash_algo(xattr_value, xattr_len);
358 
359 	rc = ima_collect_measurement(iint, file, buf, size, hash_algo, modsig);
360 	if (rc != 0 && rc != -EBADF && rc != -EINVAL)
361 		goto out_locked;
362 
363 	if (!pathbuf)	/* ima_rdwr_violation possibly pre-fetched */
364 		pathname = ima_d_path(&file->f_path, &pathbuf, filename);
365 
366 	if (action & IMA_MEASURE)
367 		ima_store_measurement(iint, file, pathname,
368 				      xattr_value, xattr_len, modsig, pcr,
369 				      template_desc);
370 	if (rc == 0 && (action & IMA_APPRAISE_SUBMASK)) {
371 		rc = ima_check_blacklist(iint, modsig, pcr);
372 		if (rc != -EPERM) {
373 			inode_lock(inode);
374 			rc = ima_appraise_measurement(func, iint, file,
375 						      pathname, xattr_value,
376 						      xattr_len, modsig);
377 			inode_unlock(inode);
378 		}
379 		if (!rc)
380 			rc = mmap_violation_check(func, file, &pathbuf,
381 						  &pathname, filename);
382 	}
383 	if (action & IMA_AUDIT)
384 		ima_audit_measurement(iint, pathname);
385 
386 	if ((file->f_flags & O_DIRECT) && (iint->flags & IMA_PERMIT_DIRECTIO))
387 		rc = 0;
388 
389 	/* Ensure the digest was generated using an allowed algorithm */
390 	if (rc == 0 && must_appraise && allowed_algos != 0 &&
391 	    (allowed_algos & (1U << hash_algo)) == 0) {
392 		rc = -EACCES;
393 
394 		integrity_audit_msg(AUDIT_INTEGRITY_DATA, file_inode(file),
395 				    pathname, "collect_data",
396 				    "denied-hash-algorithm", rc, 0);
397 	}
398 out_locked:
399 	if ((mask & MAY_WRITE) && test_bit(IMA_DIGSIG, &iint->atomic_flags) &&
400 	     !(iint->flags & IMA_NEW_FILE))
401 		rc = -EACCES;
402 	mutex_unlock(&iint->mutex);
403 	kfree(xattr_value);
404 	ima_free_modsig(modsig);
405 out:
406 	if (pathbuf)
407 		__putname(pathbuf);
408 	if (must_appraise) {
409 		if (rc && (ima_appraise & IMA_APPRAISE_ENFORCE))
410 			return -EACCES;
411 		if (file->f_mode & FMODE_WRITE)
412 			set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
413 	}
414 	return 0;
415 }
416 
417 /**
418  * ima_file_mmap - based on policy, collect/store measurement.
419  * @file: pointer to the file to be measured (May be NULL)
420  * @reqprot: protection requested by the application
421  * @prot: protection that will be applied by the kernel
422  * @flags: operational flags
423  *
424  * Measure files being mmapped executable based on the ima_must_measure()
425  * policy decision.
426  *
427  * On success return 0.  On integrity appraisal error, assuming the file
428  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
429  */
430 static int ima_file_mmap(struct file *file, unsigned long reqprot,
431 			 unsigned long prot, unsigned long flags)
432 {
433 	u32 secid;
434 	int ret;
435 
436 	if (!file)
437 		return 0;
438 
439 	security_current_getsecid_subj(&secid);
440 
441 	if (reqprot & PROT_EXEC) {
442 		ret = process_measurement(file, current_cred(), secid, NULL,
443 					  0, MAY_EXEC, MMAP_CHECK_REQPROT);
444 		if (ret)
445 			return ret;
446 	}
447 
448 	if (prot & PROT_EXEC)
449 		return process_measurement(file, current_cred(), secid, NULL,
450 					   0, MAY_EXEC, MMAP_CHECK);
451 
452 	return 0;
453 }
454 
455 /**
456  * ima_file_mprotect - based on policy, limit mprotect change
457  * @vma: vm_area_struct protection is set to
458  * @reqprot: protection requested by the application
459  * @prot: protection that will be applied by the kernel
460  *
461  * Files can be mmap'ed read/write and later changed to execute to circumvent
462  * IMA's mmap appraisal policy rules.  Due to locking issues (mmap semaphore
463  * would be taken before i_mutex), files can not be measured or appraised at
464  * this point.  Eliminate this integrity gap by denying the mprotect
465  * PROT_EXECUTE change, if an mmap appraise policy rule exists.
466  *
467  * On mprotect change success, return 0.  On failure, return -EACESS.
468  */
469 static int ima_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot,
470 			     unsigned long prot)
471 {
472 	struct ima_template_desc *template = NULL;
473 	struct file *file;
474 	char filename[NAME_MAX];
475 	char *pathbuf = NULL;
476 	const char *pathname = NULL;
477 	struct inode *inode;
478 	int result = 0;
479 	int action;
480 	u32 secid;
481 	int pcr;
482 
483 	/* Is mprotect making an mmap'ed file executable? */
484 	if (!(ima_policy_flag & IMA_APPRAISE) || !vma->vm_file ||
485 	    !(prot & PROT_EXEC) || (vma->vm_flags & VM_EXEC))
486 		return 0;
487 
488 	security_current_getsecid_subj(&secid);
489 	inode = file_inode(vma->vm_file);
490 	action = ima_get_action(file_mnt_idmap(vma->vm_file), inode,
491 				current_cred(), secid, MAY_EXEC, MMAP_CHECK,
492 				&pcr, &template, NULL, NULL);
493 	action |= ima_get_action(file_mnt_idmap(vma->vm_file), inode,
494 				 current_cred(), secid, MAY_EXEC,
495 				 MMAP_CHECK_REQPROT, &pcr, &template, NULL,
496 				 NULL);
497 
498 	/* Is the mmap'ed file in policy? */
499 	if (!(action & (IMA_MEASURE | IMA_APPRAISE_SUBMASK)))
500 		return 0;
501 
502 	if (action & IMA_APPRAISE_SUBMASK)
503 		result = -EPERM;
504 
505 	file = vma->vm_file;
506 	pathname = ima_d_path(&file->f_path, &pathbuf, filename);
507 	integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, pathname,
508 			    "collect_data", "failed-mprotect", result, 0);
509 	if (pathbuf)
510 		__putname(pathbuf);
511 
512 	return result;
513 }
514 
515 /**
516  * ima_bprm_check - based on policy, collect/store measurement.
517  * @bprm: contains the linux_binprm structure
518  *
519  * The OS protects against an executable file, already open for write,
520  * from being executed in deny_write_access() and an executable file,
521  * already open for execute, from being modified in get_write_access().
522  * So we can be certain that what we verify and measure here is actually
523  * what is being executed.
524  *
525  * On success return 0.  On integrity appraisal error, assuming the file
526  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
527  */
528 static int ima_bprm_check(struct linux_binprm *bprm)
529 {
530 	int ret;
531 	u32 secid;
532 
533 	security_current_getsecid_subj(&secid);
534 	ret = process_measurement(bprm->file, current_cred(), secid, NULL, 0,
535 				  MAY_EXEC, BPRM_CHECK);
536 	if (ret)
537 		return ret;
538 
539 	security_cred_getsecid(bprm->cred, &secid);
540 	return process_measurement(bprm->file, bprm->cred, secid, NULL, 0,
541 				   MAY_EXEC, CREDS_CHECK);
542 }
543 
544 /**
545  * ima_file_check - based on policy, collect/store measurement.
546  * @file: pointer to the file to be measured
547  * @mask: contains MAY_READ, MAY_WRITE, MAY_EXEC or MAY_APPEND
548  *
549  * Measure files based on the ima_must_measure() policy decision.
550  *
551  * On success return 0.  On integrity appraisal error, assuming the file
552  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
553  */
554 static int ima_file_check(struct file *file, int mask)
555 {
556 	u32 secid;
557 
558 	security_current_getsecid_subj(&secid);
559 	return process_measurement(file, current_cred(), secid, NULL, 0,
560 				   mask & (MAY_READ | MAY_WRITE | MAY_EXEC |
561 					   MAY_APPEND), FILE_CHECK);
562 }
563 
564 static int __ima_inode_hash(struct inode *inode, struct file *file, char *buf,
565 			    size_t buf_size)
566 {
567 	struct ima_iint_cache *iint = NULL, tmp_iint;
568 	int rc, hash_algo;
569 
570 	if (ima_policy_flag) {
571 		iint = ima_iint_find(inode);
572 		if (iint)
573 			mutex_lock(&iint->mutex);
574 	}
575 
576 	if ((!iint || !(iint->flags & IMA_COLLECTED)) && file) {
577 		if (iint)
578 			mutex_unlock(&iint->mutex);
579 
580 		memset(&tmp_iint, 0, sizeof(tmp_iint));
581 		mutex_init(&tmp_iint.mutex);
582 
583 		rc = ima_collect_measurement(&tmp_iint, file, NULL, 0,
584 					     ima_hash_algo, NULL);
585 		if (rc < 0) {
586 			/* ima_hash could be allocated in case of failure. */
587 			if (rc != -ENOMEM)
588 				kfree(tmp_iint.ima_hash);
589 
590 			return -EOPNOTSUPP;
591 		}
592 
593 		iint = &tmp_iint;
594 		mutex_lock(&iint->mutex);
595 	}
596 
597 	if (!iint)
598 		return -EOPNOTSUPP;
599 
600 	/*
601 	 * ima_file_hash can be called when ima_collect_measurement has still
602 	 * not been called, we might not always have a hash.
603 	 */
604 	if (!iint->ima_hash || !(iint->flags & IMA_COLLECTED)) {
605 		mutex_unlock(&iint->mutex);
606 		return -EOPNOTSUPP;
607 	}
608 
609 	if (buf) {
610 		size_t copied_size;
611 
612 		copied_size = min_t(size_t, iint->ima_hash->length, buf_size);
613 		memcpy(buf, iint->ima_hash->digest, copied_size);
614 	}
615 	hash_algo = iint->ima_hash->algo;
616 	mutex_unlock(&iint->mutex);
617 
618 	if (iint == &tmp_iint)
619 		kfree(iint->ima_hash);
620 
621 	return hash_algo;
622 }
623 
624 /**
625  * ima_file_hash - return a measurement of the file
626  * @file: pointer to the file
627  * @buf: buffer in which to store the hash
628  * @buf_size: length of the buffer
629  *
630  * On success, return the hash algorithm (as defined in the enum hash_algo).
631  * If buf is not NULL, this function also outputs the hash into buf.
632  * If the hash is larger than buf_size, then only buf_size bytes will be copied.
633  * It generally just makes sense to pass a buffer capable of holding the largest
634  * possible hash: IMA_MAX_DIGEST_SIZE.
635  * The file hash returned is based on the entire file, including the appended
636  * signature.
637  *
638  * If the measurement cannot be performed, return -EOPNOTSUPP.
639  * If the parameters are incorrect, return -EINVAL.
640  */
641 int ima_file_hash(struct file *file, char *buf, size_t buf_size)
642 {
643 	if (!file)
644 		return -EINVAL;
645 
646 	return __ima_inode_hash(file_inode(file), file, buf, buf_size);
647 }
648 EXPORT_SYMBOL_GPL(ima_file_hash);
649 
650 /**
651  * ima_inode_hash - return the stored measurement if the inode has been hashed
652  * and is in the iint cache.
653  * @inode: pointer to the inode
654  * @buf: buffer in which to store the hash
655  * @buf_size: length of the buffer
656  *
657  * On success, return the hash algorithm (as defined in the enum hash_algo).
658  * If buf is not NULL, this function also outputs the hash into buf.
659  * If the hash is larger than buf_size, then only buf_size bytes will be copied.
660  * It generally just makes sense to pass a buffer capable of holding the largest
661  * possible hash: IMA_MAX_DIGEST_SIZE.
662  * The hash returned is based on the entire contents, including the appended
663  * signature.
664  *
665  * If IMA is disabled or if no measurement is available, return -EOPNOTSUPP.
666  * If the parameters are incorrect, return -EINVAL.
667  */
668 int ima_inode_hash(struct inode *inode, char *buf, size_t buf_size)
669 {
670 	if (!inode)
671 		return -EINVAL;
672 
673 	return __ima_inode_hash(inode, NULL, buf, buf_size);
674 }
675 EXPORT_SYMBOL_GPL(ima_inode_hash);
676 
677 /**
678  * ima_post_create_tmpfile - mark newly created tmpfile as new
679  * @idmap: idmap of the mount the inode was found from
680  * @inode: inode of the newly created tmpfile
681  *
682  * No measuring, appraising or auditing of newly created tmpfiles is needed.
683  * Skip calling process_measurement(), but indicate which newly, created
684  * tmpfiles are in policy.
685  */
686 static void ima_post_create_tmpfile(struct mnt_idmap *idmap,
687 				    struct inode *inode)
688 
689 {
690 	struct ima_iint_cache *iint;
691 	int must_appraise;
692 
693 	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
694 		return;
695 
696 	must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS,
697 					  FILE_CHECK);
698 	if (!must_appraise)
699 		return;
700 
701 	/* Nothing to do if we can't allocate memory */
702 	iint = ima_inode_get(inode);
703 	if (!iint)
704 		return;
705 
706 	/* needed for writing the security xattrs */
707 	set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
708 	iint->ima_file_status = INTEGRITY_PASS;
709 }
710 
711 /**
712  * ima_post_path_mknod - mark as a new inode
713  * @idmap: idmap of the mount the inode was found from
714  * @dentry: newly created dentry
715  *
716  * Mark files created via the mknodat syscall as new, so that the
717  * file data can be written later.
718  */
719 static void ima_post_path_mknod(struct mnt_idmap *idmap, struct dentry *dentry)
720 {
721 	struct ima_iint_cache *iint;
722 	struct inode *inode = dentry->d_inode;
723 	int must_appraise;
724 
725 	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
726 		return;
727 
728 	must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS,
729 					  FILE_CHECK);
730 	if (!must_appraise)
731 		return;
732 
733 	/* Nothing to do if we can't allocate memory */
734 	iint = ima_inode_get(inode);
735 	if (!iint)
736 		return;
737 
738 	/* needed for re-opening empty files */
739 	iint->flags |= IMA_NEW_FILE;
740 }
741 
742 /**
743  * ima_read_file - pre-measure/appraise hook decision based on policy
744  * @file: pointer to the file to be measured/appraised/audit
745  * @read_id: caller identifier
746  * @contents: whether a subsequent call will be made to ima_post_read_file()
747  *
748  * Permit reading a file based on policy. The policy rules are written
749  * in terms of the policy identifier.  Appraising the integrity of
750  * a file requires a file descriptor.
751  *
752  * For permission return 0, otherwise return -EACCES.
753  */
754 static int ima_read_file(struct file *file, enum kernel_read_file_id read_id,
755 			 bool contents)
756 {
757 	enum ima_hooks func;
758 	u32 secid;
759 
760 	/*
761 	 * Do devices using pre-allocated memory run the risk of the
762 	 * firmware being accessible to the device prior to the completion
763 	 * of IMA's signature verification any more than when using two
764 	 * buffers? It may be desirable to include the buffer address
765 	 * in this API and walk all the dma_map_single() mappings to check.
766 	 */
767 
768 	/*
769 	 * There will be a call made to ima_post_read_file() with
770 	 * a filled buffer, so we don't need to perform an extra
771 	 * read early here.
772 	 */
773 	if (contents)
774 		return 0;
775 
776 	/* Read entire file for all partial reads. */
777 	func = read_idmap[read_id] ?: FILE_CHECK;
778 	security_current_getsecid_subj(&secid);
779 	return process_measurement(file, current_cred(), secid, NULL,
780 				   0, MAY_READ, func);
781 }
782 
783 const int read_idmap[READING_MAX_ID] = {
784 	[READING_FIRMWARE] = FIRMWARE_CHECK,
785 	[READING_MODULE] = MODULE_CHECK,
786 	[READING_KEXEC_IMAGE] = KEXEC_KERNEL_CHECK,
787 	[READING_KEXEC_INITRAMFS] = KEXEC_INITRAMFS_CHECK,
788 	[READING_POLICY] = POLICY_CHECK
789 };
790 
791 /**
792  * ima_post_read_file - in memory collect/appraise/audit measurement
793  * @file: pointer to the file to be measured/appraised/audit
794  * @buf: pointer to in memory file contents
795  * @size: size of in memory file contents
796  * @read_id: caller identifier
797  *
798  * Measure/appraise/audit in memory file based on policy.  Policy rules
799  * are written in terms of a policy identifier.
800  *
801  * On success return 0.  On integrity appraisal error, assuming the file
802  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
803  */
804 static int ima_post_read_file(struct file *file, char *buf, loff_t size,
805 			      enum kernel_read_file_id read_id)
806 {
807 	enum ima_hooks func;
808 	u32 secid;
809 
810 	/* permit signed certs */
811 	if (!file && read_id == READING_X509_CERTIFICATE)
812 		return 0;
813 
814 	if (!file || !buf || size == 0) { /* should never happen */
815 		if (ima_appraise & IMA_APPRAISE_ENFORCE)
816 			return -EACCES;
817 		return 0;
818 	}
819 
820 	func = read_idmap[read_id] ?: FILE_CHECK;
821 	security_current_getsecid_subj(&secid);
822 	return process_measurement(file, current_cred(), secid, buf, size,
823 				   MAY_READ, func);
824 }
825 
826 /**
827  * ima_load_data - appraise decision based on policy
828  * @id: kernel load data caller identifier
829  * @contents: whether the full contents will be available in a later
830  *	      call to ima_post_load_data().
831  *
832  * Callers of this LSM hook can not measure, appraise, or audit the
833  * data provided by userspace.  Enforce policy rules requiring a file
834  * signature (eg. kexec'ed kernel image).
835  *
836  * For permission return 0, otherwise return -EACCES.
837  */
838 static int ima_load_data(enum kernel_load_data_id id, bool contents)
839 {
840 	bool ima_enforce, sig_enforce;
841 
842 	ima_enforce =
843 		(ima_appraise & IMA_APPRAISE_ENFORCE) == IMA_APPRAISE_ENFORCE;
844 
845 	switch (id) {
846 	case LOADING_KEXEC_IMAGE:
847 		if (IS_ENABLED(CONFIG_KEXEC_SIG)
848 		    && arch_ima_get_secureboot()) {
849 			pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
850 			return -EACCES;
851 		}
852 
853 		if (ima_enforce && (ima_appraise & IMA_APPRAISE_KEXEC)) {
854 			pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
855 			return -EACCES;	/* INTEGRITY_UNKNOWN */
856 		}
857 		break;
858 	case LOADING_FIRMWARE:
859 		if (ima_enforce && (ima_appraise & IMA_APPRAISE_FIRMWARE) && !contents) {
860 			pr_err("Prevent firmware sysfs fallback loading.\n");
861 			return -EACCES;	/* INTEGRITY_UNKNOWN */
862 		}
863 		break;
864 	case LOADING_MODULE:
865 		sig_enforce = is_module_sig_enforced();
866 
867 		if (ima_enforce && (!sig_enforce
868 				    && (ima_appraise & IMA_APPRAISE_MODULES))) {
869 			pr_err("impossible to appraise a module without a file descriptor. sig_enforce kernel parameter might help\n");
870 			return -EACCES;	/* INTEGRITY_UNKNOWN */
871 		}
872 		break;
873 	default:
874 		break;
875 	}
876 	return 0;
877 }
878 
879 /**
880  * ima_post_load_data - appraise decision based on policy
881  * @buf: pointer to in memory file contents
882  * @size: size of in memory file contents
883  * @load_id: kernel load data caller identifier
884  * @description: @load_id-specific description of contents
885  *
886  * Measure/appraise/audit in memory buffer based on policy.  Policy rules
887  * are written in terms of a policy identifier.
888  *
889  * On success return 0.  On integrity appraisal error, assuming the file
890  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
891  */
892 static int ima_post_load_data(char *buf, loff_t size,
893 			      enum kernel_load_data_id load_id,
894 			      char *description)
895 {
896 	if (load_id == LOADING_FIRMWARE) {
897 		if ((ima_appraise & IMA_APPRAISE_FIRMWARE) &&
898 		    (ima_appraise & IMA_APPRAISE_ENFORCE)) {
899 			pr_err("Prevent firmware loading_store.\n");
900 			return -EACCES; /* INTEGRITY_UNKNOWN */
901 		}
902 		return 0;
903 	}
904 
905 	return 0;
906 }
907 
908 /**
909  * process_buffer_measurement - Measure the buffer or the buffer data hash
910  * @idmap: idmap of the mount the inode was found from
911  * @inode: inode associated with the object being measured (NULL for KEY_CHECK)
912  * @buf: pointer to the buffer that needs to be added to the log.
913  * @size: size of buffer(in bytes).
914  * @eventname: event name to be used for the buffer entry.
915  * @func: IMA hook
916  * @pcr: pcr to extend the measurement
917  * @func_data: func specific data, may be NULL
918  * @buf_hash: measure buffer data hash
919  * @digest: buffer digest will be written to
920  * @digest_len: buffer length
921  *
922  * Based on policy, either the buffer data or buffer data hash is measured
923  *
924  * Return: 0 if the buffer has been successfully measured, 1 if the digest
925  * has been written to the passed location but not added to a measurement entry,
926  * a negative value otherwise.
927  */
928 int process_buffer_measurement(struct mnt_idmap *idmap,
929 			       struct inode *inode, const void *buf, int size,
930 			       const char *eventname, enum ima_hooks func,
931 			       int pcr, const char *func_data,
932 			       bool buf_hash, u8 *digest, size_t digest_len)
933 {
934 	int ret = 0;
935 	const char *audit_cause = "ENOMEM";
936 	struct ima_template_entry *entry = NULL;
937 	struct ima_iint_cache iint = {};
938 	struct ima_event_data event_data = {.iint = &iint,
939 					    .filename = eventname,
940 					    .buf = buf,
941 					    .buf_len = size};
942 	struct ima_template_desc *template;
943 	struct ima_max_digest_data hash;
944 	char digest_hash[IMA_MAX_DIGEST_SIZE];
945 	int digest_hash_len = hash_digest_size[ima_hash_algo];
946 	int violation = 0;
947 	int action = 0;
948 	u32 secid;
949 
950 	if (digest && digest_len < digest_hash_len)
951 		return -EINVAL;
952 
953 	if (!ima_policy_flag && !digest)
954 		return -ENOENT;
955 
956 	template = ima_template_desc_buf();
957 	if (!template) {
958 		ret = -EINVAL;
959 		audit_cause = "ima_template_desc_buf";
960 		goto out;
961 	}
962 
963 	/*
964 	 * Both LSM hooks and auxilary based buffer measurements are
965 	 * based on policy.  To avoid code duplication, differentiate
966 	 * between the LSM hooks and auxilary buffer measurements,
967 	 * retrieving the policy rule information only for the LSM hook
968 	 * buffer measurements.
969 	 */
970 	if (func) {
971 		security_current_getsecid_subj(&secid);
972 		action = ima_get_action(idmap, inode, current_cred(),
973 					secid, 0, func, &pcr, &template,
974 					func_data, NULL);
975 		if (!(action & IMA_MEASURE) && !digest)
976 			return -ENOENT;
977 	}
978 
979 	if (!pcr)
980 		pcr = CONFIG_IMA_MEASURE_PCR_IDX;
981 
982 	iint.ima_hash = &hash.hdr;
983 	iint.ima_hash->algo = ima_hash_algo;
984 	iint.ima_hash->length = hash_digest_size[ima_hash_algo];
985 
986 	ret = ima_calc_buffer_hash(buf, size, iint.ima_hash);
987 	if (ret < 0) {
988 		audit_cause = "hashing_error";
989 		goto out;
990 	}
991 
992 	if (buf_hash) {
993 		memcpy(digest_hash, hash.hdr.digest, digest_hash_len);
994 
995 		ret = ima_calc_buffer_hash(digest_hash, digest_hash_len,
996 					   iint.ima_hash);
997 		if (ret < 0) {
998 			audit_cause = "hashing_error";
999 			goto out;
1000 		}
1001 
1002 		event_data.buf = digest_hash;
1003 		event_data.buf_len = digest_hash_len;
1004 	}
1005 
1006 	if (digest)
1007 		memcpy(digest, iint.ima_hash->digest, digest_hash_len);
1008 
1009 	if (!ima_policy_flag || (func && !(action & IMA_MEASURE)))
1010 		return 1;
1011 
1012 	ret = ima_alloc_init_template(&event_data, &entry, template);
1013 	if (ret < 0) {
1014 		audit_cause = "alloc_entry";
1015 		goto out;
1016 	}
1017 
1018 	ret = ima_store_template(entry, violation, NULL, event_data.buf, pcr);
1019 	if (ret < 0) {
1020 		audit_cause = "store_entry";
1021 		ima_free_template_entry(entry);
1022 	}
1023 
1024 out:
1025 	if (ret < 0)
1026 		integrity_audit_message(AUDIT_INTEGRITY_PCR, NULL, eventname,
1027 					func_measure_str(func),
1028 					audit_cause, ret, 0, ret);
1029 
1030 	return ret;
1031 }
1032 
1033 /**
1034  * ima_kexec_cmdline - measure kexec cmdline boot args
1035  * @kernel_fd: file descriptor of the kexec kernel being loaded
1036  * @buf: pointer to buffer
1037  * @size: size of buffer
1038  *
1039  * Buffers can only be measured, not appraised.
1040  */
1041 void ima_kexec_cmdline(int kernel_fd, const void *buf, int size)
1042 {
1043 	struct fd f;
1044 
1045 	if (!buf || !size)
1046 		return;
1047 
1048 	f = fdget(kernel_fd);
1049 	if (!f.file)
1050 		return;
1051 
1052 	process_buffer_measurement(file_mnt_idmap(f.file), file_inode(f.file),
1053 				   buf, size, "kexec-cmdline", KEXEC_CMDLINE, 0,
1054 				   NULL, false, NULL, 0);
1055 	fdput(f);
1056 }
1057 
1058 /**
1059  * ima_measure_critical_data - measure kernel integrity critical data
1060  * @event_label: unique event label for grouping and limiting critical data
1061  * @event_name: event name for the record in the IMA measurement list
1062  * @buf: pointer to buffer data
1063  * @buf_len: length of buffer data (in bytes)
1064  * @hash: measure buffer data hash
1065  * @digest: buffer digest will be written to
1066  * @digest_len: buffer length
1067  *
1068  * Measure data critical to the integrity of the kernel into the IMA log
1069  * and extend the pcr.  Examples of critical data could be various data
1070  * structures, policies, and states stored in kernel memory that can
1071  * impact the integrity of the system.
1072  *
1073  * Return: 0 if the buffer has been successfully measured, 1 if the digest
1074  * has been written to the passed location but not added to a measurement entry,
1075  * a negative value otherwise.
1076  */
1077 int ima_measure_critical_data(const char *event_label,
1078 			      const char *event_name,
1079 			      const void *buf, size_t buf_len,
1080 			      bool hash, u8 *digest, size_t digest_len)
1081 {
1082 	if (!event_name || !event_label || !buf || !buf_len)
1083 		return -ENOPARAM;
1084 
1085 	return process_buffer_measurement(&nop_mnt_idmap, NULL, buf, buf_len,
1086 					  event_name, CRITICAL_DATA, 0,
1087 					  event_label, hash, digest,
1088 					  digest_len);
1089 }
1090 EXPORT_SYMBOL_GPL(ima_measure_critical_data);
1091 
1092 #ifdef CONFIG_INTEGRITY_ASYMMETRIC_KEYS
1093 
1094 /**
1095  * ima_kernel_module_request - Prevent crypto-pkcs1pad(rsa,*) requests
1096  * @kmod_name: kernel module name
1097  *
1098  * Avoid a verification loop where verifying the signature of the modprobe
1099  * binary requires executing modprobe itself. Since the modprobe iint->mutex
1100  * is already held when the signature verification is performed, a deadlock
1101  * occurs as soon as modprobe is executed within the critical region, since
1102  * the same lock cannot be taken again.
1103  *
1104  * This happens when public_key_verify_signature(), in case of RSA algorithm,
1105  * use alg_name to store internal information in order to construct an
1106  * algorithm on the fly, but crypto_larval_lookup() will try to use alg_name
1107  * in order to load a kernel module with same name.
1108  *
1109  * Since we don't have any real "crypto-pkcs1pad(rsa,*)" kernel modules,
1110  * we are safe to fail such module request from crypto_larval_lookup(), and
1111  * avoid the verification loop.
1112  *
1113  * Return: Zero if it is safe to load the kernel module, -EINVAL otherwise.
1114  */
1115 static int ima_kernel_module_request(char *kmod_name)
1116 {
1117 	if (strncmp(kmod_name, "crypto-pkcs1pad(rsa,", 20) == 0)
1118 		return -EINVAL;
1119 
1120 	return 0;
1121 }
1122 
1123 #endif /* CONFIG_INTEGRITY_ASYMMETRIC_KEYS */
1124 
1125 static int __init init_ima(void)
1126 {
1127 	int error;
1128 
1129 	ima_appraise_parse_cmdline();
1130 	ima_init_template_list();
1131 	hash_setup(CONFIG_IMA_DEFAULT_HASH);
1132 	error = ima_init();
1133 
1134 	if (error && strcmp(hash_algo_name[ima_hash_algo],
1135 			    CONFIG_IMA_DEFAULT_HASH) != 0) {
1136 		pr_info("Allocating %s failed, going to use default hash algorithm %s\n",
1137 			hash_algo_name[ima_hash_algo], CONFIG_IMA_DEFAULT_HASH);
1138 		hash_setup_done = 0;
1139 		hash_setup(CONFIG_IMA_DEFAULT_HASH);
1140 		error = ima_init();
1141 	}
1142 
1143 	if (error)
1144 		return error;
1145 
1146 	error = register_blocking_lsm_notifier(&ima_lsm_policy_notifier);
1147 	if (error)
1148 		pr_warn("Couldn't register LSM notifier, error %d\n", error);
1149 
1150 	if (!error)
1151 		ima_update_policy_flags();
1152 
1153 	return error;
1154 }
1155 
1156 static struct security_hook_list ima_hooks[] __ro_after_init = {
1157 	LSM_HOOK_INIT(bprm_check_security, ima_bprm_check),
1158 	LSM_HOOK_INIT(file_post_open, ima_file_check),
1159 	LSM_HOOK_INIT(inode_post_create_tmpfile, ima_post_create_tmpfile),
1160 	LSM_HOOK_INIT(file_release, ima_file_free),
1161 	LSM_HOOK_INIT(mmap_file, ima_file_mmap),
1162 	LSM_HOOK_INIT(file_mprotect, ima_file_mprotect),
1163 	LSM_HOOK_INIT(kernel_load_data, ima_load_data),
1164 	LSM_HOOK_INIT(kernel_post_load_data, ima_post_load_data),
1165 	LSM_HOOK_INIT(kernel_read_file, ima_read_file),
1166 	LSM_HOOK_INIT(kernel_post_read_file, ima_post_read_file),
1167 	LSM_HOOK_INIT(path_post_mknod, ima_post_path_mknod),
1168 #ifdef CONFIG_IMA_MEASURE_ASYMMETRIC_KEYS
1169 	LSM_HOOK_INIT(key_post_create_or_update, ima_post_key_create_or_update),
1170 #endif
1171 #ifdef CONFIG_INTEGRITY_ASYMMETRIC_KEYS
1172 	LSM_HOOK_INIT(kernel_module_request, ima_kernel_module_request),
1173 #endif
1174 	LSM_HOOK_INIT(inode_free_security, ima_inode_free),
1175 };
1176 
1177 static const struct lsm_id ima_lsmid = {
1178 	.name = "ima",
1179 	.id = LSM_ID_IMA,
1180 };
1181 
1182 static int __init init_ima_lsm(void)
1183 {
1184 	ima_iintcache_init();
1185 	security_add_hooks(ima_hooks, ARRAY_SIZE(ima_hooks), &ima_lsmid);
1186 	init_ima_appraise_lsm(&ima_lsmid);
1187 	return 0;
1188 }
1189 
1190 struct lsm_blob_sizes ima_blob_sizes __ro_after_init = {
1191 	.lbs_inode = sizeof(struct ima_iint_cache *),
1192 };
1193 
1194 DEFINE_LSM(ima) = {
1195 	.name = "ima",
1196 	.init = init_ima_lsm,
1197 	.order = LSM_ORDER_LAST,
1198 	.blobs = &ima_blob_sizes,
1199 };
1200 
1201 late_initcall(init_ima);	/* Start IMA after the TPM is available */
1202