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