Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Integrity Measurement Architecture
0004  *
0005  * Copyright (C) 2005,2006,2007,2008 IBM Corporation
0006  *
0007  * Authors:
0008  * Reiner Sailer <sailer@watson.ibm.com>
0009  * Serge Hallyn <serue@us.ibm.com>
0010  * Kylene Hall <kylene@us.ibm.com>
0011  * Mimi Zohar <zohar@us.ibm.com>
0012  *
0013  * File: ima_main.c
0014  *  implements the IMA hooks: ima_bprm_check, ima_file_mmap,
0015  *  and ima_file_check.
0016  */
0017 
0018 #include <linux/module.h>
0019 #include <linux/file.h>
0020 #include <linux/binfmts.h>
0021 #include <linux/kernel_read_file.h>
0022 #include <linux/mount.h>
0023 #include <linux/mman.h>
0024 #include <linux/slab.h>
0025 #include <linux/xattr.h>
0026 #include <linux/ima.h>
0027 #include <linux/iversion.h>
0028 #include <linux/fs.h>
0029 
0030 #include "ima.h"
0031 
0032 #ifdef CONFIG_IMA_APPRAISE
0033 int ima_appraise = IMA_APPRAISE_ENFORCE;
0034 #else
0035 int ima_appraise;
0036 #endif
0037 
0038 int __ro_after_init ima_hash_algo = HASH_ALGO_SHA1;
0039 static int hash_setup_done;
0040 
0041 static struct notifier_block ima_lsm_policy_notifier = {
0042     .notifier_call = ima_lsm_policy_change,
0043 };
0044 
0045 static int __init hash_setup(char *str)
0046 {
0047     struct ima_template_desc *template_desc = ima_template_desc_current();
0048     int i;
0049 
0050     if (hash_setup_done)
0051         return 1;
0052 
0053     if (strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) == 0) {
0054         if (strncmp(str, "sha1", 4) == 0) {
0055             ima_hash_algo = HASH_ALGO_SHA1;
0056         } else if (strncmp(str, "md5", 3) == 0) {
0057             ima_hash_algo = HASH_ALGO_MD5;
0058         } else {
0059             pr_err("invalid hash algorithm \"%s\" for template \"%s\"",
0060                 str, IMA_TEMPLATE_IMA_NAME);
0061             return 1;
0062         }
0063         goto out;
0064     }
0065 
0066     i = match_string(hash_algo_name, HASH_ALGO__LAST, str);
0067     if (i < 0) {
0068         pr_err("invalid hash algorithm \"%s\"", str);
0069         return 1;
0070     }
0071 
0072     ima_hash_algo = i;
0073 out:
0074     hash_setup_done = 1;
0075     return 1;
0076 }
0077 __setup("ima_hash=", hash_setup);
0078 
0079 enum hash_algo ima_get_current_hash_algo(void)
0080 {
0081     return ima_hash_algo;
0082 }
0083 
0084 /* Prevent mmap'ing a file execute that is already mmap'ed write */
0085 static int mmap_violation_check(enum ima_hooks func, struct file *file,
0086                 char **pathbuf, const char **pathname,
0087                 char *filename)
0088 {
0089     struct inode *inode;
0090     int rc = 0;
0091 
0092     if ((func == MMAP_CHECK) && mapping_writably_mapped(file->f_mapping)) {
0093         rc = -ETXTBSY;
0094         inode = file_inode(file);
0095 
0096         if (!*pathbuf)  /* ima_rdwr_violation possibly pre-fetched */
0097             *pathname = ima_d_path(&file->f_path, pathbuf,
0098                            filename);
0099         integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, *pathname,
0100                     "mmap_file", "mmapped_writers", rc, 0);
0101     }
0102     return rc;
0103 }
0104 
0105 /*
0106  * ima_rdwr_violation_check
0107  *
0108  * Only invalidate the PCR for measured files:
0109  *  - Opening a file for write when already open for read,
0110  *    results in a time of measure, time of use (ToMToU) error.
0111  *  - Opening a file for read when already open for write,
0112  *    could result in a file measurement error.
0113  *
0114  */
0115 static void ima_rdwr_violation_check(struct file *file,
0116                      struct integrity_iint_cache *iint,
0117                      int must_measure,
0118                      char **pathbuf,
0119                      const char **pathname,
0120                      char *filename)
0121 {
0122     struct inode *inode = file_inode(file);
0123     fmode_t mode = file->f_mode;
0124     bool send_tomtou = false, send_writers = false;
0125 
0126     if (mode & FMODE_WRITE) {
0127         if (atomic_read(&inode->i_readcount) && IS_IMA(inode)) {
0128             if (!iint)
0129                 iint = integrity_iint_find(inode);
0130             /* IMA_MEASURE is set from reader side */
0131             if (iint && test_bit(IMA_MUST_MEASURE,
0132                         &iint->atomic_flags))
0133                 send_tomtou = true;
0134         }
0135     } else {
0136         if (must_measure)
0137             set_bit(IMA_MUST_MEASURE, &iint->atomic_flags);
0138         if (inode_is_open_for_write(inode) && must_measure)
0139             send_writers = true;
0140     }
0141 
0142     if (!send_tomtou && !send_writers)
0143         return;
0144 
0145     *pathname = ima_d_path(&file->f_path, pathbuf, filename);
0146 
0147     if (send_tomtou)
0148         ima_add_violation(file, *pathname, iint,
0149                   "invalid_pcr", "ToMToU");
0150     if (send_writers)
0151         ima_add_violation(file, *pathname, iint,
0152                   "invalid_pcr", "open_writers");
0153 }
0154 
0155 static void ima_check_last_writer(struct integrity_iint_cache *iint,
0156                   struct inode *inode, struct file *file)
0157 {
0158     fmode_t mode = file->f_mode;
0159     bool update;
0160 
0161     if (!(mode & FMODE_WRITE))
0162         return;
0163 
0164     mutex_lock(&iint->mutex);
0165     if (atomic_read(&inode->i_writecount) == 1) {
0166         update = test_and_clear_bit(IMA_UPDATE_XATTR,
0167                         &iint->atomic_flags);
0168         if (!IS_I_VERSION(inode) ||
0169             !inode_eq_iversion(inode, iint->version) ||
0170             (iint->flags & IMA_NEW_FILE)) {
0171             iint->flags &= ~(IMA_DONE_MASK | IMA_NEW_FILE);
0172             iint->measured_pcrs = 0;
0173             if (update)
0174                 ima_update_xattr(iint, file);
0175         }
0176     }
0177     mutex_unlock(&iint->mutex);
0178 }
0179 
0180 /**
0181  * ima_file_free - called on __fput()
0182  * @file: pointer to file structure being freed
0183  *
0184  * Flag files that changed, based on i_version
0185  */
0186 void ima_file_free(struct file *file)
0187 {
0188     struct inode *inode = file_inode(file);
0189     struct integrity_iint_cache *iint;
0190 
0191     if (!ima_policy_flag || !S_ISREG(inode->i_mode))
0192         return;
0193 
0194     iint = integrity_iint_find(inode);
0195     if (!iint)
0196         return;
0197 
0198     ima_check_last_writer(iint, inode, file);
0199 }
0200 
0201 static int process_measurement(struct file *file, const struct cred *cred,
0202                    u32 secid, char *buf, loff_t size, int mask,
0203                    enum ima_hooks func)
0204 {
0205     struct inode *inode = file_inode(file);
0206     struct integrity_iint_cache *iint = NULL;
0207     struct ima_template_desc *template_desc = NULL;
0208     char *pathbuf = NULL;
0209     char filename[NAME_MAX];
0210     const char *pathname = NULL;
0211     int rc = 0, action, must_appraise = 0;
0212     int pcr = CONFIG_IMA_MEASURE_PCR_IDX;
0213     struct evm_ima_xattr_data *xattr_value = NULL;
0214     struct modsig *modsig = NULL;
0215     int xattr_len = 0;
0216     bool violation_check;
0217     enum hash_algo hash_algo;
0218     unsigned int allowed_algos = 0;
0219 
0220     if (!ima_policy_flag || !S_ISREG(inode->i_mode))
0221         return 0;
0222 
0223     /* Return an IMA_MEASURE, IMA_APPRAISE, IMA_AUDIT action
0224      * bitmask based on the appraise/audit/measurement policy.
0225      * Included is the appraise submask.
0226      */
0227     action = ima_get_action(file_mnt_user_ns(file), inode, cred, secid,
0228                 mask, func, &pcr, &template_desc, NULL,
0229                 &allowed_algos);
0230     violation_check = ((func == FILE_CHECK || func == MMAP_CHECK) &&
0231                (ima_policy_flag & IMA_MEASURE));
0232     if (!action && !violation_check)
0233         return 0;
0234 
0235     must_appraise = action & IMA_APPRAISE;
0236 
0237     /*  Is the appraise rule hook specific?  */
0238     if (action & IMA_FILE_APPRAISE)
0239         func = FILE_CHECK;
0240 
0241     inode_lock(inode);
0242 
0243     if (action) {
0244         iint = integrity_inode_get(inode);
0245         if (!iint)
0246             rc = -ENOMEM;
0247     }
0248 
0249     if (!rc && violation_check)
0250         ima_rdwr_violation_check(file, iint, action & IMA_MEASURE,
0251                      &pathbuf, &pathname, filename);
0252 
0253     inode_unlock(inode);
0254 
0255     if (rc)
0256         goto out;
0257     if (!action)
0258         goto out;
0259 
0260     mutex_lock(&iint->mutex);
0261 
0262     if (test_and_clear_bit(IMA_CHANGE_ATTR, &iint->atomic_flags))
0263         /* reset appraisal flags if ima_inode_post_setattr was called */
0264         iint->flags &= ~(IMA_APPRAISE | IMA_APPRAISED |
0265                  IMA_APPRAISE_SUBMASK | IMA_APPRAISED_SUBMASK |
0266                  IMA_NONACTION_FLAGS);
0267 
0268     /*
0269      * Re-evaulate the file if either the xattr has changed or the
0270      * kernel has no way of detecting file change on the filesystem.
0271      * (Limited to privileged mounted filesystems.)
0272      */
0273     if (test_and_clear_bit(IMA_CHANGE_XATTR, &iint->atomic_flags) ||
0274         ((inode->i_sb->s_iflags & SB_I_IMA_UNVERIFIABLE_SIGNATURE) &&
0275          !(inode->i_sb->s_iflags & SB_I_UNTRUSTED_MOUNTER) &&
0276          !(action & IMA_FAIL_UNVERIFIABLE_SIGS))) {
0277         iint->flags &= ~IMA_DONE_MASK;
0278         iint->measured_pcrs = 0;
0279     }
0280 
0281     /* Determine if already appraised/measured based on bitmask
0282      * (IMA_MEASURE, IMA_MEASURED, IMA_XXXX_APPRAISE, IMA_XXXX_APPRAISED,
0283      *  IMA_AUDIT, IMA_AUDITED)
0284      */
0285     iint->flags |= action;
0286     action &= IMA_DO_MASK;
0287     action &= ~((iint->flags & (IMA_DONE_MASK ^ IMA_MEASURED)) >> 1);
0288 
0289     /* If target pcr is already measured, unset IMA_MEASURE action */
0290     if ((action & IMA_MEASURE) && (iint->measured_pcrs & (0x1 << pcr)))
0291         action ^= IMA_MEASURE;
0292 
0293     /* HASH sets the digital signature and update flags, nothing else */
0294     if ((action & IMA_HASH) &&
0295         !(test_bit(IMA_DIGSIG, &iint->atomic_flags))) {
0296         xattr_len = ima_read_xattr(file_dentry(file), &xattr_value);
0297         if ((xattr_value && xattr_len > 2) &&
0298             (xattr_value->type == EVM_IMA_XATTR_DIGSIG))
0299             set_bit(IMA_DIGSIG, &iint->atomic_flags);
0300         iint->flags |= IMA_HASHED;
0301         action ^= IMA_HASH;
0302         set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
0303     }
0304 
0305     /* Nothing to do, just return existing appraised status */
0306     if (!action) {
0307         if (must_appraise) {
0308             rc = mmap_violation_check(func, file, &pathbuf,
0309                           &pathname, filename);
0310             if (!rc)
0311                 rc = ima_get_cache_status(iint, func);
0312         }
0313         goto out_locked;
0314     }
0315 
0316     if ((action & IMA_APPRAISE_SUBMASK) ||
0317         strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) != 0) {
0318         /* read 'security.ima' */
0319         xattr_len = ima_read_xattr(file_dentry(file), &xattr_value);
0320 
0321         /*
0322          * Read the appended modsig if allowed by the policy, and allow
0323          * an additional measurement list entry, if needed, based on the
0324          * template format and whether the file was already measured.
0325          */
0326         if (iint->flags & IMA_MODSIG_ALLOWED) {
0327             rc = ima_read_modsig(func, buf, size, &modsig);
0328 
0329             if (!rc && ima_template_has_modsig(template_desc) &&
0330                 iint->flags & IMA_MEASURED)
0331                 action |= IMA_MEASURE;
0332         }
0333     }
0334 
0335     hash_algo = ima_get_hash_algo(xattr_value, xattr_len);
0336 
0337     rc = ima_collect_measurement(iint, file, buf, size, hash_algo, modsig);
0338     if (rc == -ENOMEM)
0339         goto out_locked;
0340 
0341     if (!pathbuf)   /* ima_rdwr_violation possibly pre-fetched */
0342         pathname = ima_d_path(&file->f_path, &pathbuf, filename);
0343 
0344     if (action & IMA_MEASURE)
0345         ima_store_measurement(iint, file, pathname,
0346                       xattr_value, xattr_len, modsig, pcr,
0347                       template_desc);
0348     if (rc == 0 && (action & IMA_APPRAISE_SUBMASK)) {
0349         rc = ima_check_blacklist(iint, modsig, pcr);
0350         if (rc != -EPERM) {
0351             inode_lock(inode);
0352             rc = ima_appraise_measurement(func, iint, file,
0353                               pathname, xattr_value,
0354                               xattr_len, modsig);
0355             inode_unlock(inode);
0356         }
0357         if (!rc)
0358             rc = mmap_violation_check(func, file, &pathbuf,
0359                           &pathname, filename);
0360     }
0361     if (action & IMA_AUDIT)
0362         ima_audit_measurement(iint, pathname);
0363 
0364     if ((file->f_flags & O_DIRECT) && (iint->flags & IMA_PERMIT_DIRECTIO))
0365         rc = 0;
0366 
0367     /* Ensure the digest was generated using an allowed algorithm */
0368     if (rc == 0 && must_appraise && allowed_algos != 0 &&
0369         (allowed_algos & (1U << hash_algo)) == 0) {
0370         rc = -EACCES;
0371 
0372         integrity_audit_msg(AUDIT_INTEGRITY_DATA, file_inode(file),
0373                     pathname, "collect_data",
0374                     "denied-hash-algorithm", rc, 0);
0375     }
0376 out_locked:
0377     if ((mask & MAY_WRITE) && test_bit(IMA_DIGSIG, &iint->atomic_flags) &&
0378          !(iint->flags & IMA_NEW_FILE))
0379         rc = -EACCES;
0380     mutex_unlock(&iint->mutex);
0381     kfree(xattr_value);
0382     ima_free_modsig(modsig);
0383 out:
0384     if (pathbuf)
0385         __putname(pathbuf);
0386     if (must_appraise) {
0387         if (rc && (ima_appraise & IMA_APPRAISE_ENFORCE))
0388             return -EACCES;
0389         if (file->f_mode & FMODE_WRITE)
0390             set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
0391     }
0392     return 0;
0393 }
0394 
0395 /**
0396  * ima_file_mmap - based on policy, collect/store measurement.
0397  * @file: pointer to the file to be measured (May be NULL)
0398  * @prot: contains the protection that will be applied by the kernel.
0399  *
0400  * Measure files being mmapped executable based on the ima_must_measure()
0401  * policy decision.
0402  *
0403  * On success return 0.  On integrity appraisal error, assuming the file
0404  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
0405  */
0406 int ima_file_mmap(struct file *file, unsigned long prot)
0407 {
0408     u32 secid;
0409 
0410     if (file && (prot & PROT_EXEC)) {
0411         security_current_getsecid_subj(&secid);
0412         return process_measurement(file, current_cred(), secid, NULL,
0413                        0, MAY_EXEC, MMAP_CHECK);
0414     }
0415 
0416     return 0;
0417 }
0418 
0419 /**
0420  * ima_file_mprotect - based on policy, limit mprotect change
0421  * @vma: vm_area_struct protection is set to
0422  * @prot: contains the protection that will be applied by the kernel.
0423  *
0424  * Files can be mmap'ed read/write and later changed to execute to circumvent
0425  * IMA's mmap appraisal policy rules.  Due to locking issues (mmap semaphore
0426  * would be taken before i_mutex), files can not be measured or appraised at
0427  * this point.  Eliminate this integrity gap by denying the mprotect
0428  * PROT_EXECUTE change, if an mmap appraise policy rule exists.
0429  *
0430  * On mprotect change success, return 0.  On failure, return -EACESS.
0431  */
0432 int ima_file_mprotect(struct vm_area_struct *vma, unsigned long prot)
0433 {
0434     struct ima_template_desc *template = NULL;
0435     struct file *file;
0436     char filename[NAME_MAX];
0437     char *pathbuf = NULL;
0438     const char *pathname = NULL;
0439     struct inode *inode;
0440     int result = 0;
0441     int action;
0442     u32 secid;
0443     int pcr;
0444 
0445     /* Is mprotect making an mmap'ed file executable? */
0446     if (!(ima_policy_flag & IMA_APPRAISE) || !vma->vm_file ||
0447         !(prot & PROT_EXEC) || (vma->vm_flags & VM_EXEC))
0448         return 0;
0449 
0450     security_current_getsecid_subj(&secid);
0451     inode = file_inode(vma->vm_file);
0452     action = ima_get_action(file_mnt_user_ns(vma->vm_file), inode,
0453                 current_cred(), secid, MAY_EXEC, MMAP_CHECK,
0454                 &pcr, &template, NULL, NULL);
0455 
0456     /* Is the mmap'ed file in policy? */
0457     if (!(action & (IMA_MEASURE | IMA_APPRAISE_SUBMASK)))
0458         return 0;
0459 
0460     if (action & IMA_APPRAISE_SUBMASK)
0461         result = -EPERM;
0462 
0463     file = vma->vm_file;
0464     pathname = ima_d_path(&file->f_path, &pathbuf, filename);
0465     integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, pathname,
0466                 "collect_data", "failed-mprotect", result, 0);
0467     if (pathbuf)
0468         __putname(pathbuf);
0469 
0470     return result;
0471 }
0472 
0473 /**
0474  * ima_bprm_check - based on policy, collect/store measurement.
0475  * @bprm: contains the linux_binprm structure
0476  *
0477  * The OS protects against an executable file, already open for write,
0478  * from being executed in deny_write_access() and an executable file,
0479  * already open for execute, from being modified in get_write_access().
0480  * So we can be certain that what we verify and measure here is actually
0481  * what is being executed.
0482  *
0483  * On success return 0.  On integrity appraisal error, assuming the file
0484  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
0485  */
0486 int ima_bprm_check(struct linux_binprm *bprm)
0487 {
0488     int ret;
0489     u32 secid;
0490 
0491     security_current_getsecid_subj(&secid);
0492     ret = process_measurement(bprm->file, current_cred(), secid, NULL, 0,
0493                   MAY_EXEC, BPRM_CHECK);
0494     if (ret)
0495         return ret;
0496 
0497     security_cred_getsecid(bprm->cred, &secid);
0498     return process_measurement(bprm->file, bprm->cred, secid, NULL, 0,
0499                    MAY_EXEC, CREDS_CHECK);
0500 }
0501 
0502 /**
0503  * ima_file_check - based on policy, collect/store measurement.
0504  * @file: pointer to the file to be measured
0505  * @mask: contains MAY_READ, MAY_WRITE, MAY_EXEC or MAY_APPEND
0506  *
0507  * Measure files based on the ima_must_measure() policy decision.
0508  *
0509  * On success return 0.  On integrity appraisal error, assuming the file
0510  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
0511  */
0512 int ima_file_check(struct file *file, int mask)
0513 {
0514     u32 secid;
0515 
0516     security_current_getsecid_subj(&secid);
0517     return process_measurement(file, current_cred(), secid, NULL, 0,
0518                    mask & (MAY_READ | MAY_WRITE | MAY_EXEC |
0519                        MAY_APPEND), FILE_CHECK);
0520 }
0521 EXPORT_SYMBOL_GPL(ima_file_check);
0522 
0523 static int __ima_inode_hash(struct inode *inode, struct file *file, char *buf,
0524                 size_t buf_size)
0525 {
0526     struct integrity_iint_cache *iint = NULL, tmp_iint;
0527     int rc, hash_algo;
0528 
0529     if (ima_policy_flag) {
0530         iint = integrity_iint_find(inode);
0531         if (iint)
0532             mutex_lock(&iint->mutex);
0533     }
0534 
0535     if ((!iint || !(iint->flags & IMA_COLLECTED)) && file) {
0536         if (iint)
0537             mutex_unlock(&iint->mutex);
0538 
0539         memset(&tmp_iint, 0, sizeof(tmp_iint));
0540         tmp_iint.inode = inode;
0541         mutex_init(&tmp_iint.mutex);
0542 
0543         rc = ima_collect_measurement(&tmp_iint, file, NULL, 0,
0544                          ima_hash_algo, NULL);
0545         if (rc < 0)
0546             return -EOPNOTSUPP;
0547 
0548         iint = &tmp_iint;
0549         mutex_lock(&iint->mutex);
0550     }
0551 
0552     if (!iint)
0553         return -EOPNOTSUPP;
0554 
0555     /*
0556      * ima_file_hash can be called when ima_collect_measurement has still
0557      * not been called, we might not always have a hash.
0558      */
0559     if (!iint->ima_hash) {
0560         mutex_unlock(&iint->mutex);
0561         return -EOPNOTSUPP;
0562     }
0563 
0564     if (buf) {
0565         size_t copied_size;
0566 
0567         copied_size = min_t(size_t, iint->ima_hash->length, buf_size);
0568         memcpy(buf, iint->ima_hash->digest, copied_size);
0569     }
0570     hash_algo = iint->ima_hash->algo;
0571     mutex_unlock(&iint->mutex);
0572 
0573     if (iint == &tmp_iint)
0574         kfree(iint->ima_hash);
0575 
0576     return hash_algo;
0577 }
0578 
0579 /**
0580  * ima_file_hash - return a measurement of the file
0581  * @file: pointer to the file
0582  * @buf: buffer in which to store the hash
0583  * @buf_size: length of the buffer
0584  *
0585  * On success, return the hash algorithm (as defined in the enum hash_algo).
0586  * If buf is not NULL, this function also outputs the hash into buf.
0587  * If the hash is larger than buf_size, then only buf_size bytes will be copied.
0588  * It generally just makes sense to pass a buffer capable of holding the largest
0589  * possible hash: IMA_MAX_DIGEST_SIZE.
0590  * The file hash returned is based on the entire file, including the appended
0591  * signature.
0592  *
0593  * If the measurement cannot be performed, return -EOPNOTSUPP.
0594  * If the parameters are incorrect, return -EINVAL.
0595  */
0596 int ima_file_hash(struct file *file, char *buf, size_t buf_size)
0597 {
0598     if (!file)
0599         return -EINVAL;
0600 
0601     return __ima_inode_hash(file_inode(file), file, buf, buf_size);
0602 }
0603 EXPORT_SYMBOL_GPL(ima_file_hash);
0604 
0605 /**
0606  * ima_inode_hash - return the stored measurement if the inode has been hashed
0607  * and is in the iint cache.
0608  * @inode: pointer to the inode
0609  * @buf: buffer in which to store the hash
0610  * @buf_size: length of the buffer
0611  *
0612  * On success, return the hash algorithm (as defined in the enum hash_algo).
0613  * If buf is not NULL, this function also outputs the hash into buf.
0614  * If the hash is larger than buf_size, then only buf_size bytes will be copied.
0615  * It generally just makes sense to pass a buffer capable of holding the largest
0616  * possible hash: IMA_MAX_DIGEST_SIZE.
0617  * The hash returned is based on the entire contents, including the appended
0618  * signature.
0619  *
0620  * If IMA is disabled or if no measurement is available, return -EOPNOTSUPP.
0621  * If the parameters are incorrect, return -EINVAL.
0622  */
0623 int ima_inode_hash(struct inode *inode, char *buf, size_t buf_size)
0624 {
0625     if (!inode)
0626         return -EINVAL;
0627 
0628     return __ima_inode_hash(inode, NULL, buf, buf_size);
0629 }
0630 EXPORT_SYMBOL_GPL(ima_inode_hash);
0631 
0632 /**
0633  * ima_post_create_tmpfile - mark newly created tmpfile as new
0634  * @mnt_userns: user namespace of the mount the inode was found from
0635  * @inode: inode of the newly created tmpfile
0636  *
0637  * No measuring, appraising or auditing of newly created tmpfiles is needed.
0638  * Skip calling process_measurement(), but indicate which newly, created
0639  * tmpfiles are in policy.
0640  */
0641 void ima_post_create_tmpfile(struct user_namespace *mnt_userns,
0642                  struct inode *inode)
0643 {
0644     struct integrity_iint_cache *iint;
0645     int must_appraise;
0646 
0647     if (!ima_policy_flag || !S_ISREG(inode->i_mode))
0648         return;
0649 
0650     must_appraise = ima_must_appraise(mnt_userns, inode, MAY_ACCESS,
0651                       FILE_CHECK);
0652     if (!must_appraise)
0653         return;
0654 
0655     /* Nothing to do if we can't allocate memory */
0656     iint = integrity_inode_get(inode);
0657     if (!iint)
0658         return;
0659 
0660     /* needed for writing the security xattrs */
0661     set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
0662     iint->ima_file_status = INTEGRITY_PASS;
0663 }
0664 
0665 /**
0666  * ima_post_path_mknod - mark as a new inode
0667  * @mnt_userns: user namespace of the mount the inode was found from
0668  * @dentry: newly created dentry
0669  *
0670  * Mark files created via the mknodat syscall as new, so that the
0671  * file data can be written later.
0672  */
0673 void ima_post_path_mknod(struct user_namespace *mnt_userns,
0674              struct dentry *dentry)
0675 {
0676     struct integrity_iint_cache *iint;
0677     struct inode *inode = dentry->d_inode;
0678     int must_appraise;
0679 
0680     if (!ima_policy_flag || !S_ISREG(inode->i_mode))
0681         return;
0682 
0683     must_appraise = ima_must_appraise(mnt_userns, inode, MAY_ACCESS,
0684                       FILE_CHECK);
0685     if (!must_appraise)
0686         return;
0687 
0688     /* Nothing to do if we can't allocate memory */
0689     iint = integrity_inode_get(inode);
0690     if (!iint)
0691         return;
0692 
0693     /* needed for re-opening empty files */
0694     iint->flags |= IMA_NEW_FILE;
0695 }
0696 
0697 /**
0698  * ima_read_file - pre-measure/appraise hook decision based on policy
0699  * @file: pointer to the file to be measured/appraised/audit
0700  * @read_id: caller identifier
0701  * @contents: whether a subsequent call will be made to ima_post_read_file()
0702  *
0703  * Permit reading a file based on policy. The policy rules are written
0704  * in terms of the policy identifier.  Appraising the integrity of
0705  * a file requires a file descriptor.
0706  *
0707  * For permission return 0, otherwise return -EACCES.
0708  */
0709 int ima_read_file(struct file *file, enum kernel_read_file_id read_id,
0710           bool contents)
0711 {
0712     enum ima_hooks func;
0713     u32 secid;
0714 
0715     /*
0716      * Do devices using pre-allocated memory run the risk of the
0717      * firmware being accessible to the device prior to the completion
0718      * of IMA's signature verification any more than when using two
0719      * buffers? It may be desirable to include the buffer address
0720      * in this API and walk all the dma_map_single() mappings to check.
0721      */
0722 
0723     /*
0724      * There will be a call made to ima_post_read_file() with
0725      * a filled buffer, so we don't need to perform an extra
0726      * read early here.
0727      */
0728     if (contents)
0729         return 0;
0730 
0731     /* Read entire file for all partial reads. */
0732     func = read_idmap[read_id] ?: FILE_CHECK;
0733     security_current_getsecid_subj(&secid);
0734     return process_measurement(file, current_cred(), secid, NULL,
0735                    0, MAY_READ, func);
0736 }
0737 
0738 const int read_idmap[READING_MAX_ID] = {
0739     [READING_FIRMWARE] = FIRMWARE_CHECK,
0740     [READING_MODULE] = MODULE_CHECK,
0741     [READING_KEXEC_IMAGE] = KEXEC_KERNEL_CHECK,
0742     [READING_KEXEC_INITRAMFS] = KEXEC_INITRAMFS_CHECK,
0743     [READING_POLICY] = POLICY_CHECK
0744 };
0745 
0746 /**
0747  * ima_post_read_file - in memory collect/appraise/audit measurement
0748  * @file: pointer to the file to be measured/appraised/audit
0749  * @buf: pointer to in memory file contents
0750  * @size: size of in memory file contents
0751  * @read_id: caller identifier
0752  *
0753  * Measure/appraise/audit in memory file based on policy.  Policy rules
0754  * are written in terms of a policy identifier.
0755  *
0756  * On success return 0.  On integrity appraisal error, assuming the file
0757  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
0758  */
0759 int ima_post_read_file(struct file *file, void *buf, loff_t size,
0760                enum kernel_read_file_id read_id)
0761 {
0762     enum ima_hooks func;
0763     u32 secid;
0764 
0765     /* permit signed certs */
0766     if (!file && read_id == READING_X509_CERTIFICATE)
0767         return 0;
0768 
0769     if (!file || !buf || size == 0) { /* should never happen */
0770         if (ima_appraise & IMA_APPRAISE_ENFORCE)
0771             return -EACCES;
0772         return 0;
0773     }
0774 
0775     func = read_idmap[read_id] ?: FILE_CHECK;
0776     security_current_getsecid_subj(&secid);
0777     return process_measurement(file, current_cred(), secid, buf, size,
0778                    MAY_READ, func);
0779 }
0780 
0781 /**
0782  * ima_load_data - appraise decision based on policy
0783  * @id: kernel load data caller identifier
0784  * @contents: whether the full contents will be available in a later
0785  *        call to ima_post_load_data().
0786  *
0787  * Callers of this LSM hook can not measure, appraise, or audit the
0788  * data provided by userspace.  Enforce policy rules requiring a file
0789  * signature (eg. kexec'ed kernel image).
0790  *
0791  * For permission return 0, otherwise return -EACCES.
0792  */
0793 int ima_load_data(enum kernel_load_data_id id, bool contents)
0794 {
0795     bool ima_enforce, sig_enforce;
0796 
0797     ima_enforce =
0798         (ima_appraise & IMA_APPRAISE_ENFORCE) == IMA_APPRAISE_ENFORCE;
0799 
0800     switch (id) {
0801     case LOADING_KEXEC_IMAGE:
0802         if (IS_ENABLED(CONFIG_KEXEC_SIG)
0803             && arch_ima_get_secureboot()) {
0804             pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
0805             return -EACCES;
0806         }
0807 
0808         if (ima_enforce && (ima_appraise & IMA_APPRAISE_KEXEC)) {
0809             pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
0810             return -EACCES; /* INTEGRITY_UNKNOWN */
0811         }
0812         break;
0813     case LOADING_FIRMWARE:
0814         if (ima_enforce && (ima_appraise & IMA_APPRAISE_FIRMWARE) && !contents) {
0815             pr_err("Prevent firmware sysfs fallback loading.\n");
0816             return -EACCES; /* INTEGRITY_UNKNOWN */
0817         }
0818         break;
0819     case LOADING_MODULE:
0820         sig_enforce = is_module_sig_enforced();
0821 
0822         if (ima_enforce && (!sig_enforce
0823                     && (ima_appraise & IMA_APPRAISE_MODULES))) {
0824             pr_err("impossible to appraise a module without a file descriptor. sig_enforce kernel parameter might help\n");
0825             return -EACCES; /* INTEGRITY_UNKNOWN */
0826         }
0827         break;
0828     default:
0829         break;
0830     }
0831     return 0;
0832 }
0833 
0834 /**
0835  * ima_post_load_data - appraise decision based on policy
0836  * @buf: pointer to in memory file contents
0837  * @size: size of in memory file contents
0838  * @load_id: kernel load data caller identifier
0839  * @description: @load_id-specific description of contents
0840  *
0841  * Measure/appraise/audit in memory buffer based on policy.  Policy rules
0842  * are written in terms of a policy identifier.
0843  *
0844  * On success return 0.  On integrity appraisal error, assuming the file
0845  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
0846  */
0847 int ima_post_load_data(char *buf, loff_t size,
0848                enum kernel_load_data_id load_id,
0849                char *description)
0850 {
0851     if (load_id == LOADING_FIRMWARE) {
0852         if ((ima_appraise & IMA_APPRAISE_FIRMWARE) &&
0853             (ima_appraise & IMA_APPRAISE_ENFORCE)) {
0854             pr_err("Prevent firmware loading_store.\n");
0855             return -EACCES; /* INTEGRITY_UNKNOWN */
0856         }
0857         return 0;
0858     }
0859 
0860     return 0;
0861 }
0862 
0863 /**
0864  * process_buffer_measurement - Measure the buffer or the buffer data hash
0865  * @mnt_userns: user namespace of the mount the inode was found from
0866  * @inode: inode associated with the object being measured (NULL for KEY_CHECK)
0867  * @buf: pointer to the buffer that needs to be added to the log.
0868  * @size: size of buffer(in bytes).
0869  * @eventname: event name to be used for the buffer entry.
0870  * @func: IMA hook
0871  * @pcr: pcr to extend the measurement
0872  * @func_data: func specific data, may be NULL
0873  * @buf_hash: measure buffer data hash
0874  * @digest: buffer digest will be written to
0875  * @digest_len: buffer length
0876  *
0877  * Based on policy, either the buffer data or buffer data hash is measured
0878  *
0879  * Return: 0 if the buffer has been successfully measured, 1 if the digest
0880  * has been written to the passed location but not added to a measurement entry,
0881  * a negative value otherwise.
0882  */
0883 int process_buffer_measurement(struct user_namespace *mnt_userns,
0884                    struct inode *inode, const void *buf, int size,
0885                    const char *eventname, enum ima_hooks func,
0886                    int pcr, const char *func_data,
0887                    bool buf_hash, u8 *digest, size_t digest_len)
0888 {
0889     int ret = 0;
0890     const char *audit_cause = "ENOMEM";
0891     struct ima_template_entry *entry = NULL;
0892     struct integrity_iint_cache iint = {};
0893     struct ima_event_data event_data = {.iint = &iint,
0894                         .filename = eventname,
0895                         .buf = buf,
0896                         .buf_len = size};
0897     struct ima_template_desc *template;
0898     struct ima_max_digest_data hash;
0899     char digest_hash[IMA_MAX_DIGEST_SIZE];
0900     int digest_hash_len = hash_digest_size[ima_hash_algo];
0901     int violation = 0;
0902     int action = 0;
0903     u32 secid;
0904 
0905     if (digest && digest_len < digest_hash_len)
0906         return -EINVAL;
0907 
0908     if (!ima_policy_flag && !digest)
0909         return -ENOENT;
0910 
0911     template = ima_template_desc_buf();
0912     if (!template) {
0913         ret = -EINVAL;
0914         audit_cause = "ima_template_desc_buf";
0915         goto out;
0916     }
0917 
0918     /*
0919      * Both LSM hooks and auxilary based buffer measurements are
0920      * based on policy.  To avoid code duplication, differentiate
0921      * between the LSM hooks and auxilary buffer measurements,
0922      * retrieving the policy rule information only for the LSM hook
0923      * buffer measurements.
0924      */
0925     if (func) {
0926         security_current_getsecid_subj(&secid);
0927         action = ima_get_action(mnt_userns, inode, current_cred(),
0928                     secid, 0, func, &pcr, &template,
0929                     func_data, NULL);
0930         if (!(action & IMA_MEASURE) && !digest)
0931             return -ENOENT;
0932     }
0933 
0934     if (!pcr)
0935         pcr = CONFIG_IMA_MEASURE_PCR_IDX;
0936 
0937     iint.ima_hash = &hash.hdr;
0938     iint.ima_hash->algo = ima_hash_algo;
0939     iint.ima_hash->length = hash_digest_size[ima_hash_algo];
0940 
0941     ret = ima_calc_buffer_hash(buf, size, iint.ima_hash);
0942     if (ret < 0) {
0943         audit_cause = "hashing_error";
0944         goto out;
0945     }
0946 
0947     if (buf_hash) {
0948         memcpy(digest_hash, hash.hdr.digest, digest_hash_len);
0949 
0950         ret = ima_calc_buffer_hash(digest_hash, digest_hash_len,
0951                        iint.ima_hash);
0952         if (ret < 0) {
0953             audit_cause = "hashing_error";
0954             goto out;
0955         }
0956 
0957         event_data.buf = digest_hash;
0958         event_data.buf_len = digest_hash_len;
0959     }
0960 
0961     if (digest)
0962         memcpy(digest, iint.ima_hash->digest, digest_hash_len);
0963 
0964     if (!ima_policy_flag || (func && !(action & IMA_MEASURE)))
0965         return 1;
0966 
0967     ret = ima_alloc_init_template(&event_data, &entry, template);
0968     if (ret < 0) {
0969         audit_cause = "alloc_entry";
0970         goto out;
0971     }
0972 
0973     ret = ima_store_template(entry, violation, NULL, event_data.buf, pcr);
0974     if (ret < 0) {
0975         audit_cause = "store_entry";
0976         ima_free_template_entry(entry);
0977     }
0978 
0979 out:
0980     if (ret < 0)
0981         integrity_audit_message(AUDIT_INTEGRITY_PCR, NULL, eventname,
0982                     func_measure_str(func),
0983                     audit_cause, ret, 0, ret);
0984 
0985     return ret;
0986 }
0987 
0988 /**
0989  * ima_kexec_cmdline - measure kexec cmdline boot args
0990  * @kernel_fd: file descriptor of the kexec kernel being loaded
0991  * @buf: pointer to buffer
0992  * @size: size of buffer
0993  *
0994  * Buffers can only be measured, not appraised.
0995  */
0996 void ima_kexec_cmdline(int kernel_fd, const void *buf, int size)
0997 {
0998     struct fd f;
0999 
1000     if (!buf || !size)
1001         return;
1002 
1003     f = fdget(kernel_fd);
1004     if (!f.file)
1005         return;
1006 
1007     process_buffer_measurement(file_mnt_user_ns(f.file), file_inode(f.file),
1008                    buf, size, "kexec-cmdline", KEXEC_CMDLINE, 0,
1009                    NULL, false, NULL, 0);
1010     fdput(f);
1011 }
1012 
1013 /**
1014  * ima_measure_critical_data - measure kernel integrity critical data
1015  * @event_label: unique event label for grouping and limiting critical data
1016  * @event_name: event name for the record in the IMA measurement list
1017  * @buf: pointer to buffer data
1018  * @buf_len: length of buffer data (in bytes)
1019  * @hash: measure buffer data hash
1020  * @digest: buffer digest will be written to
1021  * @digest_len: buffer length
1022  *
1023  * Measure data critical to the integrity of the kernel into the IMA log
1024  * and extend the pcr.  Examples of critical data could be various data
1025  * structures, policies, and states stored in kernel memory that can
1026  * impact the integrity of the system.
1027  *
1028  * Return: 0 if the buffer has been successfully measured, 1 if the digest
1029  * has been written to the passed location but not added to a measurement entry,
1030  * a negative value otherwise.
1031  */
1032 int ima_measure_critical_data(const char *event_label,
1033                   const char *event_name,
1034                   const void *buf, size_t buf_len,
1035                   bool hash, u8 *digest, size_t digest_len)
1036 {
1037     if (!event_name || !event_label || !buf || !buf_len)
1038         return -ENOPARAM;
1039 
1040     return process_buffer_measurement(&init_user_ns, NULL, buf, buf_len,
1041                       event_name, CRITICAL_DATA, 0,
1042                       event_label, hash, digest,
1043                       digest_len);
1044 }
1045 EXPORT_SYMBOL_GPL(ima_measure_critical_data);
1046 
1047 static int __init init_ima(void)
1048 {
1049     int error;
1050 
1051     ima_appraise_parse_cmdline();
1052     ima_init_template_list();
1053     hash_setup(CONFIG_IMA_DEFAULT_HASH);
1054     error = ima_init();
1055 
1056     if (error && strcmp(hash_algo_name[ima_hash_algo],
1057                 CONFIG_IMA_DEFAULT_HASH) != 0) {
1058         pr_info("Allocating %s failed, going to use default hash algorithm %s\n",
1059             hash_algo_name[ima_hash_algo], CONFIG_IMA_DEFAULT_HASH);
1060         hash_setup_done = 0;
1061         hash_setup(CONFIG_IMA_DEFAULT_HASH);
1062         error = ima_init();
1063     }
1064 
1065     if (error)
1066         return error;
1067 
1068     error = register_blocking_lsm_notifier(&ima_lsm_policy_notifier);
1069     if (error)
1070         pr_warn("Couldn't register LSM notifier, error %d\n", error);
1071 
1072     if (!error)
1073         ima_update_policy_flags();
1074 
1075     return error;
1076 }
1077 
1078 late_initcall(init_ima);    /* Start IMA after the TPM is available */