xref: /linux/security/integrity/ima/ima_main.c (revision 01baa39cf55fbbd0078f28a215157ecd185a5176)
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 /*
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);
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 	if (pathbuf)
584 		__putname(pathbuf);
585 
586 	return result;
587 }
588 
589 /**
590  * ima_bprm_check - based on policy, collect/store measurement.
591  * @bprm: contains the linux_binprm structure
592  *
593  * The OS protects against an executable file, already open for write,
594  * from being executed in deny_write_access() and an executable file,
595  * already open for execute, from being modified in get_write_access().
596  * So we can be certain that what we verify and measure here is actually
597  * what is being executed.
598  *
599  * On success return 0.  On integrity appraisal error, assuming the file
600  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
601  */
602 static int ima_bprm_check(struct linux_binprm *bprm)
603 {
604 	struct lsm_prop prop;
605 
606 	security_current_getlsmprop_subj(&prop);
607 	return process_measurement(bprm->file, current_cred(),
608 				   &prop, NULL, 0, MAY_EXEC, BPRM_CHECK, 0,
609 				   bprm->is_check);
610 }
611 
612 /**
613  * ima_creds_check - based on policy, collect/store measurement.
614  * @bprm: contains the linux_binprm structure
615  * @file: contains the file descriptor of the binary being executed
616  *
617  * The OS protects against an executable file, already open for write,
618  * from being executed in deny_write_access() and an executable file,
619  * already open for execute, from being modified in get_write_access().
620  * So we can be certain that what we verify and measure here is actually
621  * what is being executed.
622  *
623  * The difference from ima_bprm_check() is that ima_creds_check() is invoked
624  * only after determining the final binary to be executed without interpreter,
625  * and not when searching for intermediate binaries. The reason is that since
626  * commit 56305aa9b6fab ("exec: Compute file based creds only once"), the
627  * credentials to be applied to the process are calculated only at that stage
628  * (bprm_creds_from_file security hook instead of bprm_check_security).
629  *
630  * On success return 0.  On integrity appraisal error, assuming the file
631  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
632  */
633 static int ima_creds_check(struct linux_binprm *bprm, const struct file *file)
634 {
635 	struct lsm_prop prop;
636 
637 	security_current_getlsmprop_subj(&prop);
638 	return process_measurement((struct file *)file, bprm->cred, &prop, NULL,
639 				   0, MAY_EXEC, CREDS_CHECK, 0, false);
640 }
641 
642 /**
643  * ima_bprm_creds_for_exec - collect/store/appraise measurement.
644  * @bprm: contains the linux_binprm structure
645  *
646  * Based on the IMA policy and the execveat(2) AT_EXECVE_CHECK flag, measure
647  * and appraise the integrity of a file to be executed by script interpreters.
648  * Unlike any of the other LSM hooks where the kernel enforces file integrity,
649  * enforcing file integrity is left up to the discretion of the script
650  * interpreter (userspace).
651  *
652  * On success return 0.  On integrity appraisal error, assuming the file
653  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
654  */
655 static int ima_bprm_creds_for_exec(struct linux_binprm *bprm)
656 {
657 	/*
658 	 * As security_bprm_check() is called multiple times, both
659 	 * the script and the shebang interpreter are measured, appraised,
660 	 * and audited. Limit usage of this LSM hook to just measuring,
661 	 * appraising, and auditing the indirect script execution
662 	 * (e.g. ./sh example.sh).
663 	 */
664 	if (!bprm->is_check)
665 		return 0;
666 
667 	return ima_bprm_check(bprm);
668 }
669 
670 /**
671  * ima_file_check - based on policy, collect/store measurement.
672  * @file: pointer to the file to be measured
673  * @mask: contains MAY_READ, MAY_WRITE, MAY_EXEC or MAY_APPEND
674  *
675  * Measure files based on the ima_must_measure() policy decision.
676  *
677  * On success return 0.  On integrity appraisal error, assuming the file
678  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
679  */
680 static int ima_file_check(struct file *file, int mask)
681 {
682 	struct lsm_prop prop;
683 
684 	security_current_getlsmprop_subj(&prop);
685 	return process_measurement(file, current_cred(), &prop, NULL, 0,
686 				   mask & (MAY_READ | MAY_WRITE | MAY_EXEC |
687 					   MAY_APPEND), FILE_CHECK, 0, false);
688 }
689 
690 static int __ima_inode_hash(struct inode *inode, struct file *file, char *buf,
691 			    size_t buf_size)
692 {
693 	struct ima_iint_cache *iint = NULL, tmp_iint;
694 	int rc, hash_algo;
695 
696 	if (ima_policy_flag) {
697 		iint = ima_iint_find(inode);
698 		if (iint)
699 			mutex_lock(&iint->mutex);
700 	}
701 
702 	if ((!iint || !(iint->flags & IMA_COLLECTED)) && file) {
703 		if (iint)
704 			mutex_unlock(&iint->mutex);
705 
706 		memset(&tmp_iint, 0, sizeof(tmp_iint));
707 		mutex_init(&tmp_iint.mutex);
708 
709 		rc = ima_collect_measurement(&tmp_iint, file, NULL, 0,
710 					     ima_hash_algo, NULL);
711 		if (rc < 0) {
712 			/* ima_hash could be allocated in case of failure. */
713 			if (rc != -ENOMEM)
714 				kfree(tmp_iint.ima_hash);
715 
716 			return -EOPNOTSUPP;
717 		}
718 
719 		iint = &tmp_iint;
720 		mutex_lock(&iint->mutex);
721 	}
722 
723 	if (!iint)
724 		return -EOPNOTSUPP;
725 
726 	/*
727 	 * ima_file_hash can be called when ima_collect_measurement has still
728 	 * not been called, we might not always have a hash.
729 	 */
730 	if (!iint->ima_hash || !(iint->flags & IMA_COLLECTED)) {
731 		mutex_unlock(&iint->mutex);
732 		return -EOPNOTSUPP;
733 	}
734 
735 	if (buf) {
736 		size_t copied_size;
737 
738 		copied_size = min_t(size_t, iint->ima_hash->length, buf_size);
739 		memcpy(buf, iint->ima_hash->digest, copied_size);
740 	}
741 	hash_algo = iint->ima_hash->algo;
742 	mutex_unlock(&iint->mutex);
743 
744 	if (iint == &tmp_iint)
745 		kfree(iint->ima_hash);
746 
747 	return hash_algo;
748 }
749 
750 /**
751  * ima_file_hash - return a measurement of the file
752  * @file: pointer to the file
753  * @buf: buffer in which to store the hash
754  * @buf_size: length of the buffer
755  *
756  * On success, return the hash algorithm (as defined in the enum hash_algo).
757  * If buf is not NULL, this function also outputs the hash into buf.
758  * If the hash is larger than buf_size, then only buf_size bytes will be copied.
759  * It generally just makes sense to pass a buffer capable of holding the largest
760  * possible hash: IMA_MAX_DIGEST_SIZE.
761  * The file hash returned is based on the entire file, including the appended
762  * signature.
763  *
764  * If the measurement cannot be performed, return -EOPNOTSUPP.
765  * If the parameters are incorrect, return -EINVAL.
766  */
767 int ima_file_hash(struct file *file, char *buf, size_t buf_size)
768 {
769 	if (!file)
770 		return -EINVAL;
771 
772 	return __ima_inode_hash(file_inode(file), file, buf, buf_size);
773 }
774 EXPORT_SYMBOL_GPL(ima_file_hash);
775 
776 /**
777  * ima_inode_hash - return the stored measurement if the inode has been hashed
778  * and is in the iint cache.
779  * @inode: pointer to the inode
780  * @buf: buffer in which to store the hash
781  * @buf_size: length of the buffer
782  *
783  * On success, return the hash algorithm (as defined in the enum hash_algo).
784  * If buf is not NULL, this function also outputs the hash into buf.
785  * If the hash is larger than buf_size, then only buf_size bytes will be copied.
786  * It generally just makes sense to pass a buffer capable of holding the largest
787  * possible hash: IMA_MAX_DIGEST_SIZE.
788  * The hash returned is based on the entire contents, including the appended
789  * signature.
790  *
791  * If IMA is disabled or if no measurement is available, return -EOPNOTSUPP.
792  * If the parameters are incorrect, return -EINVAL.
793  */
794 int ima_inode_hash(struct inode *inode, char *buf, size_t buf_size)
795 {
796 	if (!inode)
797 		return -EINVAL;
798 
799 	return __ima_inode_hash(inode, NULL, buf, buf_size);
800 }
801 EXPORT_SYMBOL_GPL(ima_inode_hash);
802 
803 /**
804  * ima_post_create_tmpfile - mark newly created tmpfile as new
805  * @idmap: idmap of the mount the inode was found from
806  * @inode: inode of the newly created tmpfile
807  *
808  * No measuring, appraising or auditing of newly created tmpfiles is needed.
809  * Skip calling process_measurement(), but indicate which newly, created
810  * tmpfiles are in policy.
811  */
812 static void ima_post_create_tmpfile(struct mnt_idmap *idmap,
813 				    struct inode *inode)
814 
815 {
816 	struct ima_iint_cache *iint;
817 	int must_appraise;
818 
819 	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
820 		return;
821 
822 	must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS,
823 					  FILE_CHECK);
824 	if (!must_appraise)
825 		return;
826 
827 	/* Nothing to do if we can't allocate memory */
828 	iint = ima_inode_get(inode);
829 	if (!iint)
830 		return;
831 
832 	/* needed for writing the security xattrs */
833 	set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
834 	iint->ima_file_status = INTEGRITY_PASS;
835 }
836 
837 /**
838  * ima_post_path_mknod - mark as a new inode
839  * @idmap: idmap of the mount the inode was found from
840  * @dentry: newly created dentry
841  *
842  * Mark files created via the mknodat syscall as new, so that the
843  * file data can be written later.
844  */
845 static void ima_post_path_mknod(struct mnt_idmap *idmap, struct dentry *dentry)
846 {
847 	struct ima_iint_cache *iint;
848 	struct inode *inode = dentry->d_inode;
849 	int must_appraise;
850 
851 	if (!ima_policy_flag || !S_ISREG(inode->i_mode))
852 		return;
853 
854 	must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS,
855 					  FILE_CHECK);
856 	if (!must_appraise)
857 		return;
858 
859 	/* Nothing to do if we can't allocate memory */
860 	iint = ima_inode_get(inode);
861 	if (!iint)
862 		return;
863 
864 	/* needed for re-opening empty files */
865 	iint->flags |= IMA_NEW_FILE;
866 }
867 
868 /**
869  * ima_read_file - pre-measure/appraise hook decision based on policy
870  * @file: pointer to the file to be measured/appraised/audit
871  * @read_id: caller identifier
872  * @contents: whether a subsequent call will be made to ima_post_read_file()
873  *
874  * Permit reading a file based on policy. The policy rules are written
875  * in terms of the policy identifier.  Appraising the integrity of
876  * a file requires a file descriptor.
877  *
878  * For permission return 0, otherwise return -EACCES.
879  */
880 static int ima_read_file(struct file *file, enum kernel_read_file_id read_id,
881 			 bool contents)
882 {
883 	enum ima_hooks func;
884 	struct lsm_prop prop;
885 
886 	/*
887 	 * Do devices using pre-allocated memory run the risk of the
888 	 * firmware being accessible to the device prior to the completion
889 	 * of IMA's signature verification any more than when using two
890 	 * buffers? It may be desirable to include the buffer address
891 	 * in this API and walk all the dma_map_single() mappings to check.
892 	 */
893 
894 	/*
895 	 * There will be a call made to ima_post_read_file() with
896 	 * a filled buffer, so we don't need to perform an extra
897 	 * read early here.
898 	 */
899 	if (contents)
900 		return 0;
901 
902 	/* Read entire file for all partial reads. */
903 	func = read_idmap[read_id] ?: FILE_CHECK;
904 	security_current_getlsmprop_subj(&prop);
905 	return process_measurement(file, current_cred(), &prop, NULL, 0,
906 				   MAY_READ, func, 0, false);
907 }
908 
909 const int read_idmap[READING_MAX_ID] = {
910 	[READING_FIRMWARE] = FIRMWARE_CHECK,
911 	[READING_MODULE] = MODULE_CHECK,
912 	[READING_MODULE_COMPRESSED] = MODULE_CHECK,
913 	[READING_KEXEC_IMAGE] = KEXEC_KERNEL_CHECK,
914 	[READING_KEXEC_INITRAMFS] = KEXEC_INITRAMFS_CHECK,
915 	[READING_POLICY] = POLICY_CHECK
916 };
917 
918 /**
919  * ima_post_read_file - in memory collect/appraise/audit measurement
920  * @file: pointer to the file to be measured/appraised/audit
921  * @buf: pointer to in memory file contents
922  * @size: size of in memory file contents
923  * @read_id: caller identifier
924  *
925  * Measure/appraise/audit in memory file based on policy.  Policy rules
926  * are written in terms of a policy identifier.
927  *
928  * On success return 0.  On integrity appraisal error, assuming the file
929  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
930  */
931 static int ima_post_read_file(struct file *file, char *buf, loff_t size,
932 			      enum kernel_read_file_id read_id)
933 {
934 	enum ima_hooks func;
935 	struct lsm_prop prop;
936 
937 	/* permit signed certs */
938 	if (!file && read_id == READING_X509_CERTIFICATE)
939 		return 0;
940 
941 	if (!file || !buf || size == 0) { /* should never happen */
942 		if (ima_appraise & IMA_APPRAISE_ENFORCE)
943 			return -EACCES;
944 		return 0;
945 	}
946 
947 	func = read_idmap[read_id] ?: FILE_CHECK;
948 	security_current_getlsmprop_subj(&prop);
949 	return process_measurement(file, current_cred(), &prop, buf, size,
950 				   MAY_READ, func, read_id, false);
951 }
952 
953 /**
954  * ima_load_data - appraise decision based on policy
955  * @id: kernel load data caller identifier
956  * @contents: whether the full contents will be available in a later
957  *	      call to ima_post_load_data().
958  *
959  * Callers of this LSM hook can not measure, appraise, or audit the
960  * data provided by userspace.  Enforce policy rules requiring a file
961  * signature (eg. kexec'ed kernel image).
962  *
963  * For permission return 0, otherwise return -EACCES.
964  */
965 static int ima_load_data(enum kernel_load_data_id id, bool contents)
966 {
967 	bool ima_enforce, sig_enforce;
968 
969 	ima_enforce =
970 		(ima_appraise & IMA_APPRAISE_ENFORCE) == IMA_APPRAISE_ENFORCE;
971 
972 	switch (id) {
973 	case LOADING_KEXEC_IMAGE:
974 		if (IS_ENABLED(CONFIG_KEXEC_SIG) && arch_get_secureboot()) {
975 			pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
976 			return -EACCES;
977 		}
978 
979 		if (ima_enforce && (ima_appraise & IMA_APPRAISE_KEXEC)) {
980 			pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
981 			return -EACCES;	/* INTEGRITY_UNKNOWN */
982 		}
983 		break;
984 	case LOADING_FIRMWARE:
985 		if (ima_enforce && (ima_appraise & IMA_APPRAISE_FIRMWARE) && !contents) {
986 			pr_err("Prevent firmware sysfs fallback loading.\n");
987 			return -EACCES;	/* INTEGRITY_UNKNOWN */
988 		}
989 		break;
990 	case LOADING_MODULE:
991 		sig_enforce = is_module_sig_enforced();
992 
993 		if (ima_enforce && (!sig_enforce
994 				    && (ima_appraise & IMA_APPRAISE_MODULES))) {
995 			pr_err("impossible to appraise a module without a file descriptor. sig_enforce kernel parameter might help\n");
996 			return -EACCES;	/* INTEGRITY_UNKNOWN */
997 		}
998 		break;
999 	default:
1000 		break;
1001 	}
1002 	return 0;
1003 }
1004 
1005 /**
1006  * ima_post_load_data - appraise decision based on policy
1007  * @buf: pointer to in memory file contents
1008  * @size: size of in memory file contents
1009  * @load_id: kernel load data caller identifier
1010  * @description: @load_id-specific description of contents
1011  *
1012  * Measure/appraise/audit in memory buffer based on policy.  Policy rules
1013  * are written in terms of a policy identifier.
1014  *
1015  * On success return 0.  On integrity appraisal error, assuming the file
1016  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
1017  */
1018 static int ima_post_load_data(char *buf, loff_t size,
1019 			      enum kernel_load_data_id load_id,
1020 			      char *description)
1021 {
1022 	if (load_id == LOADING_FIRMWARE) {
1023 		if ((ima_appraise & IMA_APPRAISE_FIRMWARE) &&
1024 		    (ima_appraise & IMA_APPRAISE_ENFORCE)) {
1025 			pr_err("Prevent firmware loading_store.\n");
1026 			return -EACCES; /* INTEGRITY_UNKNOWN */
1027 		}
1028 		return 0;
1029 	}
1030 
1031 	/*
1032 	 * Measure the init_module syscall buffer containing the ELF image.
1033 	 */
1034 	if (load_id == LOADING_MODULE)
1035 		ima_measure_critical_data("modules", "init_module",
1036 					  buf, size, true, NULL, 0);
1037 
1038 	return 0;
1039 }
1040 
1041 /**
1042  * process_buffer_measurement - Measure the buffer or the buffer data hash
1043  * @idmap: idmap of the mount the inode was found from
1044  * @inode: inode associated with the object being measured (NULL for KEY_CHECK)
1045  * @buf: pointer to the buffer that needs to be added to the log.
1046  * @size: size of buffer(in bytes).
1047  * @eventname: event name to be used for the buffer entry.
1048  * @func: IMA hook
1049  * @pcr: pcr to extend the measurement
1050  * @func_data: func specific data, may be NULL
1051  * @buf_hash: measure buffer data hash
1052  * @digest: buffer digest will be written to
1053  * @digest_len: buffer length
1054  *
1055  * Based on policy, either the buffer data or buffer data hash is measured
1056  *
1057  * Return: 0 if the buffer has been successfully measured, 1 if the digest
1058  * has been written to the passed location but not added to a measurement entry,
1059  * a negative value otherwise.
1060  */
1061 int process_buffer_measurement(struct mnt_idmap *idmap,
1062 			       struct inode *inode, const void *buf, int size,
1063 			       const char *eventname, enum ima_hooks func,
1064 			       int pcr, const char *func_data,
1065 			       bool buf_hash, u8 *digest, size_t digest_len)
1066 {
1067 	int ret = 0;
1068 	const char *audit_cause = "ENOMEM";
1069 	struct ima_template_entry *entry = NULL;
1070 	struct ima_iint_cache iint = {};
1071 	struct ima_event_data event_data = {.iint = &iint,
1072 					    .filename = eventname,
1073 					    .buf = buf,
1074 					    .buf_len = size};
1075 	struct ima_template_desc *template;
1076 	struct ima_max_digest_data hash;
1077 	struct ima_digest_data *hash_hdr = container_of(&hash.hdr,
1078 						struct ima_digest_data, hdr);
1079 	char digest_hash[IMA_MAX_DIGEST_SIZE];
1080 	int digest_hash_len = hash_digest_size[ima_hash_algo];
1081 	int violation = 0;
1082 	int action = 0;
1083 	struct lsm_prop prop;
1084 
1085 	if (digest && digest_len < digest_hash_len)
1086 		return -EINVAL;
1087 
1088 	if (!ima_policy_flag && !digest)
1089 		return -ENOENT;
1090 
1091 	template = ima_template_desc_buf();
1092 	if (!template) {
1093 		ret = -EINVAL;
1094 		audit_cause = "ima_template_desc_buf";
1095 		goto out;
1096 	}
1097 
1098 	/*
1099 	 * Both LSM hooks and auxiliary based buffer measurements are
1100 	 * based on policy. To avoid code duplication, differentiate
1101 	 * between the LSM hooks and auxiliary buffer measurements,
1102 	 * retrieving the policy rule information only for the LSM hook
1103 	 * buffer measurements.
1104 	 */
1105 	if (func) {
1106 		security_current_getlsmprop_subj(&prop);
1107 		action = ima_get_action(idmap, inode, current_cred(),
1108 					&prop, 0, func, &pcr, &template,
1109 					func_data, NULL);
1110 		if (!(action & IMA_MEASURE) && !digest)
1111 			return -ENOENT;
1112 	}
1113 
1114 	if (!pcr)
1115 		pcr = CONFIG_IMA_MEASURE_PCR_IDX;
1116 
1117 	iint.ima_hash = hash_hdr;
1118 	iint.ima_hash->algo = ima_hash_algo;
1119 	iint.ima_hash->length = hash_digest_size[ima_hash_algo];
1120 
1121 	ret = ima_calc_buffer_hash(buf, size, iint.ima_hash);
1122 	if (ret < 0) {
1123 		audit_cause = "hashing_error";
1124 		goto out;
1125 	}
1126 
1127 	if (buf_hash) {
1128 		memcpy(digest_hash, hash_hdr->digest, digest_hash_len);
1129 
1130 		ret = ima_calc_buffer_hash(digest_hash, digest_hash_len,
1131 					   iint.ima_hash);
1132 		if (ret < 0) {
1133 			audit_cause = "hashing_error";
1134 			goto out;
1135 		}
1136 
1137 		event_data.buf = digest_hash;
1138 		event_data.buf_len = digest_hash_len;
1139 	}
1140 
1141 	if (digest)
1142 		memcpy(digest, iint.ima_hash->digest, digest_hash_len);
1143 
1144 	if (!ima_policy_flag || (func && !(action & IMA_MEASURE)))
1145 		return 1;
1146 
1147 	ret = ima_alloc_init_template(&event_data, &entry, template);
1148 	if (ret < 0) {
1149 		audit_cause = "alloc_entry";
1150 		goto out;
1151 	}
1152 
1153 	ret = ima_store_template(entry, violation, NULL, event_data.buf, pcr);
1154 	if (ret < 0) {
1155 		audit_cause = "store_entry";
1156 		ima_free_template_entry(entry);
1157 	}
1158 
1159 out:
1160 	if (ret < 0)
1161 		integrity_audit_message(AUDIT_INTEGRITY_PCR, NULL, eventname,
1162 					func_measure_str(func),
1163 					audit_cause, ret, 0, ret);
1164 
1165 	return ret;
1166 }
1167 
1168 /**
1169  * ima_kexec_cmdline - measure kexec cmdline boot args
1170  * @kernel_fd: file descriptor of the kexec kernel being loaded
1171  * @buf: pointer to buffer
1172  * @size: size of buffer
1173  *
1174  * Buffers can only be measured, not appraised.
1175  */
1176 void ima_kexec_cmdline(int kernel_fd, const void *buf, int size)
1177 {
1178 	if (!buf || !size)
1179 		return;
1180 
1181 	CLASS(fd, f)(kernel_fd);
1182 	if (fd_empty(f))
1183 		return;
1184 
1185 	process_buffer_measurement(file_mnt_idmap(fd_file(f)), file_inode(fd_file(f)),
1186 				   buf, size, "kexec-cmdline", KEXEC_CMDLINE, 0,
1187 				   NULL, false, NULL, 0);
1188 }
1189 
1190 /**
1191  * ima_measure_critical_data - measure kernel integrity critical data
1192  * @event_label: unique event label for grouping and limiting critical data
1193  * @event_name: event name for the record in the IMA measurement list
1194  * @buf: pointer to buffer data
1195  * @buf_len: length of buffer data (in bytes)
1196  * @hash: measure buffer data hash
1197  * @digest: buffer digest will be written to
1198  * @digest_len: buffer length
1199  *
1200  * Measure data critical to the integrity of the kernel into the IMA log
1201  * and extend the pcr.  Examples of critical data could be various data
1202  * structures, policies, and states stored in kernel memory that can
1203  * impact the integrity of the system.
1204  *
1205  * Return: 0 if the buffer has been successfully measured, 1 if the digest
1206  * has been written to the passed location but not added to a measurement entry,
1207  * a negative value otherwise.
1208  */
1209 int ima_measure_critical_data(const char *event_label,
1210 			      const char *event_name,
1211 			      const void *buf, size_t buf_len,
1212 			      bool hash, u8 *digest, size_t digest_len)
1213 {
1214 	if (!event_name || !event_label || !buf || !buf_len)
1215 		return -ENOPARAM;
1216 
1217 	return process_buffer_measurement(&nop_mnt_idmap, NULL, buf, buf_len,
1218 					  event_name, CRITICAL_DATA, 0,
1219 					  event_label, hash, digest,
1220 					  digest_len);
1221 }
1222 EXPORT_SYMBOL_GPL(ima_measure_critical_data);
1223 
1224 #ifdef CONFIG_INTEGRITY_ASYMMETRIC_KEYS
1225 
1226 /**
1227  * ima_kernel_module_request - Prevent crypto-pkcs1(rsa,*) requests
1228  * @kmod_name: kernel module name
1229  *
1230  * Avoid a verification loop where verifying the signature of the modprobe
1231  * binary requires executing modprobe itself. Since the modprobe iint->mutex
1232  * is already held when the signature verification is performed, a deadlock
1233  * occurs as soon as modprobe is executed within the critical region, since
1234  * the same lock cannot be taken again.
1235  *
1236  * This happens when public_key_verify_signature(), in case of RSA algorithm,
1237  * use alg_name to store internal information in order to construct an
1238  * algorithm on the fly, but crypto_larval_lookup() will try to use alg_name
1239  * in order to load a kernel module with same name.
1240  *
1241  * Since we don't have any real "crypto-pkcs1(rsa,*)" kernel modules,
1242  * we are safe to fail such module request from crypto_larval_lookup(), and
1243  * avoid the verification loop.
1244  *
1245  * Return: Zero if it is safe to load the kernel module, -EINVAL otherwise.
1246  */
1247 static int ima_kernel_module_request(char *kmod_name)
1248 {
1249 	if (strncmp(kmod_name, "crypto-pkcs1(rsa,", 17) == 0)
1250 		return -EINVAL;
1251 
1252 	return 0;
1253 }
1254 
1255 #endif /* CONFIG_INTEGRITY_ASYMMETRIC_KEYS */
1256 
1257 static int __init init_ima(void)
1258 {
1259 	int error;
1260 
1261 	/*Note that turning IMA off is intentionally limited to kdump kernel.*/
1262 	if (ima_disabled && is_kdump_kernel()) {
1263 		pr_info("IMA functionality is disabled");
1264 		return 0;
1265 	}
1266 
1267 	ima_appraise_parse_cmdline();
1268 	ima_init_template_list();
1269 	hash_setup(CONFIG_IMA_DEFAULT_HASH);
1270 	error = ima_init();
1271 
1272 	if (error && strcmp(hash_algo_name[ima_hash_algo],
1273 			    CONFIG_IMA_DEFAULT_HASH) != 0) {
1274 		pr_info("Allocating %s failed, going to use default hash algorithm %s\n",
1275 			hash_algo_name[ima_hash_algo], CONFIG_IMA_DEFAULT_HASH);
1276 		hash_setup_done = 0;
1277 		hash_setup(CONFIG_IMA_DEFAULT_HASH);
1278 		error = ima_init();
1279 	}
1280 
1281 	if (error)
1282 		return error;
1283 
1284 	error = register_blocking_lsm_notifier(&ima_lsm_policy_notifier);
1285 	if (error)
1286 		pr_warn("Couldn't register LSM notifier, error %d\n", error);
1287 
1288 	if (!error)
1289 		ima_update_policy_flags();
1290 
1291 	return error;
1292 }
1293 
1294 static struct security_hook_list ima_hooks[] __ro_after_init = {
1295 	LSM_HOOK_INIT(bprm_check_security, ima_bprm_check),
1296 	LSM_HOOK_INIT(bprm_creds_for_exec, ima_bprm_creds_for_exec),
1297 	LSM_HOOK_INIT(bprm_creds_from_file, ima_creds_check),
1298 	LSM_HOOK_INIT(file_post_open, ima_file_check),
1299 	LSM_HOOK_INIT(inode_post_create_tmpfile, ima_post_create_tmpfile),
1300 	LSM_HOOK_INIT(file_release, ima_file_free),
1301 	LSM_HOOK_INIT(mmap_file, ima_file_mmap),
1302 	LSM_HOOK_INIT(file_mprotect, ima_file_mprotect),
1303 	LSM_HOOK_INIT(kernel_load_data, ima_load_data),
1304 	LSM_HOOK_INIT(kernel_post_load_data, ima_post_load_data),
1305 	LSM_HOOK_INIT(kernel_read_file, ima_read_file),
1306 	LSM_HOOK_INIT(kernel_post_read_file, ima_post_read_file),
1307 	LSM_HOOK_INIT(path_post_mknod, ima_post_path_mknod),
1308 #ifdef CONFIG_IMA_MEASURE_ASYMMETRIC_KEYS
1309 	LSM_HOOK_INIT(key_post_create_or_update, ima_post_key_create_or_update),
1310 #endif
1311 #ifdef CONFIG_INTEGRITY_ASYMMETRIC_KEYS
1312 	LSM_HOOK_INIT(kernel_module_request, ima_kernel_module_request),
1313 #endif
1314 	LSM_HOOK_INIT(inode_free_security_rcu, ima_inode_free_rcu),
1315 };
1316 
1317 static const struct lsm_id ima_lsmid = {
1318 	.name = "ima",
1319 	.id = LSM_ID_IMA,
1320 };
1321 
1322 static int __init init_ima_lsm(void)
1323 {
1324 	ima_iintcache_init();
1325 	security_add_hooks(ima_hooks, ARRAY_SIZE(ima_hooks), &ima_lsmid);
1326 	init_ima_appraise_lsm(&ima_lsmid);
1327 	return 0;
1328 }
1329 
1330 struct lsm_blob_sizes ima_blob_sizes __ro_after_init = {
1331 	.lbs_inode = sizeof(struct ima_iint_cache *),
1332 };
1333 
1334 DEFINE_LSM(ima) = {
1335 	.id = &ima_lsmid,
1336 	.init = init_ima_lsm,
1337 	.order = LSM_ORDER_LAST,
1338 	.blobs = &ima_blob_sizes,
1339 	/* Start IMA after the TPM is available */
1340 	.initcall_late = init_ima,
1341 };
1342