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