1 // SPDX-License-Identifier: GPL-2.0-only
3 * Integrity Measurement Architecture
5 * Copyright (C) 2005,2006,2007,2008 IBM Corporation
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>
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);
133 /* IMA_MEASURE is set from reader side */
134 if (iint && test_and_clear_bit(IMA_MAY_EMIT_TOMTOU,
135 &iint->atomic_flags))
140 set_bit(IMA_MAY_EMIT_TOMTOU, &iint->atomic_flags);
142 /* Limit number of open_writers violations */
143 if (inode_is_open_for_write(inode) && must_measure) {
144 if (!test_and_set_bit(IMA_EMITTED_OPENWRITERS,
145 &iint->atomic_flags))
150 if (!send_tomtou && !send_writers)
153 *pathname = ima_d_path(&file->f_path, pathbuf, filename);
156 ima_add_violation(file, *pathname, iint,
157 "invalid_pcr", "ToMToU");
159 ima_add_violation(file, *pathname, iint,
160 "invalid_pcr", "open_writers");
163 static void ima_check_last_writer(struct ima_iint_cache *iint,
164 struct inode *inode, struct file *file)
166 fmode_t mode = file->f_mode;
169 if (!(mode & FMODE_WRITE))
172 mutex_lock(&iint->mutex);
173 if (atomic_read(&inode->i_writecount) == 1) {
176 clear_bit(IMA_EMITTED_OPENWRITERS, &iint->atomic_flags);
178 update = test_and_clear_bit(IMA_UPDATE_XATTR,
179 &iint->atomic_flags);
180 if ((iint->flags & IMA_NEW_FILE) ||
181 vfs_getattr_nosec(&file->f_path, &stat,
183 AT_STATX_SYNC_AS_STAT) ||
184 !(stat.result_mask & STATX_CHANGE_COOKIE) ||
185 stat.change_cookie != iint->real_inode.version) {
186 iint->flags &= ~(IMA_DONE_MASK | IMA_NEW_FILE);
187 iint->measured_pcrs = 0;
189 ima_update_xattr(iint, file);
192 mutex_unlock(&iint->mutex);
196 * ima_file_free - called on __fput()
197 * @file: pointer to file structure being freed
199 * Flag files that changed, based on i_version
201 static void ima_file_free(struct file *file)
203 struct inode *inode = file_inode(file);
204 struct ima_iint_cache *iint;
206 if (!ima_policy_flag || !S_ISREG(inode->i_mode))
209 iint = ima_iint_find(inode);
213 ima_check_last_writer(iint, inode, file);
216 static int process_measurement(struct file *file, const struct cred *cred,
217 struct lsm_prop *prop, char *buf, loff_t size,
218 int mask, enum ima_hooks func)
220 struct inode *real_inode, *inode = file_inode(file);
221 struct ima_iint_cache *iint = NULL;
222 struct ima_template_desc *template_desc = NULL;
223 struct inode *metadata_inode;
224 char *pathbuf = NULL;
225 char filename[NAME_MAX];
226 const char *pathname = NULL;
227 int rc = 0, action, must_appraise = 0;
228 int pcr = CONFIG_IMA_MEASURE_PCR_IDX;
229 struct evm_ima_xattr_data *xattr_value = NULL;
230 struct modsig *modsig = NULL;
232 bool violation_check;
233 enum hash_algo hash_algo;
234 unsigned int allowed_algos = 0;
236 if (!ima_policy_flag || !S_ISREG(inode->i_mode))
239 /* Return an IMA_MEASURE, IMA_APPRAISE, IMA_AUDIT action
240 * bitmask based on the appraise/audit/measurement policy.
241 * Included is the appraise submask.
243 action = ima_get_action(file_mnt_idmap(file), inode, cred, prop,
244 mask, func, &pcr, &template_desc, NULL,
246 violation_check = ((func == FILE_CHECK || func == MMAP_CHECK ||
247 func == MMAP_CHECK_REQPROT) &&
248 (ima_policy_flag & IMA_MEASURE) &&
249 ((action & IMA_MEASURE) ||
250 (file->f_mode & FMODE_WRITE)));
251 if (!action && !violation_check)
254 must_appraise = action & IMA_APPRAISE;
256 /* Is the appraise rule hook specific? */
257 if (action & IMA_FILE_APPRAISE)
263 iint = ima_inode_get(inode);
268 if (!rc && violation_check)
269 ima_rdwr_violation_check(file, iint, action & IMA_MEASURE,
270 &pathbuf, &pathname, filename);
279 mutex_lock(&iint->mutex);
281 if (test_and_clear_bit(IMA_CHANGE_ATTR, &iint->atomic_flags))
283 * Reset appraisal flags (action and non-action rule-specific)
284 * if ima_inode_post_setattr was called.
286 iint->flags &= ~(IMA_APPRAISE | IMA_APPRAISED |
287 IMA_APPRAISE_SUBMASK | IMA_APPRAISED_SUBMASK |
288 IMA_NONACTION_RULE_FLAGS);
291 * Re-evaulate the file if either the xattr has changed or the
292 * kernel has no way of detecting file change on the filesystem.
293 * (Limited to privileged mounted filesystems.)
295 if (test_and_clear_bit(IMA_CHANGE_XATTR, &iint->atomic_flags) ||
296 ((inode->i_sb->s_iflags & SB_I_IMA_UNVERIFIABLE_SIGNATURE) &&
297 !(inode->i_sb->s_iflags & SB_I_UNTRUSTED_MOUNTER) &&
298 !(action & IMA_FAIL_UNVERIFIABLE_SIGS))) {
299 iint->flags &= ~IMA_DONE_MASK;
300 iint->measured_pcrs = 0;
304 * On stacked filesystems, detect and re-evaluate file data and
307 real_inode = d_real_inode(file_dentry(file));
308 if (real_inode != inode &&
309 (action & IMA_DO_MASK) && (iint->flags & IMA_DONE_MASK)) {
310 if (!IS_I_VERSION(real_inode) ||
311 integrity_inode_attrs_changed(&iint->real_inode,
313 iint->flags &= ~IMA_DONE_MASK;
314 iint->measured_pcrs = 0;
318 * Reset the EVM status when metadata changed.
320 metadata_inode = d_inode(d_real(file_dentry(file),
322 if (evm_metadata_changed(inode, metadata_inode))
323 iint->flags &= ~(IMA_APPRAISED |
324 IMA_APPRAISED_SUBMASK);
327 /* Determine if already appraised/measured based on bitmask
328 * (IMA_MEASURE, IMA_MEASURED, IMA_XXXX_APPRAISE, IMA_XXXX_APPRAISED,
329 * IMA_AUDIT, IMA_AUDITED)
331 iint->flags |= action;
332 action &= IMA_DO_MASK;
333 action &= ~((iint->flags & (IMA_DONE_MASK ^ IMA_MEASURED)) >> 1);
335 /* If target pcr is already measured, unset IMA_MEASURE action */
336 if ((action & IMA_MEASURE) && (iint->measured_pcrs & (0x1 << pcr)))
337 action ^= IMA_MEASURE;
339 /* HASH sets the digital signature and update flags, nothing else */
340 if ((action & IMA_HASH) &&
341 !(test_bit(IMA_DIGSIG, &iint->atomic_flags))) {
342 xattr_len = ima_read_xattr(file_dentry(file),
343 &xattr_value, xattr_len);
344 if ((xattr_value && xattr_len > 2) &&
345 (xattr_value->type == EVM_IMA_XATTR_DIGSIG))
346 set_bit(IMA_DIGSIG, &iint->atomic_flags);
347 iint->flags |= IMA_HASHED;
349 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
352 /* Nothing to do, just return existing appraised status */
355 rc = mmap_violation_check(func, file, &pathbuf,
356 &pathname, filename);
358 rc = ima_get_cache_status(iint, func);
363 if ((action & IMA_APPRAISE_SUBMASK) ||
364 strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) != 0) {
365 /* read 'security.ima' */
366 xattr_len = ima_read_xattr(file_dentry(file),
367 &xattr_value, xattr_len);
370 * Read the appended modsig if allowed by the policy, and allow
371 * an additional measurement list entry, if needed, based on the
372 * template format and whether the file was already measured.
374 if (iint->flags & IMA_MODSIG_ALLOWED) {
375 rc = ima_read_modsig(func, buf, size, &modsig);
377 if (!rc && ima_template_has_modsig(template_desc) &&
378 iint->flags & IMA_MEASURED)
379 action |= IMA_MEASURE;
383 hash_algo = ima_get_hash_algo(xattr_value, xattr_len);
385 rc = ima_collect_measurement(iint, file, buf, size, hash_algo, modsig);
386 if (rc != 0 && rc != -EBADF && rc != -EINVAL)
389 if (!pathbuf) /* ima_rdwr_violation possibly pre-fetched */
390 pathname = ima_d_path(&file->f_path, &pathbuf, filename);
392 if (action & IMA_MEASURE)
393 ima_store_measurement(iint, file, pathname,
394 xattr_value, xattr_len, modsig, pcr,
396 if (rc == 0 && (action & IMA_APPRAISE_SUBMASK)) {
397 rc = ima_check_blacklist(iint, modsig, pcr);
400 rc = ima_appraise_measurement(func, iint, file,
401 pathname, xattr_value,
406 rc = mmap_violation_check(func, file, &pathbuf,
407 &pathname, filename);
409 if (action & IMA_AUDIT)
410 ima_audit_measurement(iint, pathname);
412 if ((file->f_flags & O_DIRECT) && (iint->flags & IMA_PERMIT_DIRECTIO))
415 /* Ensure the digest was generated using an allowed algorithm */
416 if (rc == 0 && must_appraise && allowed_algos != 0 &&
417 (allowed_algos & (1U << hash_algo)) == 0) {
420 integrity_audit_msg(AUDIT_INTEGRITY_DATA, file_inode(file),
421 pathname, "collect_data",
422 "denied-hash-algorithm", rc, 0);
425 if ((mask & MAY_WRITE) && test_bit(IMA_DIGSIG, &iint->atomic_flags) &&
426 !(iint->flags & IMA_NEW_FILE))
428 mutex_unlock(&iint->mutex);
430 ima_free_modsig(modsig);
435 if (rc && (ima_appraise & IMA_APPRAISE_ENFORCE))
437 if (file->f_mode & FMODE_WRITE)
438 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
444 * ima_file_mmap - based on policy, collect/store measurement.
445 * @file: pointer to the file to be measured (May be NULL)
446 * @reqprot: protection requested by the application
447 * @prot: protection that will be applied by the kernel
448 * @flags: operational flags
450 * Measure files being mmapped executable based on the ima_must_measure()
453 * On success return 0. On integrity appraisal error, assuming the file
454 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
456 static int ima_file_mmap(struct file *file, unsigned long reqprot,
457 unsigned long prot, unsigned long flags)
459 struct lsm_prop prop;
465 security_current_getlsmprop_subj(&prop);
467 if (reqprot & PROT_EXEC) {
468 ret = process_measurement(file, current_cred(), &prop, NULL,
469 0, MAY_EXEC, MMAP_CHECK_REQPROT);
474 if (prot & PROT_EXEC)
475 return process_measurement(file, current_cred(), &prop, NULL,
476 0, MAY_EXEC, MMAP_CHECK);
482 * ima_file_mprotect - based on policy, limit mprotect change
483 * @vma: vm_area_struct protection is set to
484 * @reqprot: protection requested by the application
485 * @prot: protection that will be applied by the kernel
487 * Files can be mmap'ed read/write and later changed to execute to circumvent
488 * IMA's mmap appraisal policy rules. Due to locking issues (mmap semaphore
489 * would be taken before i_mutex), files can not be measured or appraised at
490 * this point. Eliminate this integrity gap by denying the mprotect
491 * PROT_EXECUTE change, if an mmap appraise policy rule exists.
493 * On mprotect change success, return 0. On failure, return -EACESS.
495 static int ima_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot,
498 struct ima_template_desc *template = NULL;
500 char filename[NAME_MAX];
501 char *pathbuf = NULL;
502 const char *pathname = NULL;
504 struct lsm_prop prop;
509 /* Is mprotect making an mmap'ed file executable? */
510 if (!(ima_policy_flag & IMA_APPRAISE) || !vma->vm_file ||
511 !(prot & PROT_EXEC) || (vma->vm_flags & VM_EXEC))
514 security_current_getlsmprop_subj(&prop);
515 inode = file_inode(vma->vm_file);
516 action = ima_get_action(file_mnt_idmap(vma->vm_file), inode,
517 current_cred(), &prop, MAY_EXEC, MMAP_CHECK,
518 &pcr, &template, NULL, NULL);
519 action |= ima_get_action(file_mnt_idmap(vma->vm_file), inode,
520 current_cred(), &prop, MAY_EXEC,
521 MMAP_CHECK_REQPROT, &pcr, &template, NULL,
524 /* Is the mmap'ed file in policy? */
525 if (!(action & (IMA_MEASURE | IMA_APPRAISE_SUBMASK)))
528 if (action & IMA_APPRAISE_SUBMASK)
532 pathname = ima_d_path(&file->f_path, &pathbuf, filename);
533 integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, pathname,
534 "collect_data", "failed-mprotect", result, 0);
542 * ima_bprm_check - based on policy, collect/store measurement.
543 * @bprm: contains the linux_binprm structure
545 * The OS protects against an executable file, already open for write,
546 * from being executed in deny_write_access() and an executable file,
547 * already open for execute, from being modified in get_write_access().
548 * So we can be certain that what we verify and measure here is actually
549 * what is being executed.
551 * On success return 0. On integrity appraisal error, assuming the file
552 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
554 static int ima_bprm_check(struct linux_binprm *bprm)
557 struct lsm_prop prop;
559 security_current_getlsmprop_subj(&prop);
560 ret = process_measurement(bprm->file, current_cred(),
561 &prop, NULL, 0, MAY_EXEC, BPRM_CHECK);
565 security_cred_getlsmprop(bprm->cred, &prop);
566 return process_measurement(bprm->file, bprm->cred, &prop, NULL, 0,
567 MAY_EXEC, CREDS_CHECK);
571 * ima_bprm_creds_for_exec - collect/store/appraise measurement.
572 * @bprm: contains the linux_binprm structure
574 * Based on the IMA policy and the execveat(2) AT_EXECVE_CHECK flag, measure
575 * and appraise the integrity of a file to be executed by script interpreters.
576 * Unlike any of the other LSM hooks where the kernel enforces file integrity,
577 * enforcing file integrity is left up to the discretion of the script
578 * interpreter (userspace).
580 * On success return 0. On integrity appraisal error, assuming the file
581 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
583 static int ima_bprm_creds_for_exec(struct linux_binprm *bprm)
586 * As security_bprm_check() is called multiple times, both
587 * the script and the shebang interpreter are measured, appraised,
588 * and audited. Limit usage of this LSM hook to just measuring,
589 * appraising, and auditing the indirect script execution
590 * (e.g. ./sh example.sh).
595 return ima_bprm_check(bprm);
599 * ima_file_check - based on policy, collect/store measurement.
600 * @file: pointer to the file to be measured
601 * @mask: contains MAY_READ, MAY_WRITE, MAY_EXEC or MAY_APPEND
603 * Measure files based on the ima_must_measure() policy decision.
605 * On success return 0. On integrity appraisal error, assuming the file
606 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
608 static int ima_file_check(struct file *file, int mask)
610 struct lsm_prop prop;
612 security_current_getlsmprop_subj(&prop);
613 return process_measurement(file, current_cred(), &prop, NULL, 0,
614 mask & (MAY_READ | MAY_WRITE | MAY_EXEC |
615 MAY_APPEND), FILE_CHECK);
618 static int __ima_inode_hash(struct inode *inode, struct file *file, char *buf,
621 struct ima_iint_cache *iint = NULL, tmp_iint;
624 if (ima_policy_flag) {
625 iint = ima_iint_find(inode);
627 mutex_lock(&iint->mutex);
630 if ((!iint || !(iint->flags & IMA_COLLECTED)) && file) {
632 mutex_unlock(&iint->mutex);
634 memset(&tmp_iint, 0, sizeof(tmp_iint));
635 mutex_init(&tmp_iint.mutex);
637 rc = ima_collect_measurement(&tmp_iint, file, NULL, 0,
638 ima_hash_algo, NULL);
640 /* ima_hash could be allocated in case of failure. */
642 kfree(tmp_iint.ima_hash);
648 mutex_lock(&iint->mutex);
655 * ima_file_hash can be called when ima_collect_measurement has still
656 * not been called, we might not always have a hash.
658 if (!iint->ima_hash || !(iint->flags & IMA_COLLECTED)) {
659 mutex_unlock(&iint->mutex);
666 copied_size = min_t(size_t, iint->ima_hash->length, buf_size);
667 memcpy(buf, iint->ima_hash->digest, copied_size);
669 hash_algo = iint->ima_hash->algo;
670 mutex_unlock(&iint->mutex);
672 if (iint == &tmp_iint)
673 kfree(iint->ima_hash);
679 * ima_file_hash - return a measurement of the file
680 * @file: pointer to the file
681 * @buf: buffer in which to store the hash
682 * @buf_size: length of the buffer
684 * On success, return the hash algorithm (as defined in the enum hash_algo).
685 * If buf is not NULL, this function also outputs the hash into buf.
686 * If the hash is larger than buf_size, then only buf_size bytes will be copied.
687 * It generally just makes sense to pass a buffer capable of holding the largest
688 * possible hash: IMA_MAX_DIGEST_SIZE.
689 * The file hash returned is based on the entire file, including the appended
692 * If the measurement cannot be performed, return -EOPNOTSUPP.
693 * If the parameters are incorrect, return -EINVAL.
695 int ima_file_hash(struct file *file, char *buf, size_t buf_size)
700 return __ima_inode_hash(file_inode(file), file, buf, buf_size);
702 EXPORT_SYMBOL_GPL(ima_file_hash);
705 * ima_inode_hash - return the stored measurement if the inode has been hashed
706 * and is in the iint cache.
707 * @inode: pointer to the inode
708 * @buf: buffer in which to store the hash
709 * @buf_size: length of the buffer
711 * On success, return the hash algorithm (as defined in the enum hash_algo).
712 * If buf is not NULL, this function also outputs the hash into buf.
713 * If the hash is larger than buf_size, then only buf_size bytes will be copied.
714 * It generally just makes sense to pass a buffer capable of holding the largest
715 * possible hash: IMA_MAX_DIGEST_SIZE.
716 * The hash returned is based on the entire contents, including the appended
719 * If IMA is disabled or if no measurement is available, return -EOPNOTSUPP.
720 * If the parameters are incorrect, return -EINVAL.
722 int ima_inode_hash(struct inode *inode, char *buf, size_t buf_size)
727 return __ima_inode_hash(inode, NULL, buf, buf_size);
729 EXPORT_SYMBOL_GPL(ima_inode_hash);
732 * ima_post_create_tmpfile - mark newly created tmpfile as new
733 * @idmap: idmap of the mount the inode was found from
734 * @inode: inode of the newly created tmpfile
736 * No measuring, appraising or auditing of newly created tmpfiles is needed.
737 * Skip calling process_measurement(), but indicate which newly, created
738 * tmpfiles are in policy.
740 static void ima_post_create_tmpfile(struct mnt_idmap *idmap,
744 struct ima_iint_cache *iint;
747 if (!ima_policy_flag || !S_ISREG(inode->i_mode))
750 must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS,
755 /* Nothing to do if we can't allocate memory */
756 iint = ima_inode_get(inode);
760 /* needed for writing the security xattrs */
761 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
762 iint->ima_file_status = INTEGRITY_PASS;
766 * ima_post_path_mknod - mark as a new inode
767 * @idmap: idmap of the mount the inode was found from
768 * @dentry: newly created dentry
770 * Mark files created via the mknodat syscall as new, so that the
771 * file data can be written later.
773 static void ima_post_path_mknod(struct mnt_idmap *idmap, struct dentry *dentry)
775 struct ima_iint_cache *iint;
776 struct inode *inode = dentry->d_inode;
779 if (!ima_policy_flag || !S_ISREG(inode->i_mode))
782 must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS,
787 /* Nothing to do if we can't allocate memory */
788 iint = ima_inode_get(inode);
792 /* needed for re-opening empty files */
793 iint->flags |= IMA_NEW_FILE;
797 * ima_read_file - pre-measure/appraise hook decision based on policy
798 * @file: pointer to the file to be measured/appraised/audit
799 * @read_id: caller identifier
800 * @contents: whether a subsequent call will be made to ima_post_read_file()
802 * Permit reading a file based on policy. The policy rules are written
803 * in terms of the policy identifier. Appraising the integrity of
804 * a file requires a file descriptor.
806 * For permission return 0, otherwise return -EACCES.
808 static int ima_read_file(struct file *file, enum kernel_read_file_id read_id,
812 struct lsm_prop prop;
815 * Do devices using pre-allocated memory run the risk of the
816 * firmware being accessible to the device prior to the completion
817 * of IMA's signature verification any more than when using two
818 * buffers? It may be desirable to include the buffer address
819 * in this API and walk all the dma_map_single() mappings to check.
823 * There will be a call made to ima_post_read_file() with
824 * a filled buffer, so we don't need to perform an extra
830 /* Read entire file for all partial reads. */
831 func = read_idmap[read_id] ?: FILE_CHECK;
832 security_current_getlsmprop_subj(&prop);
833 return process_measurement(file, current_cred(), &prop, NULL, 0,
837 const int read_idmap[READING_MAX_ID] = {
838 [READING_FIRMWARE] = FIRMWARE_CHECK,
839 [READING_MODULE] = MODULE_CHECK,
840 [READING_KEXEC_IMAGE] = KEXEC_KERNEL_CHECK,
841 [READING_KEXEC_INITRAMFS] = KEXEC_INITRAMFS_CHECK,
842 [READING_POLICY] = POLICY_CHECK
846 * ima_post_read_file - in memory collect/appraise/audit measurement
847 * @file: pointer to the file to be measured/appraised/audit
848 * @buf: pointer to in memory file contents
849 * @size: size of in memory file contents
850 * @read_id: caller identifier
852 * Measure/appraise/audit in memory file based on policy. Policy rules
853 * are written in terms of a policy identifier.
855 * On success return 0. On integrity appraisal error, assuming the file
856 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
858 static int ima_post_read_file(struct file *file, char *buf, loff_t size,
859 enum kernel_read_file_id read_id)
862 struct lsm_prop prop;
864 /* permit signed certs */
865 if (!file && read_id == READING_X509_CERTIFICATE)
868 if (!file || !buf || size == 0) { /* should never happen */
869 if (ima_appraise & IMA_APPRAISE_ENFORCE)
874 func = read_idmap[read_id] ?: FILE_CHECK;
875 security_current_getlsmprop_subj(&prop);
876 return process_measurement(file, current_cred(), &prop, buf, size,
881 * ima_load_data - appraise decision based on policy
882 * @id: kernel load data caller identifier
883 * @contents: whether the full contents will be available in a later
884 * call to ima_post_load_data().
886 * Callers of this LSM hook can not measure, appraise, or audit the
887 * data provided by userspace. Enforce policy rules requiring a file
888 * signature (eg. kexec'ed kernel image).
890 * For permission return 0, otherwise return -EACCES.
892 static int ima_load_data(enum kernel_load_data_id id, bool contents)
894 bool ima_enforce, sig_enforce;
897 (ima_appraise & IMA_APPRAISE_ENFORCE) == IMA_APPRAISE_ENFORCE;
900 case LOADING_KEXEC_IMAGE:
901 if (IS_ENABLED(CONFIG_KEXEC_SIG)
902 && arch_ima_get_secureboot()) {
903 pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
907 if (ima_enforce && (ima_appraise & IMA_APPRAISE_KEXEC)) {
908 pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
909 return -EACCES; /* INTEGRITY_UNKNOWN */
912 case LOADING_FIRMWARE:
913 if (ima_enforce && (ima_appraise & IMA_APPRAISE_FIRMWARE) && !contents) {
914 pr_err("Prevent firmware sysfs fallback loading.\n");
915 return -EACCES; /* INTEGRITY_UNKNOWN */
919 sig_enforce = is_module_sig_enforced();
921 if (ima_enforce && (!sig_enforce
922 && (ima_appraise & IMA_APPRAISE_MODULES))) {
923 pr_err("impossible to appraise a module without a file descriptor. sig_enforce kernel parameter might help\n");
924 return -EACCES; /* INTEGRITY_UNKNOWN */
934 * ima_post_load_data - appraise decision based on policy
935 * @buf: pointer to in memory file contents
936 * @size: size of in memory file contents
937 * @load_id: kernel load data caller identifier
938 * @description: @load_id-specific description of contents
940 * Measure/appraise/audit in memory buffer based on policy. Policy rules
941 * are written in terms of a policy identifier.
943 * On success return 0. On integrity appraisal error, assuming the file
944 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
946 static int ima_post_load_data(char *buf, loff_t size,
947 enum kernel_load_data_id load_id,
950 if (load_id == LOADING_FIRMWARE) {
951 if ((ima_appraise & IMA_APPRAISE_FIRMWARE) &&
952 (ima_appraise & IMA_APPRAISE_ENFORCE)) {
953 pr_err("Prevent firmware loading_store.\n");
954 return -EACCES; /* INTEGRITY_UNKNOWN */
960 * Measure the init_module syscall buffer containing the ELF image.
962 if (load_id == LOADING_MODULE)
963 ima_measure_critical_data("modules", "init_module",
964 buf, size, true, NULL, 0);
970 * process_buffer_measurement - Measure the buffer or the buffer data hash
971 * @idmap: idmap of the mount the inode was found from
972 * @inode: inode associated with the object being measured (NULL for KEY_CHECK)
973 * @buf: pointer to the buffer that needs to be added to the log.
974 * @size: size of buffer(in bytes).
975 * @eventname: event name to be used for the buffer entry.
977 * @pcr: pcr to extend the measurement
978 * @func_data: func specific data, may be NULL
979 * @buf_hash: measure buffer data hash
980 * @digest: buffer digest will be written to
981 * @digest_len: buffer length
983 * Based on policy, either the buffer data or buffer data hash is measured
985 * Return: 0 if the buffer has been successfully measured, 1 if the digest
986 * has been written to the passed location but not added to a measurement entry,
987 * a negative value otherwise.
989 int process_buffer_measurement(struct mnt_idmap *idmap,
990 struct inode *inode, const void *buf, int size,
991 const char *eventname, enum ima_hooks func,
992 int pcr, const char *func_data,
993 bool buf_hash, u8 *digest, size_t digest_len)
996 const char *audit_cause = "ENOMEM";
997 struct ima_template_entry *entry = NULL;
998 struct ima_iint_cache iint = {};
999 struct ima_event_data event_data = {.iint = &iint,
1000 .filename = eventname,
1003 struct ima_template_desc *template;
1004 struct ima_max_digest_data hash;
1005 struct ima_digest_data *hash_hdr = container_of(&hash.hdr,
1006 struct ima_digest_data, hdr);
1007 char digest_hash[IMA_MAX_DIGEST_SIZE];
1008 int digest_hash_len = hash_digest_size[ima_hash_algo];
1011 struct lsm_prop prop;
1013 if (digest && digest_len < digest_hash_len)
1016 if (!ima_policy_flag && !digest)
1019 template = ima_template_desc_buf();
1022 audit_cause = "ima_template_desc_buf";
1027 * Both LSM hooks and auxiliary based buffer measurements are
1028 * based on policy. To avoid code duplication, differentiate
1029 * between the LSM hooks and auxiliary buffer measurements,
1030 * retrieving the policy rule information only for the LSM hook
1031 * buffer measurements.
1034 security_current_getlsmprop_subj(&prop);
1035 action = ima_get_action(idmap, inode, current_cred(),
1036 &prop, 0, func, &pcr, &template,
1038 if (!(action & IMA_MEASURE) && !digest)
1043 pcr = CONFIG_IMA_MEASURE_PCR_IDX;
1045 iint.ima_hash = hash_hdr;
1046 iint.ima_hash->algo = ima_hash_algo;
1047 iint.ima_hash->length = hash_digest_size[ima_hash_algo];
1049 ret = ima_calc_buffer_hash(buf, size, iint.ima_hash);
1051 audit_cause = "hashing_error";
1056 memcpy(digest_hash, hash_hdr->digest, digest_hash_len);
1058 ret = ima_calc_buffer_hash(digest_hash, digest_hash_len,
1061 audit_cause = "hashing_error";
1065 event_data.buf = digest_hash;
1066 event_data.buf_len = digest_hash_len;
1070 memcpy(digest, iint.ima_hash->digest, digest_hash_len);
1072 if (!ima_policy_flag || (func && !(action & IMA_MEASURE)))
1075 ret = ima_alloc_init_template(&event_data, &entry, template);
1077 audit_cause = "alloc_entry";
1081 ret = ima_store_template(entry, violation, NULL, event_data.buf, pcr);
1083 audit_cause = "store_entry";
1084 ima_free_template_entry(entry);
1089 integrity_audit_message(AUDIT_INTEGRITY_PCR, NULL, eventname,
1090 func_measure_str(func),
1091 audit_cause, ret, 0, ret);
1097 * ima_kexec_cmdline - measure kexec cmdline boot args
1098 * @kernel_fd: file descriptor of the kexec kernel being loaded
1099 * @buf: pointer to buffer
1100 * @size: size of buffer
1102 * Buffers can only be measured, not appraised.
1104 void ima_kexec_cmdline(int kernel_fd, const void *buf, int size)
1109 CLASS(fd, f)(kernel_fd);
1113 process_buffer_measurement(file_mnt_idmap(fd_file(f)), file_inode(fd_file(f)),
1114 buf, size, "kexec-cmdline", KEXEC_CMDLINE, 0,
1115 NULL, false, NULL, 0);
1119 * ima_measure_critical_data - measure kernel integrity critical data
1120 * @event_label: unique event label for grouping and limiting critical data
1121 * @event_name: event name for the record in the IMA measurement list
1122 * @buf: pointer to buffer data
1123 * @buf_len: length of buffer data (in bytes)
1124 * @hash: measure buffer data hash
1125 * @digest: buffer digest will be written to
1126 * @digest_len: buffer length
1128 * Measure data critical to the integrity of the kernel into the IMA log
1129 * and extend the pcr. Examples of critical data could be various data
1130 * structures, policies, and states stored in kernel memory that can
1131 * impact the integrity of the system.
1133 * Return: 0 if the buffer has been successfully measured, 1 if the digest
1134 * has been written to the passed location but not added to a measurement entry,
1135 * a negative value otherwise.
1137 int ima_measure_critical_data(const char *event_label,
1138 const char *event_name,
1139 const void *buf, size_t buf_len,
1140 bool hash, u8 *digest, size_t digest_len)
1142 if (!event_name || !event_label || !buf || !buf_len)
1145 return process_buffer_measurement(&nop_mnt_idmap, NULL, buf, buf_len,
1146 event_name, CRITICAL_DATA, 0,
1147 event_label, hash, digest,
1150 EXPORT_SYMBOL_GPL(ima_measure_critical_data);
1152 #ifdef CONFIG_INTEGRITY_ASYMMETRIC_KEYS
1155 * ima_kernel_module_request - Prevent crypto-pkcs1(rsa,*) requests
1156 * @kmod_name: kernel module name
1158 * Avoid a verification loop where verifying the signature of the modprobe
1159 * binary requires executing modprobe itself. Since the modprobe iint->mutex
1160 * is already held when the signature verification is performed, a deadlock
1161 * occurs as soon as modprobe is executed within the critical region, since
1162 * the same lock cannot be taken again.
1164 * This happens when public_key_verify_signature(), in case of RSA algorithm,
1165 * use alg_name to store internal information in order to construct an
1166 * algorithm on the fly, but crypto_larval_lookup() will try to use alg_name
1167 * in order to load a kernel module with same name.
1169 * Since we don't have any real "crypto-pkcs1(rsa,*)" kernel modules,
1170 * we are safe to fail such module request from crypto_larval_lookup(), and
1171 * avoid the verification loop.
1173 * Return: Zero if it is safe to load the kernel module, -EINVAL otherwise.
1175 static int ima_kernel_module_request(char *kmod_name)
1177 if (strncmp(kmod_name, "crypto-pkcs1(rsa,", 17) == 0)
1183 #endif /* CONFIG_INTEGRITY_ASYMMETRIC_KEYS */
1185 static int __init init_ima(void)
1189 ima_appraise_parse_cmdline();
1190 ima_init_template_list();
1191 hash_setup(CONFIG_IMA_DEFAULT_HASH);
1194 if (error && strcmp(hash_algo_name[ima_hash_algo],
1195 CONFIG_IMA_DEFAULT_HASH) != 0) {
1196 pr_info("Allocating %s failed, going to use default hash algorithm %s\n",
1197 hash_algo_name[ima_hash_algo], CONFIG_IMA_DEFAULT_HASH);
1198 hash_setup_done = 0;
1199 hash_setup(CONFIG_IMA_DEFAULT_HASH);
1206 error = register_blocking_lsm_notifier(&ima_lsm_policy_notifier);
1208 pr_warn("Couldn't register LSM notifier, error %d\n", error);
1211 ima_update_policy_flags();
1216 static struct security_hook_list ima_hooks[] __ro_after_init = {
1217 LSM_HOOK_INIT(bprm_check_security, ima_bprm_check),
1218 LSM_HOOK_INIT(bprm_creds_for_exec, ima_bprm_creds_for_exec),
1219 LSM_HOOK_INIT(file_post_open, ima_file_check),
1220 LSM_HOOK_INIT(inode_post_create_tmpfile, ima_post_create_tmpfile),
1221 LSM_HOOK_INIT(file_release, ima_file_free),
1222 LSM_HOOK_INIT(mmap_file, ima_file_mmap),
1223 LSM_HOOK_INIT(file_mprotect, ima_file_mprotect),
1224 LSM_HOOK_INIT(kernel_load_data, ima_load_data),
1225 LSM_HOOK_INIT(kernel_post_load_data, ima_post_load_data),
1226 LSM_HOOK_INIT(kernel_read_file, ima_read_file),
1227 LSM_HOOK_INIT(kernel_post_read_file, ima_post_read_file),
1228 LSM_HOOK_INIT(path_post_mknod, ima_post_path_mknod),
1229 #ifdef CONFIG_IMA_MEASURE_ASYMMETRIC_KEYS
1230 LSM_HOOK_INIT(key_post_create_or_update, ima_post_key_create_or_update),
1232 #ifdef CONFIG_INTEGRITY_ASYMMETRIC_KEYS
1233 LSM_HOOK_INIT(kernel_module_request, ima_kernel_module_request),
1235 LSM_HOOK_INIT(inode_free_security_rcu, ima_inode_free_rcu),
1238 static const struct lsm_id ima_lsmid = {
1243 static int __init init_ima_lsm(void)
1245 ima_iintcache_init();
1246 security_add_hooks(ima_hooks, ARRAY_SIZE(ima_hooks), &ima_lsmid);
1247 init_ima_appraise_lsm(&ima_lsmid);
1251 struct lsm_blob_sizes ima_blob_sizes __ro_after_init = {
1252 .lbs_inode = sizeof(struct ima_iint_cache *),
1257 .init = init_ima_lsm,
1258 .order = LSM_ORDER_LAST,
1259 .blobs = &ima_blob_sizes,
1262 late_initcall(init_ima); /* Start IMA after the TPM is available */