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