1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * Integrity Measurement Architecture 4 * 5 * Copyright (C) 2005,2006,2007,2008 IBM Corporation 6 * 7 * Authors: 8 * Reiner Sailer <sailer@watson.ibm.com> 9 * Serge Hallyn <serue@us.ibm.com> 10 * Kylene Hall <kylene@us.ibm.com> 11 * Mimi Zohar <zohar@us.ibm.com> 12 * 13 * File: ima_main.c 14 * implements the IMA hooks: ima_bprm_check, ima_file_mmap, 15 * and ima_file_check. 16 */ 17 18 #include <linux/module.h> 19 #include <linux/file.h> 20 #include <linux/binfmts.h> 21 #include <linux/kernel_read_file.h> 22 #include <linux/mount.h> 23 #include <linux/mman.h> 24 #include <linux/slab.h> 25 #include <linux/xattr.h> 26 #include <linux/ima.h> 27 #include <linux/fs.h> 28 #include <linux/iversion.h> 29 #include <linux/evm.h> 30 31 #include "ima.h" 32 33 #ifdef CONFIG_IMA_APPRAISE 34 int ima_appraise = IMA_APPRAISE_ENFORCE; 35 #else 36 int ima_appraise; 37 #endif 38 39 int __ro_after_init ima_hash_algo = HASH_ALGO_SHA1; 40 static int hash_setup_done; 41 42 static struct notifier_block ima_lsm_policy_notifier = { 43 .notifier_call = ima_lsm_policy_change, 44 }; 45 46 static int __init hash_setup(char *str) 47 { 48 struct ima_template_desc *template_desc = ima_template_desc_current(); 49 int i; 50 51 if (hash_setup_done) 52 return 1; 53 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; 59 } else { 60 pr_err("invalid hash algorithm \"%s\" for template \"%s\"", 61 str, IMA_TEMPLATE_IMA_NAME); 62 return 1; 63 } 64 goto out; 65 } 66 67 i = match_string(hash_algo_name, HASH_ALGO__LAST, str); 68 if (i < 0) { 69 pr_err("invalid hash algorithm \"%s\"", str); 70 return 1; 71 } 72 73 ima_hash_algo = i; 74 out: 75 hash_setup_done = 1; 76 return 1; 77 } 78 __setup("ima_hash=", hash_setup); 79 80 enum hash_algo ima_get_current_hash_algo(void) 81 { 82 return ima_hash_algo; 83 } 84 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, 88 char *filename) 89 { 90 struct inode *inode; 91 int rc = 0; 92 93 if ((func == MMAP_CHECK || func == MMAP_CHECK_REQPROT) && 94 mapping_writably_mapped(file->f_mapping)) { 95 rc = -ETXTBSY; 96 inode = file_inode(file); 97 98 if (!*pathbuf) /* ima_rdwr_violation possibly pre-fetched */ 99 *pathname = ima_d_path(&file->f_path, pathbuf, 100 filename); 101 integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, *pathname, 102 "mmap_file", "mmapped_writers", rc, 0); 103 } 104 return rc; 105 } 106 107 /* 108 * ima_rdwr_violation_check 109 * 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. 115 * 116 */ 117 static void ima_rdwr_violation_check(struct file *file, 118 struct ima_iint_cache *iint, 119 int must_measure, 120 char **pathbuf, 121 const char **pathname, 122 char *filename) 123 { 124 struct inode *inode = file_inode(file); 125 fmode_t mode = file->f_mode; 126 bool send_tomtou = false, send_writers = false; 127 128 if (mode & FMODE_WRITE) { 129 if (atomic_read(&inode->i_readcount) && IS_IMA(inode)) { 130 if (!iint) 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)) 135 send_tomtou = true; 136 } 137 } else { 138 if (must_measure) 139 set_bit(IMA_MUST_MEASURE, &iint->atomic_flags); 140 if (inode_is_open_for_write(inode) && must_measure) 141 send_writers = true; 142 } 143 144 if (!send_tomtou && !send_writers) 145 return; 146 147 *pathname = ima_d_path(&file->f_path, pathbuf, filename); 148 149 if (send_tomtou) 150 ima_add_violation(file, *pathname, iint, 151 "invalid_pcr", "ToMToU"); 152 if (send_writers) 153 ima_add_violation(file, *pathname, iint, 154 "invalid_pcr", "open_writers"); 155 } 156 157 static void ima_check_last_writer(struct ima_iint_cache *iint, 158 struct inode *inode, struct file *file) 159 { 160 fmode_t mode = file->f_mode; 161 bool update; 162 163 if (!(mode & FMODE_WRITE)) 164 return; 165 166 mutex_lock(&iint->mutex); 167 if (atomic_read(&inode->i_writecount) == 1) { 168 struct kstat stat; 169 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, 174 STATX_CHANGE_COOKIE, 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; 180 if (update) 181 ima_update_xattr(iint, file); 182 } 183 } 184 mutex_unlock(&iint->mutex); 185 } 186 187 /** 188 * ima_file_free - called on __fput() 189 * @file: pointer to file structure being freed 190 * 191 * Flag files that changed, based on i_version 192 */ 193 static void ima_file_free(struct file *file) 194 { 195 struct inode *inode = file_inode(file); 196 struct ima_iint_cache *iint; 197 198 if (!ima_policy_flag || !S_ISREG(inode->i_mode)) 199 return; 200 201 iint = ima_iint_find(inode); 202 if (!iint) 203 return; 204 205 ima_check_last_writer(iint, inode, file); 206 } 207 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) 211 { 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; 223 int xattr_len = 0; 224 bool violation_check; 225 enum hash_algo hash_algo; 226 unsigned int allowed_algos = 0; 227 228 if (!ima_policy_flag || !S_ISREG(inode->i_mode)) 229 return 0; 230 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. 234 */ 235 action = ima_get_action(file_mnt_idmap(file), inode, cred, prop, 236 mask, func, &pcr, &template_desc, NULL, 237 &allowed_algos); 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) 242 return 0; 243 244 must_appraise = action & IMA_APPRAISE; 245 246 /* Is the appraise rule hook specific? */ 247 if (action & IMA_FILE_APPRAISE) 248 func = FILE_CHECK; 249 250 inode_lock(inode); 251 252 if (action) { 253 iint = ima_inode_get(inode); 254 if (!iint) 255 rc = -ENOMEM; 256 } 257 258 if (!rc && violation_check) 259 ima_rdwr_violation_check(file, iint, action & IMA_MEASURE, 260 &pathbuf, &pathname, filename); 261 262 inode_unlock(inode); 263 264 if (rc) 265 goto out; 266 if (!action) 267 goto out; 268 269 mutex_lock(&iint->mutex); 270 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); 276 277 /* 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.) 281 */ 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; 288 } 289 290 /* 291 * On stacked filesystems, detect and re-evaluate file data and 292 * metadata changes. 293 */ 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, 299 real_inode)) { 300 iint->flags &= ~IMA_DONE_MASK; 301 iint->measured_pcrs = 0; 302 } 303 304 /* 305 * Reset the EVM status when metadata changed. 306 */ 307 metadata_inode = d_inode(d_real(file_dentry(file), 308 D_REAL_METADATA)); 309 if (evm_metadata_changed(inode, metadata_inode)) 310 iint->flags &= ~(IMA_APPRAISED | 311 IMA_APPRAISED_SUBMASK); 312 } 313 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) 317 */ 318 iint->flags |= action; 319 action &= IMA_DO_MASK; 320 action &= ~((iint->flags & (IMA_DONE_MASK ^ IMA_MEASURED)) >> 1); 321 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; 325 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; 335 action ^= IMA_HASH; 336 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags); 337 } 338 339 /* Nothing to do, just return existing appraised status */ 340 if (!action) { 341 if (must_appraise) { 342 rc = mmap_violation_check(func, file, &pathbuf, 343 &pathname, filename); 344 if (!rc) 345 rc = ima_get_cache_status(iint, func); 346 } 347 goto out_locked; 348 } 349 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); 355 356 /* 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. 360 */ 361 if (iint->flags & IMA_MODSIG_ALLOWED) { 362 rc = ima_read_modsig(func, buf, size, &modsig); 363 364 if (!rc && ima_template_has_modsig(template_desc) && 365 iint->flags & IMA_MEASURED) 366 action |= IMA_MEASURE; 367 } 368 } 369 370 hash_algo = ima_get_hash_algo(xattr_value, xattr_len); 371 372 rc = ima_collect_measurement(iint, file, buf, size, hash_algo, modsig); 373 if (rc != 0 && rc != -EBADF && rc != -EINVAL) 374 goto out_locked; 375 376 if (!pathbuf) /* ima_rdwr_violation possibly pre-fetched */ 377 pathname = ima_d_path(&file->f_path, &pathbuf, filename); 378 379 if (action & IMA_MEASURE) 380 ima_store_measurement(iint, file, pathname, 381 xattr_value, xattr_len, modsig, pcr, 382 template_desc); 383 if (rc == 0 && (action & IMA_APPRAISE_SUBMASK)) { 384 rc = ima_check_blacklist(iint, modsig, pcr); 385 if (rc != -EPERM) { 386 inode_lock(inode); 387 rc = ima_appraise_measurement(func, iint, file, 388 pathname, xattr_value, 389 xattr_len, modsig); 390 inode_unlock(inode); 391 } 392 if (!rc) 393 rc = mmap_violation_check(func, file, &pathbuf, 394 &pathname, filename); 395 } 396 if (action & IMA_AUDIT) 397 ima_audit_measurement(iint, pathname); 398 399 if ((file->f_flags & O_DIRECT) && (iint->flags & IMA_PERMIT_DIRECTIO)) 400 rc = 0; 401 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) { 405 rc = -EACCES; 406 407 integrity_audit_msg(AUDIT_INTEGRITY_DATA, file_inode(file), 408 pathname, "collect_data", 409 "denied-hash-algorithm", rc, 0); 410 } 411 out_locked: 412 if ((mask & MAY_WRITE) && test_bit(IMA_DIGSIG, &iint->atomic_flags) && 413 !(iint->flags & IMA_NEW_FILE)) 414 rc = -EACCES; 415 mutex_unlock(&iint->mutex); 416 kfree(xattr_value); 417 ima_free_modsig(modsig); 418 out: 419 if (pathbuf) 420 __putname(pathbuf); 421 if (must_appraise) { 422 if (rc && (ima_appraise & IMA_APPRAISE_ENFORCE)) 423 return -EACCES; 424 if (file->f_mode & FMODE_WRITE) 425 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags); 426 } 427 return 0; 428 } 429 430 /** 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 436 * 437 * Measure files being mmapped executable based on the ima_must_measure() 438 * policy decision. 439 * 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. 442 */ 443 static int ima_file_mmap(struct file *file, unsigned long reqprot, 444 unsigned long prot, unsigned long flags) 445 { 446 struct lsm_prop prop; 447 int ret; 448 449 if (!file) 450 return 0; 451 452 security_current_getlsmprop_subj(&prop); 453 454 if (reqprot & PROT_EXEC) { 455 ret = process_measurement(file, current_cred(), &prop, NULL, 456 0, MAY_EXEC, MMAP_CHECK_REQPROT); 457 if (ret) 458 return ret; 459 } 460 461 if (prot & PROT_EXEC) 462 return process_measurement(file, current_cred(), &prop, NULL, 463 0, MAY_EXEC, MMAP_CHECK); 464 465 return 0; 466 } 467 468 /** 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 473 * 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. 479 * 480 * On mprotect change success, return 0. On failure, return -EACESS. 481 */ 482 static int ima_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot, 483 unsigned long prot) 484 { 485 struct ima_template_desc *template = NULL; 486 struct file *file; 487 char filename[NAME_MAX]; 488 char *pathbuf = NULL; 489 const char *pathname = NULL; 490 struct inode *inode; 491 struct lsm_prop prop; 492 int result = 0; 493 int action; 494 int pcr; 495 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)) 499 return 0; 500 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, 509 NULL); 510 511 /* Is the mmap'ed file in policy? */ 512 if (!(action & (IMA_MEASURE | IMA_APPRAISE_SUBMASK))) 513 return 0; 514 515 if (action & IMA_APPRAISE_SUBMASK) 516 result = -EPERM; 517 518 file = vma->vm_file; 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); 522 if (pathbuf) 523 __putname(pathbuf); 524 525 return result; 526 } 527 528 /** 529 * ima_bprm_check - based on policy, collect/store measurement. 530 * @bprm: contains the linux_binprm structure 531 * 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. 537 * 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. 540 */ 541 static int ima_bprm_check(struct linux_binprm *bprm) 542 { 543 int ret; 544 struct lsm_prop prop; 545 546 security_current_getlsmprop_subj(&prop); 547 ret = process_measurement(bprm->file, current_cred(), 548 &prop, NULL, 0, MAY_EXEC, BPRM_CHECK); 549 if (ret) 550 return ret; 551 552 security_cred_getlsmprop(bprm->cred, &prop); 553 return process_measurement(bprm->file, bprm->cred, &prop, NULL, 0, 554 MAY_EXEC, CREDS_CHECK); 555 } 556 557 /** 558 * ima_bprm_creds_for_exec - collect/store/appraise measurement. 559 * @bprm: contains the linux_binprm structure 560 * 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). 566 * 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. 569 */ 570 static int ima_bprm_creds_for_exec(struct linux_binprm *bprm) 571 { 572 /* 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). 578 */ 579 if (!bprm->is_check) 580 return 0; 581 582 return ima_bprm_check(bprm); 583 } 584 585 /** 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 589 * 590 * Measure files based on the ima_must_measure() policy decision. 591 * 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. 594 */ 595 static int ima_file_check(struct file *file, int mask) 596 { 597 struct lsm_prop prop; 598 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); 603 } 604 605 static int __ima_inode_hash(struct inode *inode, struct file *file, char *buf, 606 size_t buf_size) 607 { 608 struct ima_iint_cache *iint = NULL, tmp_iint; 609 int rc, hash_algo; 610 611 if (ima_policy_flag) { 612 iint = ima_iint_find(inode); 613 if (iint) 614 mutex_lock(&iint->mutex); 615 } 616 617 if ((!iint || !(iint->flags & IMA_COLLECTED)) && file) { 618 if (iint) 619 mutex_unlock(&iint->mutex); 620 621 memset(&tmp_iint, 0, sizeof(tmp_iint)); 622 mutex_init(&tmp_iint.mutex); 623 624 rc = ima_collect_measurement(&tmp_iint, file, NULL, 0, 625 ima_hash_algo, NULL); 626 if (rc < 0) { 627 /* ima_hash could be allocated in case of failure. */ 628 if (rc != -ENOMEM) 629 kfree(tmp_iint.ima_hash); 630 631 return -EOPNOTSUPP; 632 } 633 634 iint = &tmp_iint; 635 mutex_lock(&iint->mutex); 636 } 637 638 if (!iint) 639 return -EOPNOTSUPP; 640 641 /* 642 * ima_file_hash can be called when ima_collect_measurement has still 643 * not been called, we might not always have a hash. 644 */ 645 if (!iint->ima_hash || !(iint->flags & IMA_COLLECTED)) { 646 mutex_unlock(&iint->mutex); 647 return -EOPNOTSUPP; 648 } 649 650 if (buf) { 651 size_t copied_size; 652 653 copied_size = min_t(size_t, iint->ima_hash->length, buf_size); 654 memcpy(buf, iint->ima_hash->digest, copied_size); 655 } 656 hash_algo = iint->ima_hash->algo; 657 mutex_unlock(&iint->mutex); 658 659 if (iint == &tmp_iint) 660 kfree(iint->ima_hash); 661 662 return hash_algo; 663 } 664 665 /** 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 670 * 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 677 * signature. 678 * 679 * If the measurement cannot be performed, return -EOPNOTSUPP. 680 * If the parameters are incorrect, return -EINVAL. 681 */ 682 int ima_file_hash(struct file *file, char *buf, size_t buf_size) 683 { 684 if (!file) 685 return -EINVAL; 686 687 return __ima_inode_hash(file_inode(file), file, buf, buf_size); 688 } 689 EXPORT_SYMBOL_GPL(ima_file_hash); 690 691 /** 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 697 * 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 704 * signature. 705 * 706 * If IMA is disabled or if no measurement is available, return -EOPNOTSUPP. 707 * If the parameters are incorrect, return -EINVAL. 708 */ 709 int ima_inode_hash(struct inode *inode, char *buf, size_t buf_size) 710 { 711 if (!inode) 712 return -EINVAL; 713 714 return __ima_inode_hash(inode, NULL, buf, buf_size); 715 } 716 EXPORT_SYMBOL_GPL(ima_inode_hash); 717 718 /** 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 722 * 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. 726 */ 727 static void ima_post_create_tmpfile(struct mnt_idmap *idmap, 728 struct inode *inode) 729 730 { 731 struct ima_iint_cache *iint; 732 int must_appraise; 733 734 if (!ima_policy_flag || !S_ISREG(inode->i_mode)) 735 return; 736 737 must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS, 738 FILE_CHECK); 739 if (!must_appraise) 740 return; 741 742 /* Nothing to do if we can't allocate memory */ 743 iint = ima_inode_get(inode); 744 if (!iint) 745 return; 746 747 /* needed for writing the security xattrs */ 748 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags); 749 iint->ima_file_status = INTEGRITY_PASS; 750 } 751 752 /** 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 756 * 757 * Mark files created via the mknodat syscall as new, so that the 758 * file data can be written later. 759 */ 760 static void ima_post_path_mknod(struct mnt_idmap *idmap, struct dentry *dentry) 761 { 762 struct ima_iint_cache *iint; 763 struct inode *inode = dentry->d_inode; 764 int must_appraise; 765 766 if (!ima_policy_flag || !S_ISREG(inode->i_mode)) 767 return; 768 769 must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS, 770 FILE_CHECK); 771 if (!must_appraise) 772 return; 773 774 /* Nothing to do if we can't allocate memory */ 775 iint = ima_inode_get(inode); 776 if (!iint) 777 return; 778 779 /* needed for re-opening empty files */ 780 iint->flags |= IMA_NEW_FILE; 781 } 782 783 /** 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() 788 * 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. 792 * 793 * For permission return 0, otherwise return -EACCES. 794 */ 795 static int ima_read_file(struct file *file, enum kernel_read_file_id read_id, 796 bool contents) 797 { 798 enum ima_hooks func; 799 struct lsm_prop prop; 800 801 /* 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. 807 */ 808 809 /* 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 812 * read early here. 813 */ 814 if (contents) 815 return 0; 816 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, 821 MAY_READ, func); 822 } 823 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 830 }; 831 832 /** 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 838 * 839 * Measure/appraise/audit in memory file based on policy. Policy rules 840 * are written in terms of a policy identifier. 841 * 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. 844 */ 845 static int ima_post_read_file(struct file *file, char *buf, loff_t size, 846 enum kernel_read_file_id read_id) 847 { 848 enum ima_hooks func; 849 struct lsm_prop prop; 850 851 /* permit signed certs */ 852 if (!file && read_id == READING_X509_CERTIFICATE) 853 return 0; 854 855 if (!file || !buf || size == 0) { /* should never happen */ 856 if (ima_appraise & IMA_APPRAISE_ENFORCE) 857 return -EACCES; 858 return 0; 859 } 860 861 func = read_idmap[read_id] ?: FILE_CHECK; 862 security_current_getlsmprop_subj(&prop); 863 return process_measurement(file, current_cred(), &prop, buf, size, 864 MAY_READ, func); 865 } 866 867 /** 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(). 872 * 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). 876 * 877 * For permission return 0, otherwise return -EACCES. 878 */ 879 static int ima_load_data(enum kernel_load_data_id id, bool contents) 880 { 881 bool ima_enforce, sig_enforce; 882 883 ima_enforce = 884 (ima_appraise & IMA_APPRAISE_ENFORCE) == IMA_APPRAISE_ENFORCE; 885 886 switch (id) { 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"); 891 return -EACCES; 892 } 893 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 */ 897 } 898 break; 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 */ 903 } 904 break; 905 case LOADING_MODULE: 906 sig_enforce = is_module_sig_enforced(); 907 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 */ 912 } 913 break; 914 default: 915 break; 916 } 917 return 0; 918 } 919 920 /** 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 926 * 927 * Measure/appraise/audit in memory buffer based on policy. Policy rules 928 * are written in terms of a policy identifier. 929 * 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. 932 */ 933 static int ima_post_load_data(char *buf, loff_t size, 934 enum kernel_load_data_id load_id, 935 char *description) 936 { 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 */ 942 } 943 return 0; 944 } 945 946 /* 947 * Measure the init_module syscall buffer containing the ELF image. 948 */ 949 if (load_id == LOADING_MODULE) 950 ima_measure_critical_data("modules", "init_module", 951 buf, size, true, NULL, 0); 952 953 return 0; 954 } 955 956 /** 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. 963 * @func: IMA hook 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 969 * 970 * Based on policy, either the buffer data or buffer data hash is measured 971 * 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. 975 */ 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) 981 { 982 int ret = 0; 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, 988 .buf = buf, 989 .buf_len = size}; 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]; 996 int violation = 0; 997 int action = 0; 998 struct lsm_prop prop; 999 1000 if (digest && digest_len < digest_hash_len) 1001 return -EINVAL; 1002 1003 if (!ima_policy_flag && !digest) 1004 return -ENOENT; 1005 1006 template = ima_template_desc_buf(); 1007 if (!template) { 1008 ret = -EINVAL; 1009 audit_cause = "ima_template_desc_buf"; 1010 goto out; 1011 } 1012 1013 /* 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. 1019 */ 1020 if (func) { 1021 security_current_getlsmprop_subj(&prop); 1022 action = ima_get_action(idmap, inode, current_cred(), 1023 &prop, 0, func, &pcr, &template, 1024 func_data, NULL); 1025 if (!(action & IMA_MEASURE) && !digest) 1026 return -ENOENT; 1027 } 1028 1029 if (!pcr) 1030 pcr = CONFIG_IMA_MEASURE_PCR_IDX; 1031 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]; 1035 1036 ret = ima_calc_buffer_hash(buf, size, iint.ima_hash); 1037 if (ret < 0) { 1038 audit_cause = "hashing_error"; 1039 goto out; 1040 } 1041 1042 if (buf_hash) { 1043 memcpy(digest_hash, hash_hdr->digest, digest_hash_len); 1044 1045 ret = ima_calc_buffer_hash(digest_hash, digest_hash_len, 1046 iint.ima_hash); 1047 if (ret < 0) { 1048 audit_cause = "hashing_error"; 1049 goto out; 1050 } 1051 1052 event_data.buf = digest_hash; 1053 event_data.buf_len = digest_hash_len; 1054 } 1055 1056 if (digest) 1057 memcpy(digest, iint.ima_hash->digest, digest_hash_len); 1058 1059 if (!ima_policy_flag || (func && !(action & IMA_MEASURE))) 1060 return 1; 1061 1062 ret = ima_alloc_init_template(&event_data, &entry, template); 1063 if (ret < 0) { 1064 audit_cause = "alloc_entry"; 1065 goto out; 1066 } 1067 1068 ret = ima_store_template(entry, violation, NULL, event_data.buf, pcr); 1069 if (ret < 0) { 1070 audit_cause = "store_entry"; 1071 ima_free_template_entry(entry); 1072 } 1073 1074 out: 1075 if (ret < 0) 1076 integrity_audit_message(AUDIT_INTEGRITY_PCR, NULL, eventname, 1077 func_measure_str(func), 1078 audit_cause, ret, 0, ret); 1079 1080 return ret; 1081 } 1082 1083 /** 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 1088 * 1089 * Buffers can only be measured, not appraised. 1090 */ 1091 void ima_kexec_cmdline(int kernel_fd, const void *buf, int size) 1092 { 1093 if (!buf || !size) 1094 return; 1095 1096 CLASS(fd, f)(kernel_fd); 1097 if (fd_empty(f)) 1098 return; 1099 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); 1103 } 1104 1105 /** 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 1114 * 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. 1119 * 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. 1123 */ 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) 1128 { 1129 if (!event_name || !event_label || !buf || !buf_len) 1130 return -ENOPARAM; 1131 1132 return process_buffer_measurement(&nop_mnt_idmap, NULL, buf, buf_len, 1133 event_name, CRITICAL_DATA, 0, 1134 event_label, hash, digest, 1135 digest_len); 1136 } 1137 EXPORT_SYMBOL_GPL(ima_measure_critical_data); 1138 1139 #ifdef CONFIG_INTEGRITY_ASYMMETRIC_KEYS 1140 1141 /** 1142 * ima_kernel_module_request - Prevent crypto-pkcs1(rsa,*) requests 1143 * @kmod_name: kernel module name 1144 * 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. 1150 * 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. 1155 * 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. 1159 * 1160 * Return: Zero if it is safe to load the kernel module, -EINVAL otherwise. 1161 */ 1162 static int ima_kernel_module_request(char *kmod_name) 1163 { 1164 if (strncmp(kmod_name, "crypto-pkcs1(rsa,", 17) == 0) 1165 return -EINVAL; 1166 1167 return 0; 1168 } 1169 1170 #endif /* CONFIG_INTEGRITY_ASYMMETRIC_KEYS */ 1171 1172 static int __init init_ima(void) 1173 { 1174 int error; 1175 1176 ima_appraise_parse_cmdline(); 1177 ima_init_template_list(); 1178 hash_setup(CONFIG_IMA_DEFAULT_HASH); 1179 error = ima_init(); 1180 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); 1187 error = ima_init(); 1188 } 1189 1190 if (error) 1191 return error; 1192 1193 error = register_blocking_lsm_notifier(&ima_lsm_policy_notifier); 1194 if (error) 1195 pr_warn("Couldn't register LSM notifier, error %d\n", error); 1196 1197 if (!error) 1198 ima_update_policy_flags(); 1199 1200 return error; 1201 } 1202 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), 1218 #endif 1219 #ifdef CONFIG_INTEGRITY_ASYMMETRIC_KEYS 1220 LSM_HOOK_INIT(kernel_module_request, ima_kernel_module_request), 1221 #endif 1222 LSM_HOOK_INIT(inode_free_security_rcu, ima_inode_free_rcu), 1223 }; 1224 1225 static const struct lsm_id ima_lsmid = { 1226 .name = "ima", 1227 .id = LSM_ID_IMA, 1228 }; 1229 1230 static int __init init_ima_lsm(void) 1231 { 1232 ima_iintcache_init(); 1233 security_add_hooks(ima_hooks, ARRAY_SIZE(ima_hooks), &ima_lsmid); 1234 init_ima_appraise_lsm(&ima_lsmid); 1235 return 0; 1236 } 1237 1238 struct lsm_blob_sizes ima_blob_sizes __ro_after_init = { 1239 .lbs_inode = sizeof(struct ima_iint_cache *), 1240 }; 1241 1242 DEFINE_LSM(ima) = { 1243 .name = "ima", 1244 .init = init_ima_lsm, 1245 .order = LSM_ORDER_LAST, 1246 .blobs = &ima_blob_sizes, 1247 }; 1248 1249 late_initcall(init_ima); /* Start IMA after the TPM is available */ 1250