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 133 /* IMA_MEASURE is set from reader side */ 134 if (iint && test_and_clear_bit(IMA_MAY_EMIT_TOMTOU, 135 &iint->atomic_flags)) 136 send_tomtou = true; 137 } 138 } else { 139 if (must_measure) 140 set_bit(IMA_MAY_EMIT_TOMTOU, &iint->atomic_flags); 141 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)) 146 send_writers = true; 147 } 148 } 149 150 if (!send_tomtou && !send_writers) 151 return; 152 153 *pathname = ima_d_path(&file->f_path, pathbuf, filename); 154 155 if (send_tomtou) 156 ima_add_violation(file, *pathname, iint, 157 "invalid_pcr", "ToMToU"); 158 if (send_writers) 159 ima_add_violation(file, *pathname, iint, 160 "invalid_pcr", "open_writers"); 161 } 162 163 static void ima_check_last_writer(struct ima_iint_cache *iint, 164 struct inode *inode, struct file *file) 165 { 166 fmode_t mode = file->f_mode; 167 bool update; 168 169 if (!(mode & FMODE_WRITE)) 170 return; 171 172 mutex_lock(&iint->mutex); 173 if (atomic_read(&inode->i_writecount) == 1) { 174 struct kstat stat; 175 176 clear_bit(IMA_EMITTED_OPENWRITERS, &iint->atomic_flags); 177 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, 182 STATX_CHANGE_COOKIE, 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; 188 if (update) 189 ima_update_xattr(iint, file); 190 } 191 } 192 mutex_unlock(&iint->mutex); 193 } 194 195 /** 196 * ima_file_free - called on __fput() 197 * @file: pointer to file structure being freed 198 * 199 * Flag files that changed, based on i_version 200 */ 201 static void ima_file_free(struct file *file) 202 { 203 struct inode *inode = file_inode(file); 204 struct ima_iint_cache *iint; 205 206 if (!ima_policy_flag || !S_ISREG(inode->i_mode)) 207 return; 208 209 iint = ima_iint_find(inode); 210 if (!iint) 211 return; 212 213 ima_check_last_writer(iint, inode, file); 214 } 215 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) 219 { 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; 231 int xattr_len = 0; 232 bool violation_check; 233 enum hash_algo hash_algo; 234 unsigned int allowed_algos = 0; 235 236 if (!ima_policy_flag || !S_ISREG(inode->i_mode)) 237 return 0; 238 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. 242 */ 243 action = ima_get_action(file_mnt_idmap(file), inode, cred, prop, 244 mask, func, &pcr, &template_desc, NULL, 245 &allowed_algos); 246 violation_check = ((func == FILE_CHECK || func == MMAP_CHECK || 247 func == MMAP_CHECK_REQPROT) && 248 (ima_policy_flag & IMA_MEASURE)); 249 if (!action && !violation_check) 250 return 0; 251 252 must_appraise = action & IMA_APPRAISE; 253 254 /* Is the appraise rule hook specific? */ 255 if (action & IMA_FILE_APPRAISE) 256 func = FILE_CHECK; 257 258 inode_lock(inode); 259 260 if (action) { 261 iint = ima_inode_get(inode); 262 if (!iint) 263 rc = -ENOMEM; 264 } 265 266 if (!rc && violation_check) 267 ima_rdwr_violation_check(file, iint, action & IMA_MEASURE, 268 &pathbuf, &pathname, filename); 269 270 inode_unlock(inode); 271 272 if (rc) 273 goto out; 274 if (!action) 275 goto out; 276 277 mutex_lock(&iint->mutex); 278 279 if (test_and_clear_bit(IMA_CHANGE_ATTR, &iint->atomic_flags)) 280 /* 281 * Reset appraisal flags (action and non-action rule-specific) 282 * if ima_inode_post_setattr was called. 283 */ 284 iint->flags &= ~(IMA_APPRAISE | IMA_APPRAISED | 285 IMA_APPRAISE_SUBMASK | IMA_APPRAISED_SUBMASK | 286 IMA_NONACTION_RULE_FLAGS); 287 288 /* 289 * Re-evaulate the file if either the xattr has changed or the 290 * kernel has no way of detecting file change on the filesystem. 291 * (Limited to privileged mounted filesystems.) 292 */ 293 if (test_and_clear_bit(IMA_CHANGE_XATTR, &iint->atomic_flags) || 294 ((inode->i_sb->s_iflags & SB_I_IMA_UNVERIFIABLE_SIGNATURE) && 295 !(inode->i_sb->s_iflags & SB_I_UNTRUSTED_MOUNTER) && 296 !(action & IMA_FAIL_UNVERIFIABLE_SIGS))) { 297 iint->flags &= ~IMA_DONE_MASK; 298 iint->measured_pcrs = 0; 299 } 300 301 /* 302 * On stacked filesystems, detect and re-evaluate file data and 303 * metadata changes. 304 */ 305 real_inode = d_real_inode(file_dentry(file)); 306 if (real_inode != inode && 307 (action & IMA_DO_MASK) && (iint->flags & IMA_DONE_MASK)) { 308 if (!IS_I_VERSION(real_inode) || 309 integrity_inode_attrs_changed(&iint->real_inode, 310 real_inode)) { 311 iint->flags &= ~IMA_DONE_MASK; 312 iint->measured_pcrs = 0; 313 } 314 315 /* 316 * Reset the EVM status when metadata changed. 317 */ 318 metadata_inode = d_inode(d_real(file_dentry(file), 319 D_REAL_METADATA)); 320 if (evm_metadata_changed(inode, metadata_inode)) 321 iint->flags &= ~(IMA_APPRAISED | 322 IMA_APPRAISED_SUBMASK); 323 } 324 325 /* Determine if already appraised/measured based on bitmask 326 * (IMA_MEASURE, IMA_MEASURED, IMA_XXXX_APPRAISE, IMA_XXXX_APPRAISED, 327 * IMA_AUDIT, IMA_AUDITED) 328 */ 329 iint->flags |= action; 330 action &= IMA_DO_MASK; 331 action &= ~((iint->flags & (IMA_DONE_MASK ^ IMA_MEASURED)) >> 1); 332 333 /* If target pcr is already measured, unset IMA_MEASURE action */ 334 if ((action & IMA_MEASURE) && (iint->measured_pcrs & (0x1 << pcr))) 335 action ^= IMA_MEASURE; 336 337 /* HASH sets the digital signature and update flags, nothing else */ 338 if ((action & IMA_HASH) && 339 !(test_bit(IMA_DIGSIG, &iint->atomic_flags))) { 340 xattr_len = ima_read_xattr(file_dentry(file), 341 &xattr_value, xattr_len); 342 if ((xattr_value && xattr_len > 2) && 343 (xattr_value->type == EVM_IMA_XATTR_DIGSIG)) 344 set_bit(IMA_DIGSIG, &iint->atomic_flags); 345 iint->flags |= IMA_HASHED; 346 action ^= IMA_HASH; 347 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags); 348 } 349 350 /* Nothing to do, just return existing appraised status */ 351 if (!action) { 352 if (must_appraise) { 353 rc = mmap_violation_check(func, file, &pathbuf, 354 &pathname, filename); 355 if (!rc) 356 rc = ima_get_cache_status(iint, func); 357 } 358 goto out_locked; 359 } 360 361 if ((action & IMA_APPRAISE_SUBMASK) || 362 strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) != 0) { 363 /* read 'security.ima' */ 364 xattr_len = ima_read_xattr(file_dentry(file), 365 &xattr_value, xattr_len); 366 367 /* 368 * Read the appended modsig if allowed by the policy, and allow 369 * an additional measurement list entry, if needed, based on the 370 * template format and whether the file was already measured. 371 */ 372 if (iint->flags & IMA_MODSIG_ALLOWED) { 373 rc = ima_read_modsig(func, buf, size, &modsig); 374 375 if (!rc && ima_template_has_modsig(template_desc) && 376 iint->flags & IMA_MEASURED) 377 action |= IMA_MEASURE; 378 } 379 } 380 381 hash_algo = ima_get_hash_algo(xattr_value, xattr_len); 382 383 rc = ima_collect_measurement(iint, file, buf, size, hash_algo, modsig); 384 if (rc != 0 && rc != -EBADF && rc != -EINVAL) 385 goto out_locked; 386 387 if (!pathbuf) /* ima_rdwr_violation possibly pre-fetched */ 388 pathname = ima_d_path(&file->f_path, &pathbuf, filename); 389 390 if (action & IMA_MEASURE) 391 ima_store_measurement(iint, file, pathname, 392 xattr_value, xattr_len, modsig, pcr, 393 template_desc); 394 if (rc == 0 && (action & IMA_APPRAISE_SUBMASK)) { 395 rc = ima_check_blacklist(iint, modsig, pcr); 396 if (rc != -EPERM) { 397 inode_lock(inode); 398 rc = ima_appraise_measurement(func, iint, file, 399 pathname, xattr_value, 400 xattr_len, modsig); 401 inode_unlock(inode); 402 } 403 if (!rc) 404 rc = mmap_violation_check(func, file, &pathbuf, 405 &pathname, filename); 406 } 407 if (action & IMA_AUDIT) 408 ima_audit_measurement(iint, pathname); 409 410 if ((file->f_flags & O_DIRECT) && (iint->flags & IMA_PERMIT_DIRECTIO)) 411 rc = 0; 412 413 /* Ensure the digest was generated using an allowed algorithm */ 414 if (rc == 0 && must_appraise && allowed_algos != 0 && 415 (allowed_algos & (1U << hash_algo)) == 0) { 416 rc = -EACCES; 417 418 integrity_audit_msg(AUDIT_INTEGRITY_DATA, file_inode(file), 419 pathname, "collect_data", 420 "denied-hash-algorithm", rc, 0); 421 } 422 out_locked: 423 if ((mask & MAY_WRITE) && test_bit(IMA_DIGSIG, &iint->atomic_flags) && 424 !(iint->flags & IMA_NEW_FILE)) 425 rc = -EACCES; 426 mutex_unlock(&iint->mutex); 427 kfree(xattr_value); 428 ima_free_modsig(modsig); 429 out: 430 if (pathbuf) 431 __putname(pathbuf); 432 if (must_appraise) { 433 if (rc && (ima_appraise & IMA_APPRAISE_ENFORCE)) 434 return -EACCES; 435 if (file->f_mode & FMODE_WRITE) 436 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags); 437 } 438 return 0; 439 } 440 441 /** 442 * ima_file_mmap - based on policy, collect/store measurement. 443 * @file: pointer to the file to be measured (May be NULL) 444 * @reqprot: protection requested by the application 445 * @prot: protection that will be applied by the kernel 446 * @flags: operational flags 447 * 448 * Measure files being mmapped executable based on the ima_must_measure() 449 * policy decision. 450 * 451 * On success return 0. On integrity appraisal error, assuming the file 452 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES. 453 */ 454 static int ima_file_mmap(struct file *file, unsigned long reqprot, 455 unsigned long prot, unsigned long flags) 456 { 457 struct lsm_prop prop; 458 int ret; 459 460 if (!file) 461 return 0; 462 463 security_current_getlsmprop_subj(&prop); 464 465 if (reqprot & PROT_EXEC) { 466 ret = process_measurement(file, current_cred(), &prop, NULL, 467 0, MAY_EXEC, MMAP_CHECK_REQPROT); 468 if (ret) 469 return ret; 470 } 471 472 if (prot & PROT_EXEC) 473 return process_measurement(file, current_cred(), &prop, NULL, 474 0, MAY_EXEC, MMAP_CHECK); 475 476 return 0; 477 } 478 479 /** 480 * ima_file_mprotect - based on policy, limit mprotect change 481 * @vma: vm_area_struct protection is set to 482 * @reqprot: protection requested by the application 483 * @prot: protection that will be applied by the kernel 484 * 485 * Files can be mmap'ed read/write and later changed to execute to circumvent 486 * IMA's mmap appraisal policy rules. Due to locking issues (mmap semaphore 487 * would be taken before i_mutex), files can not be measured or appraised at 488 * this point. Eliminate this integrity gap by denying the mprotect 489 * PROT_EXECUTE change, if an mmap appraise policy rule exists. 490 * 491 * On mprotect change success, return 0. On failure, return -EACESS. 492 */ 493 static int ima_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot, 494 unsigned long prot) 495 { 496 struct ima_template_desc *template = NULL; 497 struct file *file; 498 char filename[NAME_MAX]; 499 char *pathbuf = NULL; 500 const char *pathname = NULL; 501 struct inode *inode; 502 struct lsm_prop prop; 503 int result = 0; 504 int action; 505 int pcr; 506 507 /* Is mprotect making an mmap'ed file executable? */ 508 if (!(ima_policy_flag & IMA_APPRAISE) || !vma->vm_file || 509 !(prot & PROT_EXEC) || (vma->vm_flags & VM_EXEC)) 510 return 0; 511 512 security_current_getlsmprop_subj(&prop); 513 inode = file_inode(vma->vm_file); 514 action = ima_get_action(file_mnt_idmap(vma->vm_file), inode, 515 current_cred(), &prop, MAY_EXEC, MMAP_CHECK, 516 &pcr, &template, NULL, NULL); 517 action |= ima_get_action(file_mnt_idmap(vma->vm_file), inode, 518 current_cred(), &prop, MAY_EXEC, 519 MMAP_CHECK_REQPROT, &pcr, &template, NULL, 520 NULL); 521 522 /* Is the mmap'ed file in policy? */ 523 if (!(action & (IMA_MEASURE | IMA_APPRAISE_SUBMASK))) 524 return 0; 525 526 if (action & IMA_APPRAISE_SUBMASK) 527 result = -EPERM; 528 529 file = vma->vm_file; 530 pathname = ima_d_path(&file->f_path, &pathbuf, filename); 531 integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, pathname, 532 "collect_data", "failed-mprotect", result, 0); 533 if (pathbuf) 534 __putname(pathbuf); 535 536 return result; 537 } 538 539 /** 540 * ima_bprm_check - based on policy, collect/store measurement. 541 * @bprm: contains the linux_binprm structure 542 * 543 * The OS protects against an executable file, already open for write, 544 * from being executed in deny_write_access() and an executable file, 545 * already open for execute, from being modified in get_write_access(). 546 * So we can be certain that what we verify and measure here is actually 547 * what is being executed. 548 * 549 * On success return 0. On integrity appraisal error, assuming the file 550 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES. 551 */ 552 static int ima_bprm_check(struct linux_binprm *bprm) 553 { 554 int ret; 555 struct lsm_prop prop; 556 557 security_current_getlsmprop_subj(&prop); 558 ret = process_measurement(bprm->file, current_cred(), 559 &prop, NULL, 0, MAY_EXEC, BPRM_CHECK); 560 if (ret) 561 return ret; 562 563 security_cred_getlsmprop(bprm->cred, &prop); 564 return process_measurement(bprm->file, bprm->cred, &prop, NULL, 0, 565 MAY_EXEC, CREDS_CHECK); 566 } 567 568 /** 569 * ima_bprm_creds_for_exec - collect/store/appraise measurement. 570 * @bprm: contains the linux_binprm structure 571 * 572 * Based on the IMA policy and the execveat(2) AT_EXECVE_CHECK flag, measure 573 * and appraise the integrity of a file to be executed by script interpreters. 574 * Unlike any of the other LSM hooks where the kernel enforces file integrity, 575 * enforcing file integrity is left up to the discretion of the script 576 * interpreter (userspace). 577 * 578 * On success return 0. On integrity appraisal error, assuming the file 579 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES. 580 */ 581 static int ima_bprm_creds_for_exec(struct linux_binprm *bprm) 582 { 583 /* 584 * As security_bprm_check() is called multiple times, both 585 * the script and the shebang interpreter are measured, appraised, 586 * and audited. Limit usage of this LSM hook to just measuring, 587 * appraising, and auditing the indirect script execution 588 * (e.g. ./sh example.sh). 589 */ 590 if (!bprm->is_check) 591 return 0; 592 593 return ima_bprm_check(bprm); 594 } 595 596 /** 597 * ima_file_check - based on policy, collect/store measurement. 598 * @file: pointer to the file to be measured 599 * @mask: contains MAY_READ, MAY_WRITE, MAY_EXEC or MAY_APPEND 600 * 601 * Measure files based on the ima_must_measure() policy decision. 602 * 603 * On success return 0. On integrity appraisal error, assuming the file 604 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES. 605 */ 606 static int ima_file_check(struct file *file, int mask) 607 { 608 struct lsm_prop prop; 609 610 security_current_getlsmprop_subj(&prop); 611 return process_measurement(file, current_cred(), &prop, NULL, 0, 612 mask & (MAY_READ | MAY_WRITE | MAY_EXEC | 613 MAY_APPEND), FILE_CHECK); 614 } 615 616 static int __ima_inode_hash(struct inode *inode, struct file *file, char *buf, 617 size_t buf_size) 618 { 619 struct ima_iint_cache *iint = NULL, tmp_iint; 620 int rc, hash_algo; 621 622 if (ima_policy_flag) { 623 iint = ima_iint_find(inode); 624 if (iint) 625 mutex_lock(&iint->mutex); 626 } 627 628 if ((!iint || !(iint->flags & IMA_COLLECTED)) && file) { 629 if (iint) 630 mutex_unlock(&iint->mutex); 631 632 memset(&tmp_iint, 0, sizeof(tmp_iint)); 633 mutex_init(&tmp_iint.mutex); 634 635 rc = ima_collect_measurement(&tmp_iint, file, NULL, 0, 636 ima_hash_algo, NULL); 637 if (rc < 0) { 638 /* ima_hash could be allocated in case of failure. */ 639 if (rc != -ENOMEM) 640 kfree(tmp_iint.ima_hash); 641 642 return -EOPNOTSUPP; 643 } 644 645 iint = &tmp_iint; 646 mutex_lock(&iint->mutex); 647 } 648 649 if (!iint) 650 return -EOPNOTSUPP; 651 652 /* 653 * ima_file_hash can be called when ima_collect_measurement has still 654 * not been called, we might not always have a hash. 655 */ 656 if (!iint->ima_hash || !(iint->flags & IMA_COLLECTED)) { 657 mutex_unlock(&iint->mutex); 658 return -EOPNOTSUPP; 659 } 660 661 if (buf) { 662 size_t copied_size; 663 664 copied_size = min_t(size_t, iint->ima_hash->length, buf_size); 665 memcpy(buf, iint->ima_hash->digest, copied_size); 666 } 667 hash_algo = iint->ima_hash->algo; 668 mutex_unlock(&iint->mutex); 669 670 if (iint == &tmp_iint) 671 kfree(iint->ima_hash); 672 673 return hash_algo; 674 } 675 676 /** 677 * ima_file_hash - return a measurement of the file 678 * @file: pointer to the file 679 * @buf: buffer in which to store the hash 680 * @buf_size: length of the buffer 681 * 682 * On success, return the hash algorithm (as defined in the enum hash_algo). 683 * If buf is not NULL, this function also outputs the hash into buf. 684 * If the hash is larger than buf_size, then only buf_size bytes will be copied. 685 * It generally just makes sense to pass a buffer capable of holding the largest 686 * possible hash: IMA_MAX_DIGEST_SIZE. 687 * The file hash returned is based on the entire file, including the appended 688 * signature. 689 * 690 * If the measurement cannot be performed, return -EOPNOTSUPP. 691 * If the parameters are incorrect, return -EINVAL. 692 */ 693 int ima_file_hash(struct file *file, char *buf, size_t buf_size) 694 { 695 if (!file) 696 return -EINVAL; 697 698 return __ima_inode_hash(file_inode(file), file, buf, buf_size); 699 } 700 EXPORT_SYMBOL_GPL(ima_file_hash); 701 702 /** 703 * ima_inode_hash - return the stored measurement if the inode has been hashed 704 * and is in the iint cache. 705 * @inode: pointer to the inode 706 * @buf: buffer in which to store the hash 707 * @buf_size: length of the buffer 708 * 709 * On success, return the hash algorithm (as defined in the enum hash_algo). 710 * If buf is not NULL, this function also outputs the hash into buf. 711 * If the hash is larger than buf_size, then only buf_size bytes will be copied. 712 * It generally just makes sense to pass a buffer capable of holding the largest 713 * possible hash: IMA_MAX_DIGEST_SIZE. 714 * The hash returned is based on the entire contents, including the appended 715 * signature. 716 * 717 * If IMA is disabled or if no measurement is available, return -EOPNOTSUPP. 718 * If the parameters are incorrect, return -EINVAL. 719 */ 720 int ima_inode_hash(struct inode *inode, char *buf, size_t buf_size) 721 { 722 if (!inode) 723 return -EINVAL; 724 725 return __ima_inode_hash(inode, NULL, buf, buf_size); 726 } 727 EXPORT_SYMBOL_GPL(ima_inode_hash); 728 729 /** 730 * ima_post_create_tmpfile - mark newly created tmpfile as new 731 * @idmap: idmap of the mount the inode was found from 732 * @inode: inode of the newly created tmpfile 733 * 734 * No measuring, appraising or auditing of newly created tmpfiles is needed. 735 * Skip calling process_measurement(), but indicate which newly, created 736 * tmpfiles are in policy. 737 */ 738 static void ima_post_create_tmpfile(struct mnt_idmap *idmap, 739 struct inode *inode) 740 741 { 742 struct ima_iint_cache *iint; 743 int must_appraise; 744 745 if (!ima_policy_flag || !S_ISREG(inode->i_mode)) 746 return; 747 748 must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS, 749 FILE_CHECK); 750 if (!must_appraise) 751 return; 752 753 /* Nothing to do if we can't allocate memory */ 754 iint = ima_inode_get(inode); 755 if (!iint) 756 return; 757 758 /* needed for writing the security xattrs */ 759 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags); 760 iint->ima_file_status = INTEGRITY_PASS; 761 } 762 763 /** 764 * ima_post_path_mknod - mark as a new inode 765 * @idmap: idmap of the mount the inode was found from 766 * @dentry: newly created dentry 767 * 768 * Mark files created via the mknodat syscall as new, so that the 769 * file data can be written later. 770 */ 771 static void ima_post_path_mknod(struct mnt_idmap *idmap, struct dentry *dentry) 772 { 773 struct ima_iint_cache *iint; 774 struct inode *inode = dentry->d_inode; 775 int must_appraise; 776 777 if (!ima_policy_flag || !S_ISREG(inode->i_mode)) 778 return; 779 780 must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS, 781 FILE_CHECK); 782 if (!must_appraise) 783 return; 784 785 /* Nothing to do if we can't allocate memory */ 786 iint = ima_inode_get(inode); 787 if (!iint) 788 return; 789 790 /* needed for re-opening empty files */ 791 iint->flags |= IMA_NEW_FILE; 792 } 793 794 /** 795 * ima_read_file - pre-measure/appraise hook decision based on policy 796 * @file: pointer to the file to be measured/appraised/audit 797 * @read_id: caller identifier 798 * @contents: whether a subsequent call will be made to ima_post_read_file() 799 * 800 * Permit reading a file based on policy. The policy rules are written 801 * in terms of the policy identifier. Appraising the integrity of 802 * a file requires a file descriptor. 803 * 804 * For permission return 0, otherwise return -EACCES. 805 */ 806 static int ima_read_file(struct file *file, enum kernel_read_file_id read_id, 807 bool contents) 808 { 809 enum ima_hooks func; 810 struct lsm_prop prop; 811 812 /* 813 * Do devices using pre-allocated memory run the risk of the 814 * firmware being accessible to the device prior to the completion 815 * of IMA's signature verification any more than when using two 816 * buffers? It may be desirable to include the buffer address 817 * in this API and walk all the dma_map_single() mappings to check. 818 */ 819 820 /* 821 * There will be a call made to ima_post_read_file() with 822 * a filled buffer, so we don't need to perform an extra 823 * read early here. 824 */ 825 if (contents) 826 return 0; 827 828 /* Read entire file for all partial reads. */ 829 func = read_idmap[read_id] ?: FILE_CHECK; 830 security_current_getlsmprop_subj(&prop); 831 return process_measurement(file, current_cred(), &prop, NULL, 0, 832 MAY_READ, func); 833 } 834 835 const int read_idmap[READING_MAX_ID] = { 836 [READING_FIRMWARE] = FIRMWARE_CHECK, 837 [READING_MODULE] = MODULE_CHECK, 838 [READING_KEXEC_IMAGE] = KEXEC_KERNEL_CHECK, 839 [READING_KEXEC_INITRAMFS] = KEXEC_INITRAMFS_CHECK, 840 [READING_POLICY] = POLICY_CHECK 841 }; 842 843 /** 844 * ima_post_read_file - in memory collect/appraise/audit measurement 845 * @file: pointer to the file to be measured/appraised/audit 846 * @buf: pointer to in memory file contents 847 * @size: size of in memory file contents 848 * @read_id: caller identifier 849 * 850 * Measure/appraise/audit in memory file based on policy. Policy rules 851 * are written in terms of a policy identifier. 852 * 853 * On success return 0. On integrity appraisal error, assuming the file 854 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES. 855 */ 856 static int ima_post_read_file(struct file *file, char *buf, loff_t size, 857 enum kernel_read_file_id read_id) 858 { 859 enum ima_hooks func; 860 struct lsm_prop prop; 861 862 /* permit signed certs */ 863 if (!file && read_id == READING_X509_CERTIFICATE) 864 return 0; 865 866 if (!file || !buf || size == 0) { /* should never happen */ 867 if (ima_appraise & IMA_APPRAISE_ENFORCE) 868 return -EACCES; 869 return 0; 870 } 871 872 func = read_idmap[read_id] ?: FILE_CHECK; 873 security_current_getlsmprop_subj(&prop); 874 return process_measurement(file, current_cred(), &prop, buf, size, 875 MAY_READ, func); 876 } 877 878 /** 879 * ima_load_data - appraise decision based on policy 880 * @id: kernel load data caller identifier 881 * @contents: whether the full contents will be available in a later 882 * call to ima_post_load_data(). 883 * 884 * Callers of this LSM hook can not measure, appraise, or audit the 885 * data provided by userspace. Enforce policy rules requiring a file 886 * signature (eg. kexec'ed kernel image). 887 * 888 * For permission return 0, otherwise return -EACCES. 889 */ 890 static int ima_load_data(enum kernel_load_data_id id, bool contents) 891 { 892 bool ima_enforce, sig_enforce; 893 894 ima_enforce = 895 (ima_appraise & IMA_APPRAISE_ENFORCE) == IMA_APPRAISE_ENFORCE; 896 897 switch (id) { 898 case LOADING_KEXEC_IMAGE: 899 if (IS_ENABLED(CONFIG_KEXEC_SIG) 900 && arch_ima_get_secureboot()) { 901 pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n"); 902 return -EACCES; 903 } 904 905 if (ima_enforce && (ima_appraise & IMA_APPRAISE_KEXEC)) { 906 pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n"); 907 return -EACCES; /* INTEGRITY_UNKNOWN */ 908 } 909 break; 910 case LOADING_FIRMWARE: 911 if (ima_enforce && (ima_appraise & IMA_APPRAISE_FIRMWARE) && !contents) { 912 pr_err("Prevent firmware sysfs fallback loading.\n"); 913 return -EACCES; /* INTEGRITY_UNKNOWN */ 914 } 915 break; 916 case LOADING_MODULE: 917 sig_enforce = is_module_sig_enforced(); 918 919 if (ima_enforce && (!sig_enforce 920 && (ima_appraise & IMA_APPRAISE_MODULES))) { 921 pr_err("impossible to appraise a module without a file descriptor. sig_enforce kernel parameter might help\n"); 922 return -EACCES; /* INTEGRITY_UNKNOWN */ 923 } 924 break; 925 default: 926 break; 927 } 928 return 0; 929 } 930 931 /** 932 * ima_post_load_data - appraise decision based on policy 933 * @buf: pointer to in memory file contents 934 * @size: size of in memory file contents 935 * @load_id: kernel load data caller identifier 936 * @description: @load_id-specific description of contents 937 * 938 * Measure/appraise/audit in memory buffer based on policy. Policy rules 939 * are written in terms of a policy identifier. 940 * 941 * On success return 0. On integrity appraisal error, assuming the file 942 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES. 943 */ 944 static int ima_post_load_data(char *buf, loff_t size, 945 enum kernel_load_data_id load_id, 946 char *description) 947 { 948 if (load_id == LOADING_FIRMWARE) { 949 if ((ima_appraise & IMA_APPRAISE_FIRMWARE) && 950 (ima_appraise & IMA_APPRAISE_ENFORCE)) { 951 pr_err("Prevent firmware loading_store.\n"); 952 return -EACCES; /* INTEGRITY_UNKNOWN */ 953 } 954 return 0; 955 } 956 957 /* 958 * Measure the init_module syscall buffer containing the ELF image. 959 */ 960 if (load_id == LOADING_MODULE) 961 ima_measure_critical_data("modules", "init_module", 962 buf, size, true, NULL, 0); 963 964 return 0; 965 } 966 967 /** 968 * process_buffer_measurement - Measure the buffer or the buffer data hash 969 * @idmap: idmap of the mount the inode was found from 970 * @inode: inode associated with the object being measured (NULL for KEY_CHECK) 971 * @buf: pointer to the buffer that needs to be added to the log. 972 * @size: size of buffer(in bytes). 973 * @eventname: event name to be used for the buffer entry. 974 * @func: IMA hook 975 * @pcr: pcr to extend the measurement 976 * @func_data: func specific data, may be NULL 977 * @buf_hash: measure buffer data hash 978 * @digest: buffer digest will be written to 979 * @digest_len: buffer length 980 * 981 * Based on policy, either the buffer data or buffer data hash is measured 982 * 983 * Return: 0 if the buffer has been successfully measured, 1 if the digest 984 * has been written to the passed location but not added to a measurement entry, 985 * a negative value otherwise. 986 */ 987 int process_buffer_measurement(struct mnt_idmap *idmap, 988 struct inode *inode, const void *buf, int size, 989 const char *eventname, enum ima_hooks func, 990 int pcr, const char *func_data, 991 bool buf_hash, u8 *digest, size_t digest_len) 992 { 993 int ret = 0; 994 const char *audit_cause = "ENOMEM"; 995 struct ima_template_entry *entry = NULL; 996 struct ima_iint_cache iint = {}; 997 struct ima_event_data event_data = {.iint = &iint, 998 .filename = eventname, 999 .buf = buf, 1000 .buf_len = size}; 1001 struct ima_template_desc *template; 1002 struct ima_max_digest_data hash; 1003 struct ima_digest_data *hash_hdr = container_of(&hash.hdr, 1004 struct ima_digest_data, hdr); 1005 char digest_hash[IMA_MAX_DIGEST_SIZE]; 1006 int digest_hash_len = hash_digest_size[ima_hash_algo]; 1007 int violation = 0; 1008 int action = 0; 1009 struct lsm_prop prop; 1010 1011 if (digest && digest_len < digest_hash_len) 1012 return -EINVAL; 1013 1014 if (!ima_policy_flag && !digest) 1015 return -ENOENT; 1016 1017 template = ima_template_desc_buf(); 1018 if (!template) { 1019 ret = -EINVAL; 1020 audit_cause = "ima_template_desc_buf"; 1021 goto out; 1022 } 1023 1024 /* 1025 * Both LSM hooks and auxiliary based buffer measurements are 1026 * based on policy. To avoid code duplication, differentiate 1027 * between the LSM hooks and auxiliary buffer measurements, 1028 * retrieving the policy rule information only for the LSM hook 1029 * buffer measurements. 1030 */ 1031 if (func) { 1032 security_current_getlsmprop_subj(&prop); 1033 action = ima_get_action(idmap, inode, current_cred(), 1034 &prop, 0, func, &pcr, &template, 1035 func_data, NULL); 1036 if (!(action & IMA_MEASURE) && !digest) 1037 return -ENOENT; 1038 } 1039 1040 if (!pcr) 1041 pcr = CONFIG_IMA_MEASURE_PCR_IDX; 1042 1043 iint.ima_hash = hash_hdr; 1044 iint.ima_hash->algo = ima_hash_algo; 1045 iint.ima_hash->length = hash_digest_size[ima_hash_algo]; 1046 1047 ret = ima_calc_buffer_hash(buf, size, iint.ima_hash); 1048 if (ret < 0) { 1049 audit_cause = "hashing_error"; 1050 goto out; 1051 } 1052 1053 if (buf_hash) { 1054 memcpy(digest_hash, hash_hdr->digest, digest_hash_len); 1055 1056 ret = ima_calc_buffer_hash(digest_hash, digest_hash_len, 1057 iint.ima_hash); 1058 if (ret < 0) { 1059 audit_cause = "hashing_error"; 1060 goto out; 1061 } 1062 1063 event_data.buf = digest_hash; 1064 event_data.buf_len = digest_hash_len; 1065 } 1066 1067 if (digest) 1068 memcpy(digest, iint.ima_hash->digest, digest_hash_len); 1069 1070 if (!ima_policy_flag || (func && !(action & IMA_MEASURE))) 1071 return 1; 1072 1073 ret = ima_alloc_init_template(&event_data, &entry, template); 1074 if (ret < 0) { 1075 audit_cause = "alloc_entry"; 1076 goto out; 1077 } 1078 1079 ret = ima_store_template(entry, violation, NULL, event_data.buf, pcr); 1080 if (ret < 0) { 1081 audit_cause = "store_entry"; 1082 ima_free_template_entry(entry); 1083 } 1084 1085 out: 1086 if (ret < 0) 1087 integrity_audit_message(AUDIT_INTEGRITY_PCR, NULL, eventname, 1088 func_measure_str(func), 1089 audit_cause, ret, 0, ret); 1090 1091 return ret; 1092 } 1093 1094 /** 1095 * ima_kexec_cmdline - measure kexec cmdline boot args 1096 * @kernel_fd: file descriptor of the kexec kernel being loaded 1097 * @buf: pointer to buffer 1098 * @size: size of buffer 1099 * 1100 * Buffers can only be measured, not appraised. 1101 */ 1102 void ima_kexec_cmdline(int kernel_fd, const void *buf, int size) 1103 { 1104 if (!buf || !size) 1105 return; 1106 1107 CLASS(fd, f)(kernel_fd); 1108 if (fd_empty(f)) 1109 return; 1110 1111 process_buffer_measurement(file_mnt_idmap(fd_file(f)), file_inode(fd_file(f)), 1112 buf, size, "kexec-cmdline", KEXEC_CMDLINE, 0, 1113 NULL, false, NULL, 0); 1114 } 1115 1116 /** 1117 * ima_measure_critical_data - measure kernel integrity critical data 1118 * @event_label: unique event label for grouping and limiting critical data 1119 * @event_name: event name for the record in the IMA measurement list 1120 * @buf: pointer to buffer data 1121 * @buf_len: length of buffer data (in bytes) 1122 * @hash: measure buffer data hash 1123 * @digest: buffer digest will be written to 1124 * @digest_len: buffer length 1125 * 1126 * Measure data critical to the integrity of the kernel into the IMA log 1127 * and extend the pcr. Examples of critical data could be various data 1128 * structures, policies, and states stored in kernel memory that can 1129 * impact the integrity of the system. 1130 * 1131 * Return: 0 if the buffer has been successfully measured, 1 if the digest 1132 * has been written to the passed location but not added to a measurement entry, 1133 * a negative value otherwise. 1134 */ 1135 int ima_measure_critical_data(const char *event_label, 1136 const char *event_name, 1137 const void *buf, size_t buf_len, 1138 bool hash, u8 *digest, size_t digest_len) 1139 { 1140 if (!event_name || !event_label || !buf || !buf_len) 1141 return -ENOPARAM; 1142 1143 return process_buffer_measurement(&nop_mnt_idmap, NULL, buf, buf_len, 1144 event_name, CRITICAL_DATA, 0, 1145 event_label, hash, digest, 1146 digest_len); 1147 } 1148 EXPORT_SYMBOL_GPL(ima_measure_critical_data); 1149 1150 #ifdef CONFIG_INTEGRITY_ASYMMETRIC_KEYS 1151 1152 /** 1153 * ima_kernel_module_request - Prevent crypto-pkcs1(rsa,*) requests 1154 * @kmod_name: kernel module name 1155 * 1156 * Avoid a verification loop where verifying the signature of the modprobe 1157 * binary requires executing modprobe itself. Since the modprobe iint->mutex 1158 * is already held when the signature verification is performed, a deadlock 1159 * occurs as soon as modprobe is executed within the critical region, since 1160 * the same lock cannot be taken again. 1161 * 1162 * This happens when public_key_verify_signature(), in case of RSA algorithm, 1163 * use alg_name to store internal information in order to construct an 1164 * algorithm on the fly, but crypto_larval_lookup() will try to use alg_name 1165 * in order to load a kernel module with same name. 1166 * 1167 * Since we don't have any real "crypto-pkcs1(rsa,*)" kernel modules, 1168 * we are safe to fail such module request from crypto_larval_lookup(), and 1169 * avoid the verification loop. 1170 * 1171 * Return: Zero if it is safe to load the kernel module, -EINVAL otherwise. 1172 */ 1173 static int ima_kernel_module_request(char *kmod_name) 1174 { 1175 if (strncmp(kmod_name, "crypto-pkcs1(rsa,", 17) == 0) 1176 return -EINVAL; 1177 1178 return 0; 1179 } 1180 1181 #endif /* CONFIG_INTEGRITY_ASYMMETRIC_KEYS */ 1182 1183 static int __init init_ima(void) 1184 { 1185 int error; 1186 1187 ima_appraise_parse_cmdline(); 1188 ima_init_template_list(); 1189 hash_setup(CONFIG_IMA_DEFAULT_HASH); 1190 error = ima_init(); 1191 1192 if (error && strcmp(hash_algo_name[ima_hash_algo], 1193 CONFIG_IMA_DEFAULT_HASH) != 0) { 1194 pr_info("Allocating %s failed, going to use default hash algorithm %s\n", 1195 hash_algo_name[ima_hash_algo], CONFIG_IMA_DEFAULT_HASH); 1196 hash_setup_done = 0; 1197 hash_setup(CONFIG_IMA_DEFAULT_HASH); 1198 error = ima_init(); 1199 } 1200 1201 if (error) 1202 return error; 1203 1204 error = register_blocking_lsm_notifier(&ima_lsm_policy_notifier); 1205 if (error) 1206 pr_warn("Couldn't register LSM notifier, error %d\n", error); 1207 1208 if (!error) 1209 ima_update_policy_flags(); 1210 1211 return error; 1212 } 1213 1214 static struct security_hook_list ima_hooks[] __ro_after_init = { 1215 LSM_HOOK_INIT(bprm_check_security, ima_bprm_check), 1216 LSM_HOOK_INIT(bprm_creds_for_exec, ima_bprm_creds_for_exec), 1217 LSM_HOOK_INIT(file_post_open, ima_file_check), 1218 LSM_HOOK_INIT(inode_post_create_tmpfile, ima_post_create_tmpfile), 1219 LSM_HOOK_INIT(file_release, ima_file_free), 1220 LSM_HOOK_INIT(mmap_file, ima_file_mmap), 1221 LSM_HOOK_INIT(file_mprotect, ima_file_mprotect), 1222 LSM_HOOK_INIT(kernel_load_data, ima_load_data), 1223 LSM_HOOK_INIT(kernel_post_load_data, ima_post_load_data), 1224 LSM_HOOK_INIT(kernel_read_file, ima_read_file), 1225 LSM_HOOK_INIT(kernel_post_read_file, ima_post_read_file), 1226 LSM_HOOK_INIT(path_post_mknod, ima_post_path_mknod), 1227 #ifdef CONFIG_IMA_MEASURE_ASYMMETRIC_KEYS 1228 LSM_HOOK_INIT(key_post_create_or_update, ima_post_key_create_or_update), 1229 #endif 1230 #ifdef CONFIG_INTEGRITY_ASYMMETRIC_KEYS 1231 LSM_HOOK_INIT(kernel_module_request, ima_kernel_module_request), 1232 #endif 1233 LSM_HOOK_INIT(inode_free_security_rcu, ima_inode_free_rcu), 1234 }; 1235 1236 static const struct lsm_id ima_lsmid = { 1237 .name = "ima", 1238 .id = LSM_ID_IMA, 1239 }; 1240 1241 static int __init init_ima_lsm(void) 1242 { 1243 ima_iintcache_init(); 1244 security_add_hooks(ima_hooks, ARRAY_SIZE(ima_hooks), &ima_lsmid); 1245 init_ima_appraise_lsm(&ima_lsmid); 1246 return 0; 1247 } 1248 1249 struct lsm_blob_sizes ima_blob_sizes __ro_after_init = { 1250 .lbs_inode = sizeof(struct ima_iint_cache *), 1251 }; 1252 1253 DEFINE_LSM(ima) = { 1254 .name = "ima", 1255 .init = init_ima_lsm, 1256 .order = LSM_ORDER_LAST, 1257 .blobs = &ima_blob_sizes, 1258 }; 1259 1260 late_initcall(init_ima); /* Start IMA after the TPM is available */ 1261