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