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
30 #include "ima.h"
31
32 #ifdef CONFIG_IMA_APPRAISE
33 int ima_appraise = IMA_APPRAISE_ENFORCE;
34 #else
35 int ima_appraise;
36 #endif
37
38 int __ro_after_init ima_hash_algo = HASH_ALGO_SHA1;
39 static int hash_setup_done;
40
41 static struct notifier_block ima_lsm_policy_notifier = {
42 .notifier_call = ima_lsm_policy_change,
43 };
44
hash_setup(char * str)45 static int __init hash_setup(char *str)
46 {
47 struct ima_template_desc *template_desc = ima_template_desc_current();
48 int i;
49
50 if (hash_setup_done)
51 return 1;
52
53 if (strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) == 0) {
54 if (strncmp(str, "sha1", 4) == 0) {
55 ima_hash_algo = HASH_ALGO_SHA1;
56 } else if (strncmp(str, "md5", 3) == 0) {
57 ima_hash_algo = HASH_ALGO_MD5;
58 } else {
59 pr_err("invalid hash algorithm \"%s\" for template \"%s\"",
60 str, IMA_TEMPLATE_IMA_NAME);
61 return 1;
62 }
63 goto out;
64 }
65
66 i = match_string(hash_algo_name, HASH_ALGO__LAST, str);
67 if (i < 0) {
68 pr_err("invalid hash algorithm \"%s\"", str);
69 return 1;
70 }
71
72 ima_hash_algo = i;
73 out:
74 hash_setup_done = 1;
75 return 1;
76 }
77 __setup("ima_hash=", hash_setup);
78
ima_get_current_hash_algo(void)79 enum hash_algo ima_get_current_hash_algo(void)
80 {
81 return ima_hash_algo;
82 }
83
84 /* 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)85 static int mmap_violation_check(enum ima_hooks func, struct file *file,
86 char **pathbuf, const char **pathname,
87 char *filename)
88 {
89 struct inode *inode;
90 int rc = 0;
91
92 if ((func == MMAP_CHECK || func == MMAP_CHECK_REQPROT) &&
93 mapping_writably_mapped(file->f_mapping)) {
94 rc = -ETXTBSY;
95 inode = file_inode(file);
96
97 if (!*pathbuf) /* ima_rdwr_violation possibly pre-fetched */
98 *pathname = ima_d_path(&file->f_path, pathbuf,
99 filename);
100 integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, *pathname,
101 "mmap_file", "mmapped_writers", rc, 0);
102 }
103 return rc;
104 }
105
106 /*
107 * ima_rdwr_violation_check
108 *
109 * Only invalidate the PCR for measured files:
110 * - Opening a file for write when already open for read,
111 * results in a time of measure, time of use (ToMToU) error.
112 * - Opening a file for read when already open for write,
113 * could result in a file measurement error.
114 *
115 */
ima_rdwr_violation_check(struct file * file,struct integrity_iint_cache * iint,int must_measure,char ** pathbuf,const char ** pathname,char * filename)116 static void ima_rdwr_violation_check(struct file *file,
117 struct integrity_iint_cache *iint,
118 int must_measure,
119 char **pathbuf,
120 const char **pathname,
121 char *filename)
122 {
123 struct inode *inode = file_inode(file);
124 fmode_t mode = file->f_mode;
125 bool send_tomtou = false, send_writers = false;
126
127 if (mode & FMODE_WRITE) {
128 if (atomic_read(&inode->i_readcount) && IS_IMA(inode)) {
129 if (!iint)
130 iint = integrity_iint_find(inode);
131 /* IMA_MEASURE is set from reader side */
132 if (iint && test_bit(IMA_MUST_MEASURE,
133 &iint->atomic_flags))
134 send_tomtou = true;
135 }
136 } else {
137 if (must_measure)
138 set_bit(IMA_MUST_MEASURE, &iint->atomic_flags);
139 if (inode_is_open_for_write(inode) && must_measure)
140 send_writers = true;
141 }
142
143 if (!send_tomtou && !send_writers)
144 return;
145
146 *pathname = ima_d_path(&file->f_path, pathbuf, filename);
147
148 if (send_tomtou)
149 ima_add_violation(file, *pathname, iint,
150 "invalid_pcr", "ToMToU");
151 if (send_writers)
152 ima_add_violation(file, *pathname, iint,
153 "invalid_pcr", "open_writers");
154 }
155
ima_check_last_writer(struct integrity_iint_cache * iint,struct inode * inode,struct file * file)156 static void ima_check_last_writer(struct integrity_iint_cache *iint,
157 struct inode *inode, struct file *file)
158 {
159 fmode_t mode = file->f_mode;
160 bool update;
161
162 if (!(mode & FMODE_WRITE))
163 return;
164
165 mutex_lock(&iint->mutex);
166 if (atomic_read(&inode->i_writecount) == 1) {
167 struct kstat stat;
168
169 update = test_and_clear_bit(IMA_UPDATE_XATTR,
170 &iint->atomic_flags);
171 if ((iint->flags & IMA_NEW_FILE) ||
172 vfs_getattr_nosec(&file->f_path, &stat,
173 STATX_CHANGE_COOKIE,
174 AT_STATX_SYNC_AS_STAT) ||
175 !(stat.result_mask & STATX_CHANGE_COOKIE) ||
176 stat.change_cookie != iint->version) {
177 iint->flags &= ~(IMA_DONE_MASK | IMA_NEW_FILE);
178 iint->measured_pcrs = 0;
179 if (update)
180 ima_update_xattr(iint, file);
181 }
182 }
183 mutex_unlock(&iint->mutex);
184 }
185
186 /**
187 * ima_file_free - called on __fput()
188 * @file: pointer to file structure being freed
189 *
190 * Flag files that changed, based on i_version
191 */
ima_file_free(struct file * file)192 void ima_file_free(struct file *file)
193 {
194 struct inode *inode = file_inode(file);
195 struct integrity_iint_cache *iint;
196
197 if (!ima_policy_flag || !S_ISREG(inode->i_mode))
198 return;
199
200 iint = integrity_iint_find(inode);
201 if (!iint)
202 return;
203
204 ima_check_last_writer(iint, inode, file);
205 }
206
process_measurement(struct file * file,const struct cred * cred,u32 secid,char * buf,loff_t size,int mask,enum ima_hooks func)207 static int process_measurement(struct file *file, const struct cred *cred,
208 u32 secid, char *buf, loff_t size, int mask,
209 enum ima_hooks func)
210 {
211 struct inode *backing_inode, *inode = file_inode(file);
212 struct integrity_iint_cache *iint = NULL;
213 struct ima_template_desc *template_desc = NULL;
214 char *pathbuf = NULL;
215 char filename[NAME_MAX];
216 const char *pathname = NULL;
217 int rc = 0, action, must_appraise = 0;
218 int pcr = CONFIG_IMA_MEASURE_PCR_IDX;
219 struct evm_ima_xattr_data *xattr_value = NULL;
220 struct modsig *modsig = NULL;
221 int xattr_len = 0;
222 bool violation_check;
223 enum hash_algo hash_algo;
224 unsigned int allowed_algos = 0;
225
226 if (!ima_policy_flag || !S_ISREG(inode->i_mode))
227 return 0;
228
229 /* Return an IMA_MEASURE, IMA_APPRAISE, IMA_AUDIT action
230 * bitmask based on the appraise/audit/measurement policy.
231 * Included is the appraise submask.
232 */
233 action = ima_get_action(file_mnt_idmap(file), inode, cred, secid,
234 mask, func, &pcr, &template_desc, NULL,
235 &allowed_algos);
236 violation_check = ((func == FILE_CHECK || func == MMAP_CHECK ||
237 func == MMAP_CHECK_REQPROT) &&
238 (ima_policy_flag & IMA_MEASURE) &&
239 ((action & IMA_MEASURE) ||
240 (file->f_mode & FMODE_WRITE)));
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 = integrity_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 /* Detect and re-evaluate changes made to the backing file. */
294 backing_inode = d_real_inode(file_dentry(file));
295 if (backing_inode != inode &&
296 (action & IMA_DO_MASK) && (iint->flags & IMA_DONE_MASK)) {
297 if (!IS_I_VERSION(backing_inode) ||
298 backing_inode->i_sb->s_dev != iint->real_dev ||
299 backing_inode->i_ino != iint->real_ino ||
300 !inode_eq_iversion(backing_inode, iint->version)) {
301 iint->flags &= ~IMA_DONE_MASK;
302 iint->measured_pcrs = 0;
303 }
304 }
305
306 /* Determine if already appraised/measured based on bitmask
307 * (IMA_MEASURE, IMA_MEASURED, IMA_XXXX_APPRAISE, IMA_XXXX_APPRAISED,
308 * IMA_AUDIT, IMA_AUDITED)
309 */
310 iint->flags |= action;
311 action &= IMA_DO_MASK;
312 action &= ~((iint->flags & (IMA_DONE_MASK ^ IMA_MEASURED)) >> 1);
313
314 /* If target pcr is already measured, unset IMA_MEASURE action */
315 if ((action & IMA_MEASURE) && (iint->measured_pcrs & (0x1 << pcr)))
316 action ^= IMA_MEASURE;
317
318 /* HASH sets the digital signature and update flags, nothing else */
319 if ((action & IMA_HASH) &&
320 !(test_bit(IMA_DIGSIG, &iint->atomic_flags))) {
321 xattr_len = ima_read_xattr(file_dentry(file),
322 &xattr_value, xattr_len);
323 if ((xattr_value && xattr_len > 2) &&
324 (xattr_value->type == EVM_IMA_XATTR_DIGSIG))
325 set_bit(IMA_DIGSIG, &iint->atomic_flags);
326 iint->flags |= IMA_HASHED;
327 action ^= IMA_HASH;
328 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
329 }
330
331 /* Nothing to do, just return existing appraised status */
332 if (!action) {
333 if (must_appraise) {
334 rc = mmap_violation_check(func, file, &pathbuf,
335 &pathname, filename);
336 if (!rc)
337 rc = ima_get_cache_status(iint, func);
338 }
339 goto out_locked;
340 }
341
342 if ((action & IMA_APPRAISE_SUBMASK) ||
343 strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) != 0) {
344 /* read 'security.ima' */
345 xattr_len = ima_read_xattr(file_dentry(file),
346 &xattr_value, xattr_len);
347
348 /*
349 * Read the appended modsig if allowed by the policy, and allow
350 * an additional measurement list entry, if needed, based on the
351 * template format and whether the file was already measured.
352 */
353 if (iint->flags & IMA_MODSIG_ALLOWED) {
354 rc = ima_read_modsig(func, buf, size, &modsig);
355
356 if (!rc && ima_template_has_modsig(template_desc) &&
357 iint->flags & IMA_MEASURED)
358 action |= IMA_MEASURE;
359 }
360 }
361
362 hash_algo = ima_get_hash_algo(xattr_value, xattr_len);
363
364 rc = ima_collect_measurement(iint, file, buf, size, hash_algo, modsig);
365 if (rc != 0 && rc != -EBADF && rc != -EINVAL)
366 goto out_locked;
367
368 if (!pathbuf) /* ima_rdwr_violation possibly pre-fetched */
369 pathname = ima_d_path(&file->f_path, &pathbuf, filename);
370
371 if (action & IMA_MEASURE)
372 ima_store_measurement(iint, file, pathname,
373 xattr_value, xattr_len, modsig, pcr,
374 template_desc);
375 if (rc == 0 && (action & IMA_APPRAISE_SUBMASK)) {
376 rc = ima_check_blacklist(iint, modsig, pcr);
377 if (rc != -EPERM) {
378 inode_lock(inode);
379 rc = ima_appraise_measurement(func, iint, file,
380 pathname, xattr_value,
381 xattr_len, modsig);
382 inode_unlock(inode);
383 }
384 if (!rc)
385 rc = mmap_violation_check(func, file, &pathbuf,
386 &pathname, filename);
387 }
388 if (action & IMA_AUDIT)
389 ima_audit_measurement(iint, pathname);
390
391 if ((file->f_flags & O_DIRECT) && (iint->flags & IMA_PERMIT_DIRECTIO))
392 rc = 0;
393
394 /* Ensure the digest was generated using an allowed algorithm */
395 if (rc == 0 && must_appraise && allowed_algos != 0 &&
396 (allowed_algos & (1U << hash_algo)) == 0) {
397 rc = -EACCES;
398
399 integrity_audit_msg(AUDIT_INTEGRITY_DATA, file_inode(file),
400 pathname, "collect_data",
401 "denied-hash-algorithm", rc, 0);
402 }
403 out_locked:
404 if ((mask & MAY_WRITE) && test_bit(IMA_DIGSIG, &iint->atomic_flags) &&
405 !(iint->flags & IMA_NEW_FILE))
406 rc = -EACCES;
407 mutex_unlock(&iint->mutex);
408 kfree(xattr_value);
409 ima_free_modsig(modsig);
410 out:
411 if (pathbuf)
412 __putname(pathbuf);
413 if (must_appraise) {
414 if (rc && (ima_appraise & IMA_APPRAISE_ENFORCE))
415 return -EACCES;
416 if (file->f_mode & FMODE_WRITE)
417 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
418 }
419 return 0;
420 }
421
422 /**
423 * ima_file_mmap - based on policy, collect/store measurement.
424 * @file: pointer to the file to be measured (May be NULL)
425 * @reqprot: protection requested by the application
426 * @prot: protection that will be applied by the kernel
427 * @flags: operational flags
428 *
429 * Measure files being mmapped executable based on the ima_must_measure()
430 * policy decision.
431 *
432 * On success return 0. On integrity appraisal error, assuming the file
433 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
434 */
ima_file_mmap(struct file * file,unsigned long reqprot,unsigned long prot,unsigned long flags)435 int ima_file_mmap(struct file *file, unsigned long reqprot,
436 unsigned long prot, unsigned long flags)
437 {
438 u32 secid;
439 int ret;
440
441 if (!file)
442 return 0;
443
444 security_current_getsecid_subj(&secid);
445
446 if (reqprot & PROT_EXEC) {
447 ret = process_measurement(file, current_cred(), secid, NULL,
448 0, MAY_EXEC, MMAP_CHECK_REQPROT);
449 if (ret)
450 return ret;
451 }
452
453 if (prot & PROT_EXEC)
454 return process_measurement(file, current_cred(), secid, NULL,
455 0, MAY_EXEC, MMAP_CHECK);
456
457 return 0;
458 }
459
460 /**
461 * ima_file_mprotect - based on policy, limit mprotect change
462 * @vma: vm_area_struct protection is set to
463 * @prot: contains the protection that will be applied by the kernel.
464 *
465 * Files can be mmap'ed read/write and later changed to execute to circumvent
466 * IMA's mmap appraisal policy rules. Due to locking issues (mmap semaphore
467 * would be taken before i_mutex), files can not be measured or appraised at
468 * this point. Eliminate this integrity gap by denying the mprotect
469 * PROT_EXECUTE change, if an mmap appraise policy rule exists.
470 *
471 * On mprotect change success, return 0. On failure, return -EACESS.
472 */
ima_file_mprotect(struct vm_area_struct * vma,unsigned long prot)473 int ima_file_mprotect(struct vm_area_struct *vma, unsigned long prot)
474 {
475 struct ima_template_desc *template = NULL;
476 struct file *file;
477 char filename[NAME_MAX];
478 char *pathbuf = NULL;
479 const char *pathname = NULL;
480 struct inode *inode;
481 int result = 0;
482 int action;
483 u32 secid;
484 int pcr;
485
486 /* Is mprotect making an mmap'ed file executable? */
487 if (!(ima_policy_flag & IMA_APPRAISE) || !vma->vm_file ||
488 !(prot & PROT_EXEC) || (vma->vm_flags & VM_EXEC))
489 return 0;
490
491 security_current_getsecid_subj(&secid);
492 inode = file_inode(vma->vm_file);
493 action = ima_get_action(file_mnt_idmap(vma->vm_file), inode,
494 current_cred(), secid, MAY_EXEC, MMAP_CHECK,
495 &pcr, &template, NULL, NULL);
496 action |= ima_get_action(file_mnt_idmap(vma->vm_file), inode,
497 current_cred(), secid, MAY_EXEC,
498 MMAP_CHECK_REQPROT, &pcr, &template, NULL,
499 NULL);
500
501 /* Is the mmap'ed file in policy? */
502 if (!(action & (IMA_MEASURE | IMA_APPRAISE_SUBMASK)))
503 return 0;
504
505 if (action & IMA_APPRAISE_SUBMASK)
506 result = -EPERM;
507
508 file = vma->vm_file;
509 pathname = ima_d_path(&file->f_path, &pathbuf, filename);
510 integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, pathname,
511 "collect_data", "failed-mprotect", result, 0);
512 if (pathbuf)
513 __putname(pathbuf);
514
515 return result;
516 }
517
518 /**
519 * ima_bprm_check - based on policy, collect/store measurement.
520 * @bprm: contains the linux_binprm structure
521 *
522 * The OS protects against an executable file, already open for write,
523 * from being executed in deny_write_access() and an executable file,
524 * already open for execute, from being modified in get_write_access().
525 * So we can be certain that what we verify and measure here is actually
526 * what is being executed.
527 *
528 * On success return 0. On integrity appraisal error, assuming the file
529 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
530 */
ima_bprm_check(struct linux_binprm * bprm)531 int ima_bprm_check(struct linux_binprm *bprm)
532 {
533 int ret;
534 u32 secid;
535
536 security_current_getsecid_subj(&secid);
537 ret = process_measurement(bprm->file, current_cred(), secid, NULL, 0,
538 MAY_EXEC, BPRM_CHECK);
539 if (ret)
540 return ret;
541
542 security_cred_getsecid(bprm->cred, &secid);
543 return process_measurement(bprm->file, bprm->cred, secid, NULL, 0,
544 MAY_EXEC, CREDS_CHECK);
545 }
546
547 /**
548 * ima_file_check - based on policy, collect/store measurement.
549 * @file: pointer to the file to be measured
550 * @mask: contains MAY_READ, MAY_WRITE, MAY_EXEC or MAY_APPEND
551 *
552 * Measure files based on the ima_must_measure() policy decision.
553 *
554 * On success return 0. On integrity appraisal error, assuming the file
555 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
556 */
ima_file_check(struct file * file,int mask)557 int ima_file_check(struct file *file, int mask)
558 {
559 u32 secid;
560
561 security_current_getsecid_subj(&secid);
562 return process_measurement(file, current_cred(), secid, NULL, 0,
563 mask & (MAY_READ | MAY_WRITE | MAY_EXEC |
564 MAY_APPEND), FILE_CHECK);
565 }
566 EXPORT_SYMBOL_GPL(ima_file_check);
567
__ima_inode_hash(struct inode * inode,struct file * file,char * buf,size_t buf_size)568 static int __ima_inode_hash(struct inode *inode, struct file *file, char *buf,
569 size_t buf_size)
570 {
571 struct integrity_iint_cache *iint = NULL, tmp_iint;
572 int rc, hash_algo;
573
574 if (ima_policy_flag) {
575 iint = integrity_iint_find(inode);
576 if (iint)
577 mutex_lock(&iint->mutex);
578 }
579
580 if ((!iint || !(iint->flags & IMA_COLLECTED)) && file) {
581 if (iint)
582 mutex_unlock(&iint->mutex);
583
584 memset(&tmp_iint, 0, sizeof(tmp_iint));
585 tmp_iint.inode = inode;
586 mutex_init(&tmp_iint.mutex);
587
588 rc = ima_collect_measurement(&tmp_iint, file, NULL, 0,
589 ima_hash_algo, NULL);
590 if (rc < 0) {
591 /* ima_hash could be allocated in case of failure. */
592 if (rc != -ENOMEM)
593 kfree(tmp_iint.ima_hash);
594
595 return -EOPNOTSUPP;
596 }
597
598 iint = &tmp_iint;
599 mutex_lock(&iint->mutex);
600 }
601
602 if (!iint)
603 return -EOPNOTSUPP;
604
605 /*
606 * ima_file_hash can be called when ima_collect_measurement has still
607 * not been called, we might not always have a hash.
608 */
609 if (!iint->ima_hash || !(iint->flags & IMA_COLLECTED)) {
610 mutex_unlock(&iint->mutex);
611 return -EOPNOTSUPP;
612 }
613
614 if (buf) {
615 size_t copied_size;
616
617 copied_size = min_t(size_t, iint->ima_hash->length, buf_size);
618 memcpy(buf, iint->ima_hash->digest, copied_size);
619 }
620 hash_algo = iint->ima_hash->algo;
621 mutex_unlock(&iint->mutex);
622
623 if (iint == &tmp_iint)
624 kfree(iint->ima_hash);
625
626 return hash_algo;
627 }
628
629 /**
630 * ima_file_hash - return a measurement of the file
631 * @file: pointer to the file
632 * @buf: buffer in which to store the hash
633 * @buf_size: length of the buffer
634 *
635 * On success, return the hash algorithm (as defined in the enum hash_algo).
636 * If buf is not NULL, this function also outputs the hash into buf.
637 * If the hash is larger than buf_size, then only buf_size bytes will be copied.
638 * It generally just makes sense to pass a buffer capable of holding the largest
639 * possible hash: IMA_MAX_DIGEST_SIZE.
640 * The file hash returned is based on the entire file, including the appended
641 * signature.
642 *
643 * If the measurement cannot be performed, return -EOPNOTSUPP.
644 * If the parameters are incorrect, return -EINVAL.
645 */
ima_file_hash(struct file * file,char * buf,size_t buf_size)646 int ima_file_hash(struct file *file, char *buf, size_t buf_size)
647 {
648 if (!file)
649 return -EINVAL;
650
651 return __ima_inode_hash(file_inode(file), file, buf, buf_size);
652 }
653 EXPORT_SYMBOL_GPL(ima_file_hash);
654
655 /**
656 * ima_inode_hash - return the stored measurement if the inode has been hashed
657 * and is in the iint cache.
658 * @inode: pointer to the inode
659 * @buf: buffer in which to store the hash
660 * @buf_size: length of the buffer
661 *
662 * On success, return the hash algorithm (as defined in the enum hash_algo).
663 * If buf is not NULL, this function also outputs the hash into buf.
664 * If the hash is larger than buf_size, then only buf_size bytes will be copied.
665 * It generally just makes sense to pass a buffer capable of holding the largest
666 * possible hash: IMA_MAX_DIGEST_SIZE.
667 * The hash returned is based on the entire contents, including the appended
668 * signature.
669 *
670 * If IMA is disabled or if no measurement is available, return -EOPNOTSUPP.
671 * If the parameters are incorrect, return -EINVAL.
672 */
ima_inode_hash(struct inode * inode,char * buf,size_t buf_size)673 int ima_inode_hash(struct inode *inode, char *buf, size_t buf_size)
674 {
675 if (!inode)
676 return -EINVAL;
677
678 return __ima_inode_hash(inode, NULL, buf, buf_size);
679 }
680 EXPORT_SYMBOL_GPL(ima_inode_hash);
681
682 /**
683 * ima_post_create_tmpfile - mark newly created tmpfile as new
684 * @idmap: idmap of the mount the inode was found from
685 * @inode: inode of the newly created tmpfile
686 *
687 * No measuring, appraising or auditing of newly created tmpfiles is needed.
688 * Skip calling process_measurement(), but indicate which newly, created
689 * tmpfiles are in policy.
690 */
ima_post_create_tmpfile(struct mnt_idmap * idmap,struct inode * inode)691 void ima_post_create_tmpfile(struct mnt_idmap *idmap,
692 struct inode *inode)
693 {
694 struct integrity_iint_cache *iint;
695 int must_appraise;
696
697 if (!ima_policy_flag || !S_ISREG(inode->i_mode))
698 return;
699
700 must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS,
701 FILE_CHECK);
702 if (!must_appraise)
703 return;
704
705 /* Nothing to do if we can't allocate memory */
706 iint = integrity_inode_get(inode);
707 if (!iint)
708 return;
709
710 /* needed for writing the security xattrs */
711 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
712 iint->ima_file_status = INTEGRITY_PASS;
713 }
714
715 /**
716 * ima_post_path_mknod - mark as a new inode
717 * @idmap: idmap of the mount the inode was found from
718 * @dentry: newly created dentry
719 *
720 * Mark files created via the mknodat syscall as new, so that the
721 * file data can be written later.
722 */
ima_post_path_mknod(struct mnt_idmap * idmap,struct dentry * dentry)723 void ima_post_path_mknod(struct mnt_idmap *idmap,
724 struct dentry *dentry)
725 {
726 struct integrity_iint_cache *iint;
727 struct inode *inode = dentry->d_inode;
728 int must_appraise;
729
730 if (!ima_policy_flag || !S_ISREG(inode->i_mode))
731 return;
732
733 must_appraise = ima_must_appraise(idmap, inode, MAY_ACCESS,
734 FILE_CHECK);
735 if (!must_appraise)
736 return;
737
738 /* Nothing to do if we can't allocate memory */
739 iint = integrity_inode_get(inode);
740 if (!iint)
741 return;
742
743 /* needed for re-opening empty files */
744 iint->flags |= IMA_NEW_FILE;
745 }
746
747 /**
748 * ima_read_file - pre-measure/appraise hook decision based on policy
749 * @file: pointer to the file to be measured/appraised/audit
750 * @read_id: caller identifier
751 * @contents: whether a subsequent call will be made to ima_post_read_file()
752 *
753 * Permit reading a file based on policy. The policy rules are written
754 * in terms of the policy identifier. Appraising the integrity of
755 * a file requires a file descriptor.
756 *
757 * For permission return 0, otherwise return -EACCES.
758 */
ima_read_file(struct file * file,enum kernel_read_file_id read_id,bool contents)759 int ima_read_file(struct file *file, enum kernel_read_file_id read_id,
760 bool contents)
761 {
762 enum ima_hooks func;
763 u32 secid;
764
765 /*
766 * Do devices using pre-allocated memory run the risk of the
767 * firmware being accessible to the device prior to the completion
768 * of IMA's signature verification any more than when using two
769 * buffers? It may be desirable to include the buffer address
770 * in this API and walk all the dma_map_single() mappings to check.
771 */
772
773 /*
774 * There will be a call made to ima_post_read_file() with
775 * a filled buffer, so we don't need to perform an extra
776 * read early here.
777 */
778 if (contents)
779 return 0;
780
781 /* Read entire file for all partial reads. */
782 func = read_idmap[read_id] ?: FILE_CHECK;
783 security_current_getsecid_subj(&secid);
784 return process_measurement(file, current_cred(), secid, NULL,
785 0, MAY_READ, func);
786 }
787
788 const int read_idmap[READING_MAX_ID] = {
789 [READING_FIRMWARE] = FIRMWARE_CHECK,
790 [READING_MODULE] = MODULE_CHECK,
791 [READING_KEXEC_IMAGE] = KEXEC_KERNEL_CHECK,
792 [READING_KEXEC_INITRAMFS] = KEXEC_INITRAMFS_CHECK,
793 [READING_POLICY] = POLICY_CHECK
794 };
795
796 /**
797 * ima_post_read_file - in memory collect/appraise/audit measurement
798 * @file: pointer to the file to be measured/appraised/audit
799 * @buf: pointer to in memory file contents
800 * @size: size of in memory file contents
801 * @read_id: caller identifier
802 *
803 * Measure/appraise/audit in memory file based on policy. Policy rules
804 * are written in terms of a policy identifier.
805 *
806 * On success return 0. On integrity appraisal error, assuming the file
807 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
808 */
ima_post_read_file(struct file * file,void * buf,loff_t size,enum kernel_read_file_id read_id)809 int ima_post_read_file(struct file *file, void *buf, loff_t size,
810 enum kernel_read_file_id read_id)
811 {
812 enum ima_hooks func;
813 u32 secid;
814
815 /* permit signed certs */
816 if (!file && read_id == READING_X509_CERTIFICATE)
817 return 0;
818
819 if (!file || !buf || size == 0) { /* should never happen */
820 if (ima_appraise & IMA_APPRAISE_ENFORCE)
821 return -EACCES;
822 return 0;
823 }
824
825 func = read_idmap[read_id] ?: FILE_CHECK;
826 security_current_getsecid_subj(&secid);
827 return process_measurement(file, current_cred(), secid, buf, size,
828 MAY_READ, func);
829 }
830
831 /**
832 * ima_load_data - appraise decision based on policy
833 * @id: kernel load data caller identifier
834 * @contents: whether the full contents will be available in a later
835 * call to ima_post_load_data().
836 *
837 * Callers of this LSM hook can not measure, appraise, or audit the
838 * data provided by userspace. Enforce policy rules requiring a file
839 * signature (eg. kexec'ed kernel image).
840 *
841 * For permission return 0, otherwise return -EACCES.
842 */
ima_load_data(enum kernel_load_data_id id,bool contents)843 int ima_load_data(enum kernel_load_data_id id, bool contents)
844 {
845 bool ima_enforce, sig_enforce;
846
847 ima_enforce =
848 (ima_appraise & IMA_APPRAISE_ENFORCE) == IMA_APPRAISE_ENFORCE;
849
850 switch (id) {
851 case LOADING_KEXEC_IMAGE:
852 if (IS_ENABLED(CONFIG_KEXEC_SIG)
853 && arch_ima_get_secureboot()) {
854 pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
855 return -EACCES;
856 }
857
858 if (ima_enforce && (ima_appraise & IMA_APPRAISE_KEXEC)) {
859 pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
860 return -EACCES; /* INTEGRITY_UNKNOWN */
861 }
862 break;
863 case LOADING_FIRMWARE:
864 if (ima_enforce && (ima_appraise & IMA_APPRAISE_FIRMWARE) && !contents) {
865 pr_err("Prevent firmware sysfs fallback loading.\n");
866 return -EACCES; /* INTEGRITY_UNKNOWN */
867 }
868 break;
869 case LOADING_MODULE:
870 sig_enforce = is_module_sig_enforced();
871
872 if (ima_enforce && (!sig_enforce
873 && (ima_appraise & IMA_APPRAISE_MODULES))) {
874 pr_err("impossible to appraise a module without a file descriptor. sig_enforce kernel parameter might help\n");
875 return -EACCES; /* INTEGRITY_UNKNOWN */
876 }
877 break;
878 default:
879 break;
880 }
881 return 0;
882 }
883
884 /**
885 * ima_post_load_data - appraise decision based on policy
886 * @buf: pointer to in memory file contents
887 * @size: size of in memory file contents
888 * @load_id: kernel load data caller identifier
889 * @description: @load_id-specific description of contents
890 *
891 * Measure/appraise/audit in memory buffer based on policy. Policy rules
892 * are written in terms of a policy identifier.
893 *
894 * On success return 0. On integrity appraisal error, assuming the file
895 * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
896 */
ima_post_load_data(char * buf,loff_t size,enum kernel_load_data_id load_id,char * description)897 int ima_post_load_data(char *buf, loff_t size,
898 enum kernel_load_data_id load_id,
899 char *description)
900 {
901 if (load_id == LOADING_FIRMWARE) {
902 if ((ima_appraise & IMA_APPRAISE_FIRMWARE) &&
903 (ima_appraise & IMA_APPRAISE_ENFORCE)) {
904 pr_err("Prevent firmware loading_store.\n");
905 return -EACCES; /* INTEGRITY_UNKNOWN */
906 }
907 return 0;
908 }
909
910 return 0;
911 }
912
913 /**
914 * process_buffer_measurement - Measure the buffer or the buffer data hash
915 * @idmap: idmap of the mount the inode was found from
916 * @inode: inode associated with the object being measured (NULL for KEY_CHECK)
917 * @buf: pointer to the buffer that needs to be added to the log.
918 * @size: size of buffer(in bytes).
919 * @eventname: event name to be used for the buffer entry.
920 * @func: IMA hook
921 * @pcr: pcr to extend the measurement
922 * @func_data: func specific data, may be NULL
923 * @buf_hash: measure buffer data hash
924 * @digest: buffer digest will be written to
925 * @digest_len: buffer length
926 *
927 * Based on policy, either the buffer data or buffer data hash is measured
928 *
929 * Return: 0 if the buffer has been successfully measured, 1 if the digest
930 * has been written to the passed location but not added to a measurement entry,
931 * a negative value otherwise.
932 */
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)933 int process_buffer_measurement(struct mnt_idmap *idmap,
934 struct inode *inode, const void *buf, int size,
935 const char *eventname, enum ima_hooks func,
936 int pcr, const char *func_data,
937 bool buf_hash, u8 *digest, size_t digest_len)
938 {
939 int ret = 0;
940 const char *audit_cause = "ENOMEM";
941 struct ima_template_entry *entry = NULL;
942 struct integrity_iint_cache iint = {};
943 struct ima_event_data event_data = {.iint = &iint,
944 .filename = eventname,
945 .buf = buf,
946 .buf_len = size};
947 struct ima_template_desc *template;
948 struct ima_max_digest_data hash;
949 char digest_hash[IMA_MAX_DIGEST_SIZE];
950 int digest_hash_len = hash_digest_size[ima_hash_algo];
951 int violation = 0;
952 int action = 0;
953 u32 secid;
954
955 if (digest && digest_len < digest_hash_len)
956 return -EINVAL;
957
958 if (!ima_policy_flag && !digest)
959 return -ENOENT;
960
961 template = ima_template_desc_buf();
962 if (!template) {
963 ret = -EINVAL;
964 audit_cause = "ima_template_desc_buf";
965 goto out;
966 }
967
968 /*
969 * Both LSM hooks and auxilary based buffer measurements are
970 * based on policy. To avoid code duplication, differentiate
971 * between the LSM hooks and auxilary buffer measurements,
972 * retrieving the policy rule information only for the LSM hook
973 * buffer measurements.
974 */
975 if (func) {
976 security_current_getsecid_subj(&secid);
977 action = ima_get_action(idmap, inode, current_cred(),
978 secid, 0, func, &pcr, &template,
979 func_data, NULL);
980 if (!(action & IMA_MEASURE) && !digest)
981 return -ENOENT;
982 }
983
984 if (!pcr)
985 pcr = CONFIG_IMA_MEASURE_PCR_IDX;
986
987 iint.ima_hash = &hash.hdr;
988 iint.ima_hash->algo = ima_hash_algo;
989 iint.ima_hash->length = hash_digest_size[ima_hash_algo];
990
991 ret = ima_calc_buffer_hash(buf, size, iint.ima_hash);
992 if (ret < 0) {
993 audit_cause = "hashing_error";
994 goto out;
995 }
996
997 if (buf_hash) {
998 memcpy(digest_hash, hash.hdr.digest, digest_hash_len);
999
1000 ret = ima_calc_buffer_hash(digest_hash, digest_hash_len,
1001 iint.ima_hash);
1002 if (ret < 0) {
1003 audit_cause = "hashing_error";
1004 goto out;
1005 }
1006
1007 event_data.buf = digest_hash;
1008 event_data.buf_len = digest_hash_len;
1009 }
1010
1011 if (digest)
1012 memcpy(digest, iint.ima_hash->digest, digest_hash_len);
1013
1014 if (!ima_policy_flag || (func && !(action & IMA_MEASURE)))
1015 return 1;
1016
1017 ret = ima_alloc_init_template(&event_data, &entry, template);
1018 if (ret < 0) {
1019 audit_cause = "alloc_entry";
1020 goto out;
1021 }
1022
1023 ret = ima_store_template(entry, violation, NULL, event_data.buf, pcr);
1024 if (ret < 0) {
1025 audit_cause = "store_entry";
1026 ima_free_template_entry(entry);
1027 }
1028
1029 out:
1030 if (ret < 0)
1031 integrity_audit_message(AUDIT_INTEGRITY_PCR, NULL, eventname,
1032 func_measure_str(func),
1033 audit_cause, ret, 0, ret);
1034
1035 return ret;
1036 }
1037
1038 /**
1039 * ima_kexec_cmdline - measure kexec cmdline boot args
1040 * @kernel_fd: file descriptor of the kexec kernel being loaded
1041 * @buf: pointer to buffer
1042 * @size: size of buffer
1043 *
1044 * Buffers can only be measured, not appraised.
1045 */
ima_kexec_cmdline(int kernel_fd,const void * buf,int size)1046 void ima_kexec_cmdline(int kernel_fd, const void *buf, int size)
1047 {
1048 struct fd f;
1049
1050 if (!buf || !size)
1051 return;
1052
1053 f = fdget(kernel_fd);
1054 if (!f.file)
1055 return;
1056
1057 process_buffer_measurement(file_mnt_idmap(f.file), file_inode(f.file),
1058 buf, size, "kexec-cmdline", KEXEC_CMDLINE, 0,
1059 NULL, false, NULL, 0);
1060 fdput(f);
1061 }
1062
1063 /**
1064 * ima_measure_critical_data - measure kernel integrity critical data
1065 * @event_label: unique event label for grouping and limiting critical data
1066 * @event_name: event name for the record in the IMA measurement list
1067 * @buf: pointer to buffer data
1068 * @buf_len: length of buffer data (in bytes)
1069 * @hash: measure buffer data hash
1070 * @digest: buffer digest will be written to
1071 * @digest_len: buffer length
1072 *
1073 * Measure data critical to the integrity of the kernel into the IMA log
1074 * and extend the pcr. Examples of critical data could be various data
1075 * structures, policies, and states stored in kernel memory that can
1076 * impact the integrity of the system.
1077 *
1078 * Return: 0 if the buffer has been successfully measured, 1 if the digest
1079 * has been written to the passed location but not added to a measurement entry,
1080 * a negative value otherwise.
1081 */
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)1082 int ima_measure_critical_data(const char *event_label,
1083 const char *event_name,
1084 const void *buf, size_t buf_len,
1085 bool hash, u8 *digest, size_t digest_len)
1086 {
1087 if (!event_name || !event_label || !buf || !buf_len)
1088 return -ENOPARAM;
1089
1090 return process_buffer_measurement(&nop_mnt_idmap, NULL, buf, buf_len,
1091 event_name, CRITICAL_DATA, 0,
1092 event_label, hash, digest,
1093 digest_len);
1094 }
1095 EXPORT_SYMBOL_GPL(ima_measure_critical_data);
1096
init_ima(void)1097 static int __init init_ima(void)
1098 {
1099 int error;
1100
1101 ima_appraise_parse_cmdline();
1102 ima_init_template_list();
1103 hash_setup(CONFIG_IMA_DEFAULT_HASH);
1104 error = ima_init();
1105
1106 if (error && strcmp(hash_algo_name[ima_hash_algo],
1107 CONFIG_IMA_DEFAULT_HASH) != 0) {
1108 pr_info("Allocating %s failed, going to use default hash algorithm %s\n",
1109 hash_algo_name[ima_hash_algo], CONFIG_IMA_DEFAULT_HASH);
1110 hash_setup_done = 0;
1111 hash_setup(CONFIG_IMA_DEFAULT_HASH);
1112 error = ima_init();
1113 }
1114
1115 if (error)
1116 return error;
1117
1118 error = register_blocking_lsm_notifier(&ima_lsm_policy_notifier);
1119 if (error)
1120 pr_warn("Couldn't register LSM notifier, error %d\n", error);
1121
1122 if (!error)
1123 ima_update_policy_flags();
1124
1125 return error;
1126 }
1127
1128 late_initcall(init_ima); /* Start IMA after the TPM is available */
1129