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