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