1 // SPDX-License-Identifier: GPL-2.0-only
3 * Integrity Measurement Architecture
5 * Copyright (C) 2005,2006,2007,2008 IBM Corporation
14 * implements the IMA hooks: ima_bprm_check, ima_file_mmap,
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>
28 #include <linux/iversion.h>
29 #include <linux/evm.h>
33 #ifdef CONFIG_IMA_APPRAISE
34 int ima_appraise = IMA_APPRAISE_ENFORCE;
39 int __ro_after_init ima_hash_algo = HASH_ALGO_SHA1;
40 static int hash_setup_done;
42 static struct notifier_block ima_lsm_policy_notifier = {
43 .notifier_call = ima_lsm_policy_change,
46 static int __init hash_setup(char *str)
48 struct ima_template_desc *template_desc = ima_template_desc_current();
54 if (strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) == 0) {
55 if (strncmp(str, "sha1", 4) == 0) {
56 ima_hash_algo = HASH_ALGO_SHA1;
57 } else if (strncmp(str, "md5", 3) == 0) {
58 ima_hash_algo = HASH_ALGO_MD5;
60 pr_err("invalid hash algorithm \"%s\" for template \"%s\"",
61 str, IMA_TEMPLATE_IMA_NAME);
67 i = match_string(hash_algo_name, HASH_ALGO__LAST, str);
69 pr_err("invalid hash algorithm \"%s\"", str);
78 __setup("ima_hash=", hash_setup);
80 enum hash_algo ima_get_current_hash_algo(void)
85 /* Prevent mmap'ing a file execute that is already mmap'ed write */
86 static int mmap_violation_check(enum ima_hooks func, struct file *file,
87 char **pathbuf, const char **pathname,
93 if ((func == MMAP_CHECK || func == MMAP_CHECK_REQPROT) &&
94 mapping_writably_mapped(file->f_mapping)) {
96 inode = file_inode(file);
98 if (!*pathbuf) /* ima_rdwr_violation possibly pre-fetched */
99 *pathname = ima_d_path(&file->f_path, pathbuf,
101 integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, *pathname,
102 "mmap_file", "mmapped_writers", rc, 0);
108 * ima_rdwr_violation_check
110 * Only invalidate the PCR for measured files:
111 * - Opening a file for write when already open for read,
112 * results in a time of measure, time of use (ToMToU) error.
113 * - Opening a file for read when already open for write,
114 * could result in a file measurement error.
117 static void ima_rdwr_violation_check(struct file *file,
118 struct ima_iint_cache *iint,
121 const char **pathname,
124 struct inode *inode = file_inode(file);
125 fmode_t mode = file->f_mode;
126 bool send_tomtou = false, send_writers = false;
128 if (mode & FMODE_WRITE) {
129 if (atomic_read(&inode->i_readcount) && IS_IMA(inode)) {
131 iint = ima_iint_find(inode);
132 /* IMA_MEASURE is set from reader side */
133 if (iint && test_bit(IMA_MUST_MEASURE,
134 &iint->atomic_flags))
139 set_bit(IMA_MUST_MEASURE, &iint->atomic_flags);
140 if (inode_is_open_for_write(inode) && must_measure)
144 if (!send_tomtou && !send_writers)
147 *pathname = ima_d_path(&file->f_path, pathbuf, filename);
150 ima_add_violation(file, *pathname, iint,
151 "invalid_pcr", "ToMToU");
153 ima_add_violation(file, *pathname, iint,
154 "invalid_pcr", "open_writers");
157 static void ima_check_last_writer(struct ima_iint_cache *iint,
158 struct inode *inode, struct file *file)
160 fmode_t mode = file->f_mode;
163 if (!(mode & FMODE_WRITE))
166 mutex_lock(&iint->mutex);
167 if (atomic_read(&inode->i_writecount) == 1) {
170 update = test_and_clear_bit(IMA_UPDATE_XATTR,
171 &iint->atomic_flags);
172 if ((iint->flags & IMA_NEW_FILE) ||
173 vfs_getattr_nosec(&file->f_path, &stat,
175 AT_STATX_SYNC_AS_STAT) ||
176 !(stat.result_mask & STATX_CHANGE_COOKIE) ||
177 stat.change_cookie != iint->real_inode.version) {
178 iint->flags &= ~(IMA_DONE_MASK | IMA_NEW_FILE);
179 iint->measured_pcrs = 0;
181 ima_update_xattr(iint, file);
184 mutex_unlock(&iint->mutex);
188 * ima_file_free - called on __fput()
189 * @file: pointer to file structure being freed
191 * Flag files that changed, based on i_version
193 static void ima_file_free(struct file *file)
195 struct inode *inode = file_inode(file);
196 struct ima_iint_cache *iint;
198 if (!ima_policy_flag || !S_ISREG(inode->i_mode))
201 iint = ima_iint_find(inode);
205 ima_check_last_writer(iint, inode, file);
208 static int process_measurement(struct file *file, const struct cred *cred,
209 struct lsm_prop *prop, char *buf, loff_t size,
210 int mask, enum ima_hooks func)
212 struct inode *real_inode, *inode = file_inode(file);
213 struct ima_iint_cache *iint = NULL;
214 struct ima_template_desc *template_desc = NULL;
215 struct inode *metadata_inode;
216 char *pathbuf = NULL;
217 char filename[NAME_MAX];
218 const char *pathname = NULL;
219 int rc = 0, action, must_appraise = 0;
220 int pcr = CONFIG_IMA_MEASURE_PCR_IDX;
221 struct evm_ima_xattr_data *xattr_value = NULL;
222 struct modsig *modsig = NULL;
224 bool violation_check;
225 enum hash_algo hash_algo;
226 unsigned int allowed_algos = 0;
228 if (!ima_policy_flag || !S_ISREG(inode->i_mode))
231 /* Return an IMA_MEASURE, IMA_APPRAISE, IMA_AUDIT action
232 * bitmask based on the appraise/audit/measurement policy.
233 * Included is the appraise submask.
235 action = ima_get_action(file_mnt_idmap(file), inode, cred, prop,
236 mask, func, &pcr, &template_desc, NULL,
238 violation_check = ((func == FILE_CHECK || func == MMAP_CHECK ||
239 func == MMAP_CHECK_REQPROT) &&
240 (ima_policy_flag & IMA_MEASURE));
241 if (!action && !violation_check)
244 must_appraise = action & IMA_APPRAISE;
246 /* Is the appraise rule hook specific? */
247 if (action & IMA_FILE_APPRAISE)
253 iint = ima_inode_get(inode);
258 if (!rc && violation_check)
259 ima_rdwr_violation_check(file, iint, action & IMA_MEASURE,
260 &pathbuf, &pathname, filename);
269 mutex_lock(&iint->mutex);
271 if (test_and_clear_bit(IMA_CHANGE_ATTR, &iint->atomic_flags))
272 /* reset appraisal flags if ima_inode_post_setattr was called */
273 iint->flags &= ~(IMA_APPRAISE | IMA_APPRAISED |
274 IMA_APPRAISE_SUBMASK | IMA_APPRAISED_SUBMASK |
275 IMA_NONACTION_FLAGS);
278 * Re-evaulate the file if either the xattr has changed or the
279 * kernel has no way of detecting file change on the filesystem.
280 * (Limited to privileged mounted filesystems.)
282 if (test_and_clear_bit(IMA_CHANGE_XATTR, &iint->atomic_flags) ||
283 ((inode->i_sb->s_iflags & SB_I_IMA_UNVERIFIABLE_SIGNATURE) &&
284 !(inode->i_sb->s_iflags & SB_I_UNTRUSTED_MOUNTER) &&
285 !(action & IMA_FAIL_UNVERIFIABLE_SIGS))) {
286 iint->flags &= ~IMA_DONE_MASK;
287 iint->measured_pcrs = 0;
291 * On stacked filesystems, detect and re-evaluate file data and
294 real_inode = d_real_inode(file_dentry(file));
295 if (real_inode != inode &&
296 (action & IMA_DO_MASK) && (iint->flags & IMA_DONE_MASK)) {
297 if (!IS_I_VERSION(real_inode) ||
298 integrity_inode_attrs_changed(&iint->real_inode,
300 iint->flags &= ~IMA_DONE_MASK;
301 iint->measured_pcrs = 0;
305 * Reset the EVM status when metadata changed.
307 metadata_inode = d_inode(d_real(file_dentry(file),
309 if (evm_metadata_changed(inode, metadata_inode))
310 iint->flags &= ~(IMA_APPRAISED |
311 IMA_APPRAISED_SUBMASK);
314 /* Determine if already appraised/measured based on bitmask
315 * (IMA_MEASURE, IMA_MEASURED, IMA_XXXX_APPRAISE, IMA_XXXX_APPRAISED,
316 * IMA_AUDIT, IMA_AUDITED)
318 iint->flags |= action;
319 action &= IMA_DO_MASK;
320 action &= ~((iint->flags & (IMA_DONE_MASK ^ IMA_MEASURED)) >> 1);
322 /* If target pcr is already measured, unset IMA_MEASURE action */
323 if ((action & IMA_MEASURE) && (iint->measured_pcrs & (0x1 << pcr)))
324 action ^= IMA_MEASURE;
326 /* HASH sets the digital signature and update flags, nothing else */
327 if ((action & IMA_HASH) &&
328 !(test_bit(IMA_DIGSIG, &iint->atomic_flags))) {
329 xattr_len = ima_read_xattr(file_dentry(file),
330 &xattr_value, xattr_len);
331 if ((xattr_value && xattr_len > 2) &&
332 (xattr_value->type == EVM_IMA_XATTR_DIGSIG))
333 set_bit(IMA_DIGSIG, &iint->atomic_flags);
334 iint->flags |= IMA_HASHED;
336 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
339 /* Nothing to do, just return existing appraised status */
342 rc = mmap_violation_check(func, file, &pathbuf,
343 &pathname, filename);
345 rc = ima_get_cache_status(iint, func);
350 if ((action & IMA_APPRAISE_SUBMASK) ||
351 strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) != 0) {
352 /* read 'security.ima' */
353 xattr_len = ima_read_xattr(file_dentry(file),
354 &xattr_value, xattr_len);
357 * Read the appended modsig if allowed by the policy, and allow
358 * an additional measurement list entry, if needed, based on the
359 * template format and whether the file was already measured.
361 if (iint->flags & IMA_MODSIG_ALLOWED) {
362 rc = ima_read_modsig(func, buf, size, &modsig);
364 if (!rc && ima_template_has_modsig(template_desc) &&
365 iint->flags & IMA_MEASURED)
366 action |= IMA_MEASURE;
370 hash_algo = ima_get_hash_algo(xattr_value, xattr_len);
372 rc = ima_collect_measurement(iint, file, buf, size, hash_algo, modsig);
373 if (rc != 0 && rc != -EBADF && rc != -EINVAL)
376 if (!pathbuf) /* ima_rdwr_violation possibly pre-fetched */
377 pathname = ima_d_path(&file->f_path, &pathbuf, filename);
379 if (action & IMA_MEASURE)
380 ima_store_measurement(iint, file, pathname,
381 xattr_value, xattr_len, modsig, pcr,
383 if (rc == 0 && (action & IMA_APPRAISE_SUBMASK)) {
384 rc = ima_check_blacklist(iint, modsig, pcr);
387 rc = ima_appraise_measurement(func, iint, file,
388 pathname, xattr_value,
393 rc = mmap_violation_check(func, file, &pathbuf,
394 &pathname, filename);
396 if (action & IMA_AUDIT)
397 ima_audit_measurement(iint, pathname);
399 if ((file->f_flags & O_DIRECT) && (iint->flags & IMA_PERMIT_DIRECTIO))
402 /* Ensure the digest was generated using an allowed algorithm */
403 if (rc == 0 && must_appraise && allowed_algos != 0 &&
404 (allowed_algos & (1U << hash_algo)) == 0) {
407 integrity_audit_msg(AUDIT_INTEGRITY_DATA, file_inode(file),
408 pathname, "collect_data",
409 "denied-hash-algorithm", rc, 0);
412 if ((mask & MAY_WRITE) && test_bit(IMA_DIGSIG, &iint->atomic_flags) &&
413 !(iint->flags & IMA_NEW_FILE))
415 mutex_unlock(&iint->mutex);
417 ima_free_modsig(modsig);
422 if (rc && (ima_appraise & IMA_APPRAISE_ENFORCE))
424 if (file->f_mode & FMODE_WRITE)
425 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
431 * ima_file_mmap - based on policy, collect/store measurement.
432 * @file: pointer to the file to be measured (May be NULL)
433 * @reqprot: protection requested by the application
434 * @prot: protection that will be applied by the kernel
435 * @flags: operational flags
437 * Measure files being mmapped executable based on the ima_must_measure()
440 * On success return 0. On integrity appraisal error, assuming the file
441 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
443 static int ima_file_mmap(struct file *file, unsigned long reqprot,
444 unsigned long prot, unsigned long flags)
446 struct lsm_prop prop;
452 security_current_getlsmprop_subj(&prop);
454 if (reqprot & PROT_EXEC) {
455 ret = process_measurement(file, current_cred(), &prop, NULL,
456 0, MAY_EXEC, MMAP_CHECK_REQPROT);
461 if (prot & PROT_EXEC)
462 return process_measurement(file, current_cred(), &prop, NULL,
463 0, MAY_EXEC, MMAP_CHECK);
469 * ima_file_mprotect - based on policy, limit mprotect change
470 * @vma: vm_area_struct protection is set to
471 * @reqprot: protection requested by the application
472 * @prot: protection that will be applied by the kernel
474 * Files can be mmap'ed read/write and later changed to execute to circumvent
475 * IMA's mmap appraisal policy rules. Due to locking issues (mmap semaphore
476 * would be taken before i_mutex), files can not be measured or appraised at
477 * this point. Eliminate this integrity gap by denying the mprotect
478 * PROT_EXECUTE change, if an mmap appraise policy rule exists.
480 * On mprotect change success, return 0. On failure, return -EACESS.
482 static int ima_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot,
485 struct ima_template_desc *template = NULL;
487 char filename[NAME_MAX];
488 char *pathbuf = NULL;
489 const char *pathname = NULL;
491 struct lsm_prop prop;
496 /* Is mprotect making an mmap'ed file executable? */
497 if (!(ima_policy_flag & IMA_APPRAISE) || !vma->vm_file ||
498 !(prot & PROT_EXEC) || (vma->vm_flags & VM_EXEC))
501 security_current_getlsmprop_subj(&prop);
502 inode = file_inode(vma->vm_file);
503 action = ima_get_action(file_mnt_idmap(vma->vm_file), inode,
504 current_cred(), &prop, MAY_EXEC, MMAP_CHECK,
505 &pcr, &template, NULL, NULL);
506 action |= ima_get_action(file_mnt_idmap(vma->vm_file), inode,
507 current_cred(), &prop, MAY_EXEC,
508 MMAP_CHECK_REQPROT, &pcr, &template, NULL,
511 /* Is the mmap'ed file in policy? */
512 if (!(action & (IMA_MEASURE | IMA_APPRAISE_SUBMASK)))
515 if (action & IMA_APPRAISE_SUBMASK)
519 pathname = ima_d_path(&file->f_path, &pathbuf, filename);
520 integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, pathname,
521 "collect_data", "failed-mprotect", result, 0);
529 * ima_bprm_check - based on policy, collect/store measurement.
530 * @bprm: contains the linux_binprm structure
532 * The OS protects against an executable file, already open for write,
533 * from being executed in deny_write_access() and an executable file,
534 * already open for execute, from being modified in get_write_access().
535 * So we can be certain that what we verify and measure here is actually
536 * what is being executed.
538 * On success return 0. On integrity appraisal error, assuming the file
539 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
541 static int ima_bprm_check(struct linux_binprm *bprm)
544 struct lsm_prop prop;
546 security_current_getlsmprop_subj(&prop);
547 ret = process_measurement(bprm->file, current_cred(),
548 &prop, NULL, 0, MAY_EXEC, BPRM_CHECK);
552 security_cred_getlsmprop(bprm->cred, &prop);
553 return process_measurement(bprm->file, bprm->cred, &prop, NULL, 0,
554 MAY_EXEC, CREDS_CHECK);
558 * ima_bprm_creds_for_exec - collect/store/appraise measurement.
559 * @bprm: contains the linux_binprm structure
561 * Based on the IMA policy and the execveat(2) AT_EXECVE_CHECK flag, measure
562 * and appraise the integrity of a file to be executed by script interpreters.
563 * Unlike any of the other LSM hooks where the kernel enforces file integrity,
564 * enforcing file integrity is left up to the discretion of the script
565 * interpreter (userspace).
567 * On success return 0. On integrity appraisal error, assuming the file
568 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
570 static int ima_bprm_creds_for_exec(struct linux_binprm *bprm)
573 * As security_bprm_check() is called multiple times, both
574 * the script and the shebang interpreter are measured, appraised,
575 * and audited. Limit usage of this LSM hook to just measuring,
576 * appraising, and auditing the indirect script execution
577 * (e.g. ./sh example.sh).
582 return ima_bprm_check(bprm);
586 * ima_file_check - based on policy, collect/store measurement.
587 * @file: pointer to the file to be measured
588 * @mask: contains MAY_READ, MAY_WRITE, MAY_EXEC or MAY_APPEND
590 * Measure files based on the ima_must_measure() policy decision.
592 * On success return 0. On integrity appraisal error, assuming the file
593 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
595 static int ima_file_check(struct file *file, int mask)
597 struct lsm_prop prop;
599 security_current_getlsmprop_subj(&prop);
600 return process_measurement(file, current_cred(), &prop, NULL, 0,
601 mask & (MAY_READ | MAY_WRITE | MAY_EXEC |
602 MAY_APPEND), FILE_CHECK);
605 static int __ima_inode_hash(struct inode *inode, struct file *file, char *buf,
608 struct ima_iint_cache *iint = NULL, tmp_iint;
611 if (ima_policy_flag) {
612 iint = ima_iint_find(inode);
614 mutex_lock(&iint->mutex);
617 if ((!iint || !(iint->flags & IMA_COLLECTED)) && file) {
619 mutex_unlock(&iint->mutex);
621 memset(&tmp_iint, 0, sizeof(tmp_iint));
622 mutex_init(&tmp_iint.mutex);
624 rc = ima_collect_measurement(&tmp_iint, file, NULL, 0,
625 ima_hash_algo, NULL);
627 /* ima_hash could be allocated in case of failure. */
629 kfree(tmp_iint.ima_hash);
635 mutex_lock(&iint->mutex);
642 * ima_file_hash can be called when ima_collect_measurement has still
643 * not been called, we might not always have a hash.
645 if (!iint->ima_hash || !(iint->flags & IMA_COLLECTED)) {
646 mutex_unlock(&iint->mutex);
653 copied_size = min_t(size_t, iint->ima_hash->length, buf_size);
654 memcpy(buf, iint->ima_hash->digest, copied_size);
656 hash_algo = iint->ima_hash->algo;
657 mutex_unlock(&iint->mutex);
659 if (iint == &tmp_iint)
660 kfree(iint->ima_hash);
666 * ima_file_hash - return a measurement of the file
667 * @file: pointer to the file
668 * @buf: buffer in which to store the hash
669 * @buf_size: length of the buffer
671 * On success, return the hash algorithm (as defined in the enum hash_algo).
672 * If buf is not NULL, this function also outputs the hash into buf.
673 * If the hash is larger than buf_size, then only buf_size bytes will be copied.
674 * It generally just makes sense to pass a buffer capable of holding the largest
675 * possible hash: IMA_MAX_DIGEST_SIZE.
676 * The file hash returned is based on the entire file, including the appended
679 * If the measurement cannot be performed, return -EOPNOTSUPP.
680 * If the parameters are incorrect, return -EINVAL.
682 int ima_file_hash(struct file *file, char *buf, size_t buf_size)
687 return __ima_inode_hash(file_inode(file), file, buf, buf_size);
689 EXPORT_SYMBOL_GPL(ima_file_hash);
692 * ima_inode_hash - return the stored measurement if the inode has been hashed
693 * and is in the iint cache.
694 * @inode: pointer to the inode
695 * @buf: buffer in which to store the hash
696 * @buf_size: length of the buffer
698 * On success, return the hash algorithm (as defined in the enum hash_algo).
699 * If buf is not NULL, this function also outputs the hash into buf.
700 * If the hash is larger than buf_size, then only buf_size bytes will be copied.
701 * It generally just makes sense to pass a buffer capable of holding the largest
702 * possible hash: IMA_MAX_DIGEST_SIZE.
703 * The hash returned is based on the entire contents, including the appended
706 * If IMA is disabled or if no measurement is available, return -EOPNOTSUPP.
707 * If the parameters are incorrect, return -EINVAL.
709 int ima_inode_hash(struct inode *inode, char *buf, size_t buf_size)
714 return __ima_inode_hash(inode, NULL, buf, buf_size);
716 EXPORT_SYMBOL_GPL(ima_inode_hash);
719 * ima_post_create_tmpfile - mark newly created tmpfile as new
720 * @idmap: idmap of the mount the inode was found from
721 * @inode: inode of the newly created tmpfile
723 * No measuring, appraising or auditing of newly created tmpfiles is needed.
724 * Skip calling process_measurement(), but indicate which newly, created
725 * tmpfiles are in policy.
727 static void ima_post_create_tmpfile(struct mnt_idmap *idmap,
731 struct ima_iint_cache *iint;
734 if (!ima_policy_flag || !S_ISREG(inode->i_mode))
737 must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS,
742 /* Nothing to do if we can't allocate memory */
743 iint = ima_inode_get(inode);
747 /* needed for writing the security xattrs */
748 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
749 iint->ima_file_status = INTEGRITY_PASS;
753 * ima_post_path_mknod - mark as a new inode
754 * @idmap: idmap of the mount the inode was found from
755 * @dentry: newly created dentry
757 * Mark files created via the mknodat syscall as new, so that the
758 * file data can be written later.
760 static void ima_post_path_mknod(struct mnt_idmap *idmap, struct dentry *dentry)
762 struct ima_iint_cache *iint;
763 struct inode *inode = dentry->d_inode;
766 if (!ima_policy_flag || !S_ISREG(inode->i_mode))
769 must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS,
774 /* Nothing to do if we can't allocate memory */
775 iint = ima_inode_get(inode);
779 /* needed for re-opening empty files */
780 iint->flags |= IMA_NEW_FILE;
784 * ima_read_file - pre-measure/appraise hook decision based on policy
785 * @file: pointer to the file to be measured/appraised/audit
786 * @read_id: caller identifier
787 * @contents: whether a subsequent call will be made to ima_post_read_file()
789 * Permit reading a file based on policy. The policy rules are written
790 * in terms of the policy identifier. Appraising the integrity of
791 * a file requires a file descriptor.
793 * For permission return 0, otherwise return -EACCES.
795 static int ima_read_file(struct file *file, enum kernel_read_file_id read_id,
799 struct lsm_prop prop;
802 * Do devices using pre-allocated memory run the risk of the
803 * firmware being accessible to the device prior to the completion
804 * of IMA's signature verification any more than when using two
805 * buffers? It may be desirable to include the buffer address
806 * in this API and walk all the dma_map_single() mappings to check.
810 * There will be a call made to ima_post_read_file() with
811 * a filled buffer, so we don't need to perform an extra
817 /* Read entire file for all partial reads. */
818 func = read_idmap[read_id] ?: FILE_CHECK;
819 security_current_getlsmprop_subj(&prop);
820 return process_measurement(file, current_cred(), &prop, NULL, 0,
824 const int read_idmap[READING_MAX_ID] = {
825 [READING_FIRMWARE] = FIRMWARE_CHECK,
826 [READING_MODULE] = MODULE_CHECK,
827 [READING_KEXEC_IMAGE] = KEXEC_KERNEL_CHECK,
828 [READING_KEXEC_INITRAMFS] = KEXEC_INITRAMFS_CHECK,
829 [READING_POLICY] = POLICY_CHECK
833 * ima_post_read_file - in memory collect/appraise/audit measurement
834 * @file: pointer to the file to be measured/appraised/audit
835 * @buf: pointer to in memory file contents
836 * @size: size of in memory file contents
837 * @read_id: caller identifier
839 * Measure/appraise/audit in memory file based on policy. Policy rules
840 * are written in terms of a policy identifier.
842 * On success return 0. On integrity appraisal error, assuming the file
843 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
845 static int ima_post_read_file(struct file *file, char *buf, loff_t size,
846 enum kernel_read_file_id read_id)
849 struct lsm_prop prop;
851 /* permit signed certs */
852 if (!file && read_id == READING_X509_CERTIFICATE)
855 if (!file || !buf || size == 0) { /* should never happen */
856 if (ima_appraise & IMA_APPRAISE_ENFORCE)
861 func = read_idmap[read_id] ?: FILE_CHECK;
862 security_current_getlsmprop_subj(&prop);
863 return process_measurement(file, current_cred(), &prop, buf, size,
868 * ima_load_data - appraise decision based on policy
869 * @id: kernel load data caller identifier
870 * @contents: whether the full contents will be available in a later
871 * call to ima_post_load_data().
873 * Callers of this LSM hook can not measure, appraise, or audit the
874 * data provided by userspace. Enforce policy rules requiring a file
875 * signature (eg. kexec'ed kernel image).
877 * For permission return 0, otherwise return -EACCES.
879 static int ima_load_data(enum kernel_load_data_id id, bool contents)
881 bool ima_enforce, sig_enforce;
884 (ima_appraise & IMA_APPRAISE_ENFORCE) == IMA_APPRAISE_ENFORCE;
887 case LOADING_KEXEC_IMAGE:
888 if (IS_ENABLED(CONFIG_KEXEC_SIG)
889 && arch_ima_get_secureboot()) {
890 pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
894 if (ima_enforce && (ima_appraise & IMA_APPRAISE_KEXEC)) {
895 pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
896 return -EACCES; /* INTEGRITY_UNKNOWN */
899 case LOADING_FIRMWARE:
900 if (ima_enforce && (ima_appraise & IMA_APPRAISE_FIRMWARE) && !contents) {
901 pr_err("Prevent firmware sysfs fallback loading.\n");
902 return -EACCES; /* INTEGRITY_UNKNOWN */
906 sig_enforce = is_module_sig_enforced();
908 if (ima_enforce && (!sig_enforce
909 && (ima_appraise & IMA_APPRAISE_MODULES))) {
910 pr_err("impossible to appraise a module without a file descriptor. sig_enforce kernel parameter might help\n");
911 return -EACCES; /* INTEGRITY_UNKNOWN */
921 * ima_post_load_data - appraise decision based on policy
922 * @buf: pointer to in memory file contents
923 * @size: size of in memory file contents
924 * @load_id: kernel load data caller identifier
925 * @description: @load_id-specific description of contents
927 * Measure/appraise/audit in memory buffer based on policy. Policy rules
928 * are written in terms of a policy identifier.
930 * On success return 0. On integrity appraisal error, assuming the file
931 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
933 static int ima_post_load_data(char *buf, loff_t size,
934 enum kernel_load_data_id load_id,
937 if (load_id == LOADING_FIRMWARE) {
938 if ((ima_appraise & IMA_APPRAISE_FIRMWARE) &&
939 (ima_appraise & IMA_APPRAISE_ENFORCE)) {
940 pr_err("Prevent firmware loading_store.\n");
941 return -EACCES; /* INTEGRITY_UNKNOWN */
947 * Measure the init_module syscall buffer containing the ELF image.
949 if (load_id == LOADING_MODULE)
950 ima_measure_critical_data("modules", "init_module",
951 buf, size, true, NULL, 0);
957 * process_buffer_measurement - Measure the buffer or the buffer data hash
958 * @idmap: idmap of the mount the inode was found from
959 * @inode: inode associated with the object being measured (NULL for KEY_CHECK)
960 * @buf: pointer to the buffer that needs to be added to the log.
961 * @size: size of buffer(in bytes).
962 * @eventname: event name to be used for the buffer entry.
964 * @pcr: pcr to extend the measurement
965 * @func_data: func specific data, may be NULL
966 * @buf_hash: measure buffer data hash
967 * @digest: buffer digest will be written to
968 * @digest_len: buffer length
970 * Based on policy, either the buffer data or buffer data hash is measured
972 * Return: 0 if the buffer has been successfully measured, 1 if the digest
973 * has been written to the passed location but not added to a measurement entry,
974 * a negative value otherwise.
976 int process_buffer_measurement(struct mnt_idmap *idmap,
977 struct inode *inode, const void *buf, int size,
978 const char *eventname, enum ima_hooks func,
979 int pcr, const char *func_data,
980 bool buf_hash, u8 *digest, size_t digest_len)
983 const char *audit_cause = "ENOMEM";
984 struct ima_template_entry *entry = NULL;
985 struct ima_iint_cache iint = {};
986 struct ima_event_data event_data = {.iint = &iint,
987 .filename = eventname,
990 struct ima_template_desc *template;
991 struct ima_max_digest_data hash;
992 struct ima_digest_data *hash_hdr = container_of(&hash.hdr,
993 struct ima_digest_data, hdr);
994 char digest_hash[IMA_MAX_DIGEST_SIZE];
995 int digest_hash_len = hash_digest_size[ima_hash_algo];
998 struct lsm_prop prop;
1000 if (digest && digest_len < digest_hash_len)
1003 if (!ima_policy_flag && !digest)
1006 template = ima_template_desc_buf();
1009 audit_cause = "ima_template_desc_buf";
1014 * Both LSM hooks and auxilary based buffer measurements are
1015 * based on policy. To avoid code duplication, differentiate
1016 * between the LSM hooks and auxilary buffer measurements,
1017 * retrieving the policy rule information only for the LSM hook
1018 * buffer measurements.
1021 security_current_getlsmprop_subj(&prop);
1022 action = ima_get_action(idmap, inode, current_cred(),
1023 &prop, 0, func, &pcr, &template,
1025 if (!(action & IMA_MEASURE) && !digest)
1030 pcr = CONFIG_IMA_MEASURE_PCR_IDX;
1032 iint.ima_hash = hash_hdr;
1033 iint.ima_hash->algo = ima_hash_algo;
1034 iint.ima_hash->length = hash_digest_size[ima_hash_algo];
1036 ret = ima_calc_buffer_hash(buf, size, iint.ima_hash);
1038 audit_cause = "hashing_error";
1043 memcpy(digest_hash, hash_hdr->digest, digest_hash_len);
1045 ret = ima_calc_buffer_hash(digest_hash, digest_hash_len,
1048 audit_cause = "hashing_error";
1052 event_data.buf = digest_hash;
1053 event_data.buf_len = digest_hash_len;
1057 memcpy(digest, iint.ima_hash->digest, digest_hash_len);
1059 if (!ima_policy_flag || (func && !(action & IMA_MEASURE)))
1062 ret = ima_alloc_init_template(&event_data, &entry, template);
1064 audit_cause = "alloc_entry";
1068 ret = ima_store_template(entry, violation, NULL, event_data.buf, pcr);
1070 audit_cause = "store_entry";
1071 ima_free_template_entry(entry);
1076 integrity_audit_message(AUDIT_INTEGRITY_PCR, NULL, eventname,
1077 func_measure_str(func),
1078 audit_cause, ret, 0, ret);
1084 * ima_kexec_cmdline - measure kexec cmdline boot args
1085 * @kernel_fd: file descriptor of the kexec kernel being loaded
1086 * @buf: pointer to buffer
1087 * @size: size of buffer
1089 * Buffers can only be measured, not appraised.
1091 void ima_kexec_cmdline(int kernel_fd, const void *buf, int size)
1096 CLASS(fd, f)(kernel_fd);
1100 process_buffer_measurement(file_mnt_idmap(fd_file(f)), file_inode(fd_file(f)),
1101 buf, size, "kexec-cmdline", KEXEC_CMDLINE, 0,
1102 NULL, false, NULL, 0);
1106 * ima_measure_critical_data - measure kernel integrity critical data
1107 * @event_label: unique event label for grouping and limiting critical data
1108 * @event_name: event name for the record in the IMA measurement list
1109 * @buf: pointer to buffer data
1110 * @buf_len: length of buffer data (in bytes)
1111 * @hash: measure buffer data hash
1112 * @digest: buffer digest will be written to
1113 * @digest_len: buffer length
1115 * Measure data critical to the integrity of the kernel into the IMA log
1116 * and extend the pcr. Examples of critical data could be various data
1117 * structures, policies, and states stored in kernel memory that can
1118 * impact the integrity of the system.
1120 * Return: 0 if the buffer has been successfully measured, 1 if the digest
1121 * has been written to the passed location but not added to a measurement entry,
1122 * a negative value otherwise.
1124 int ima_measure_critical_data(const char *event_label,
1125 const char *event_name,
1126 const void *buf, size_t buf_len,
1127 bool hash, u8 *digest, size_t digest_len)
1129 if (!event_name || !event_label || !buf || !buf_len)
1132 return process_buffer_measurement(&nop_mnt_idmap, NULL, buf, buf_len,
1133 event_name, CRITICAL_DATA, 0,
1134 event_label, hash, digest,
1137 EXPORT_SYMBOL_GPL(ima_measure_critical_data);
1139 #ifdef CONFIG_INTEGRITY_ASYMMETRIC_KEYS
1142 * ima_kernel_module_request - Prevent crypto-pkcs1(rsa,*) requests
1143 * @kmod_name: kernel module name
1145 * Avoid a verification loop where verifying the signature of the modprobe
1146 * binary requires executing modprobe itself. Since the modprobe iint->mutex
1147 * is already held when the signature verification is performed, a deadlock
1148 * occurs as soon as modprobe is executed within the critical region, since
1149 * the same lock cannot be taken again.
1151 * This happens when public_key_verify_signature(), in case of RSA algorithm,
1152 * use alg_name to store internal information in order to construct an
1153 * algorithm on the fly, but crypto_larval_lookup() will try to use alg_name
1154 * in order to load a kernel module with same name.
1156 * Since we don't have any real "crypto-pkcs1(rsa,*)" kernel modules,
1157 * we are safe to fail such module request from crypto_larval_lookup(), and
1158 * avoid the verification loop.
1160 * Return: Zero if it is safe to load the kernel module, -EINVAL otherwise.
1162 static int ima_kernel_module_request(char *kmod_name)
1164 if (strncmp(kmod_name, "crypto-pkcs1(rsa,", 17) == 0)
1170 #endif /* CONFIG_INTEGRITY_ASYMMETRIC_KEYS */
1172 static int __init init_ima(void)
1176 ima_appraise_parse_cmdline();
1177 ima_init_template_list();
1178 hash_setup(CONFIG_IMA_DEFAULT_HASH);
1181 if (error && strcmp(hash_algo_name[ima_hash_algo],
1182 CONFIG_IMA_DEFAULT_HASH) != 0) {
1183 pr_info("Allocating %s failed, going to use default hash algorithm %s\n",
1184 hash_algo_name[ima_hash_algo], CONFIG_IMA_DEFAULT_HASH);
1185 hash_setup_done = 0;
1186 hash_setup(CONFIG_IMA_DEFAULT_HASH);
1193 error = register_blocking_lsm_notifier(&ima_lsm_policy_notifier);
1195 pr_warn("Couldn't register LSM notifier, error %d\n", error);
1198 ima_update_policy_flags();
1203 static struct security_hook_list ima_hooks[] __ro_after_init = {
1204 LSM_HOOK_INIT(bprm_check_security, ima_bprm_check),
1205 LSM_HOOK_INIT(bprm_creds_for_exec, ima_bprm_creds_for_exec),
1206 LSM_HOOK_INIT(file_post_open, ima_file_check),
1207 LSM_HOOK_INIT(inode_post_create_tmpfile, ima_post_create_tmpfile),
1208 LSM_HOOK_INIT(file_release, ima_file_free),
1209 LSM_HOOK_INIT(mmap_file, ima_file_mmap),
1210 LSM_HOOK_INIT(file_mprotect, ima_file_mprotect),
1211 LSM_HOOK_INIT(kernel_load_data, ima_load_data),
1212 LSM_HOOK_INIT(kernel_post_load_data, ima_post_load_data),
1213 LSM_HOOK_INIT(kernel_read_file, ima_read_file),
1214 LSM_HOOK_INIT(kernel_post_read_file, ima_post_read_file),
1215 LSM_HOOK_INIT(path_post_mknod, ima_post_path_mknod),
1216 #ifdef CONFIG_IMA_MEASURE_ASYMMETRIC_KEYS
1217 LSM_HOOK_INIT(key_post_create_or_update, ima_post_key_create_or_update),
1219 #ifdef CONFIG_INTEGRITY_ASYMMETRIC_KEYS
1220 LSM_HOOK_INIT(kernel_module_request, ima_kernel_module_request),
1222 LSM_HOOK_INIT(inode_free_security_rcu, ima_inode_free_rcu),
1225 static const struct lsm_id ima_lsmid = {
1230 static int __init init_ima_lsm(void)
1232 ima_iintcache_init();
1233 security_add_hooks(ima_hooks, ARRAY_SIZE(ima_hooks), &ima_lsmid);
1234 init_ima_appraise_lsm(&ima_lsmid);
1238 struct lsm_blob_sizes ima_blob_sizes __ro_after_init = {
1239 .lbs_inode = sizeof(struct ima_iint_cache *),
1244 .init = init_ima_lsm,
1245 .order = LSM_ORDER_LAST,
1246 .blobs = &ima_blob_sizes,
1249 late_initcall(init_ima); /* Start IMA after the TPM is available */