Merge tag 'reset-for-v5.3' of git://git.pengutronix.de/git/pza/linux into arm/drivers
[sfrench/cifs-2.6.git] / security / integrity / ima / ima_main.c
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 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
19
20 #include <linux/module.h>
21 #include <linux/file.h>
22 #include <linux/binfmts.h>
23 #include <linux/mount.h>
24 #include <linux/mman.h>
25 #include <linux/slab.h>
26 #include <linux/xattr.h>
27 #include <linux/ima.h>
28 #include <linux/iversion.h>
29 #include <linux/fs.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 ima_hash_algo = HASH_ALGO_SHA1;
40 static int hash_setup_done;
41
42 static int __init hash_setup(char *str)
43 {
44         struct ima_template_desc *template_desc = ima_template_desc_current();
45         int i;
46
47         if (hash_setup_done)
48                 return 1;
49
50         if (strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) == 0) {
51                 if (strncmp(str, "sha1", 4) == 0)
52                         ima_hash_algo = HASH_ALGO_SHA1;
53                 else if (strncmp(str, "md5", 3) == 0)
54                         ima_hash_algo = HASH_ALGO_MD5;
55                 else
56                         return 1;
57                 goto out;
58         }
59
60         i = match_string(hash_algo_name, HASH_ALGO__LAST, str);
61         if (i < 0)
62                 return 1;
63
64         ima_hash_algo = i;
65 out:
66         hash_setup_done = 1;
67         return 1;
68 }
69 __setup("ima_hash=", hash_setup);
70
71 /*
72  * ima_rdwr_violation_check
73  *
74  * Only invalidate the PCR for measured files:
75  *      - Opening a file for write when already open for read,
76  *        results in a time of measure, time of use (ToMToU) error.
77  *      - Opening a file for read when already open for write,
78  *        could result in a file measurement error.
79  *
80  */
81 static void ima_rdwr_violation_check(struct file *file,
82                                      struct integrity_iint_cache *iint,
83                                      int must_measure,
84                                      char **pathbuf,
85                                      const char **pathname,
86                                      char *filename)
87 {
88         struct inode *inode = file_inode(file);
89         fmode_t mode = file->f_mode;
90         bool send_tomtou = false, send_writers = false;
91
92         if (mode & FMODE_WRITE) {
93                 if (atomic_read(&inode->i_readcount) && IS_IMA(inode)) {
94                         if (!iint)
95                                 iint = integrity_iint_find(inode);
96                         /* IMA_MEASURE is set from reader side */
97                         if (iint && test_bit(IMA_MUST_MEASURE,
98                                                 &iint->atomic_flags))
99                                 send_tomtou = true;
100                 }
101         } else {
102                 if (must_measure)
103                         set_bit(IMA_MUST_MEASURE, &iint->atomic_flags);
104                 if (inode_is_open_for_write(inode) && must_measure)
105                         send_writers = true;
106         }
107
108         if (!send_tomtou && !send_writers)
109                 return;
110
111         *pathname = ima_d_path(&file->f_path, pathbuf, filename);
112
113         if (send_tomtou)
114                 ima_add_violation(file, *pathname, iint,
115                                   "invalid_pcr", "ToMToU");
116         if (send_writers)
117                 ima_add_violation(file, *pathname, iint,
118                                   "invalid_pcr", "open_writers");
119 }
120
121 static void ima_check_last_writer(struct integrity_iint_cache *iint,
122                                   struct inode *inode, struct file *file)
123 {
124         fmode_t mode = file->f_mode;
125         bool update;
126
127         if (!(mode & FMODE_WRITE))
128                 return;
129
130         mutex_lock(&iint->mutex);
131         if (atomic_read(&inode->i_writecount) == 1) {
132                 update = test_and_clear_bit(IMA_UPDATE_XATTR,
133                                             &iint->atomic_flags);
134                 if (!IS_I_VERSION(inode) ||
135                     !inode_eq_iversion(inode, iint->version) ||
136                     (iint->flags & IMA_NEW_FILE)) {
137                         iint->flags &= ~(IMA_DONE_MASK | IMA_NEW_FILE);
138                         iint->measured_pcrs = 0;
139                         if (update)
140                                 ima_update_xattr(iint, file);
141                 }
142         }
143         mutex_unlock(&iint->mutex);
144 }
145
146 /**
147  * ima_file_free - called on __fput()
148  * @file: pointer to file structure being freed
149  *
150  * Flag files that changed, based on i_version
151  */
152 void ima_file_free(struct file *file)
153 {
154         struct inode *inode = file_inode(file);
155         struct integrity_iint_cache *iint;
156
157         if (!ima_policy_flag || !S_ISREG(inode->i_mode))
158                 return;
159
160         iint = integrity_iint_find(inode);
161         if (!iint)
162                 return;
163
164         ima_check_last_writer(iint, inode, file);
165 }
166
167 static int process_measurement(struct file *file, const struct cred *cred,
168                                u32 secid, char *buf, loff_t size, int mask,
169                                enum ima_hooks func)
170 {
171         struct inode *inode = file_inode(file);
172         struct integrity_iint_cache *iint = NULL;
173         struct ima_template_desc *template_desc;
174         char *pathbuf = NULL;
175         char filename[NAME_MAX];
176         const char *pathname = NULL;
177         int rc = 0, action, must_appraise = 0;
178         int pcr = CONFIG_IMA_MEASURE_PCR_IDX;
179         struct evm_ima_xattr_data *xattr_value = NULL;
180         int xattr_len = 0;
181         bool violation_check;
182         enum hash_algo hash_algo;
183
184         if (!ima_policy_flag || !S_ISREG(inode->i_mode))
185                 return 0;
186
187         /* Return an IMA_MEASURE, IMA_APPRAISE, IMA_AUDIT action
188          * bitmask based on the appraise/audit/measurement policy.
189          * Included is the appraise submask.
190          */
191         action = ima_get_action(inode, cred, secid, mask, func, &pcr);
192         violation_check = ((func == FILE_CHECK || func == MMAP_CHECK) &&
193                            (ima_policy_flag & IMA_MEASURE));
194         if (!action && !violation_check)
195                 return 0;
196
197         must_appraise = action & IMA_APPRAISE;
198
199         /*  Is the appraise rule hook specific?  */
200         if (action & IMA_FILE_APPRAISE)
201                 func = FILE_CHECK;
202
203         inode_lock(inode);
204
205         if (action) {
206                 iint = integrity_inode_get(inode);
207                 if (!iint)
208                         rc = -ENOMEM;
209         }
210
211         if (!rc && violation_check)
212                 ima_rdwr_violation_check(file, iint, action & IMA_MEASURE,
213                                          &pathbuf, &pathname, filename);
214
215         inode_unlock(inode);
216
217         if (rc)
218                 goto out;
219         if (!action)
220                 goto out;
221
222         mutex_lock(&iint->mutex);
223
224         if (test_and_clear_bit(IMA_CHANGE_ATTR, &iint->atomic_flags))
225                 /* reset appraisal flags if ima_inode_post_setattr was called */
226                 iint->flags &= ~(IMA_APPRAISE | IMA_APPRAISED |
227                                  IMA_APPRAISE_SUBMASK | IMA_APPRAISED_SUBMASK |
228                                  IMA_ACTION_FLAGS);
229
230         /*
231          * Re-evaulate the file if either the xattr has changed or the
232          * kernel has no way of detecting file change on the filesystem.
233          * (Limited to privileged mounted filesystems.)
234          */
235         if (test_and_clear_bit(IMA_CHANGE_XATTR, &iint->atomic_flags) ||
236             ((inode->i_sb->s_iflags & SB_I_IMA_UNVERIFIABLE_SIGNATURE) &&
237              !(inode->i_sb->s_iflags & SB_I_UNTRUSTED_MOUNTER) &&
238              !(action & IMA_FAIL_UNVERIFIABLE_SIGS))) {
239                 iint->flags &= ~IMA_DONE_MASK;
240                 iint->measured_pcrs = 0;
241         }
242
243         /* Determine if already appraised/measured based on bitmask
244          * (IMA_MEASURE, IMA_MEASURED, IMA_XXXX_APPRAISE, IMA_XXXX_APPRAISED,
245          *  IMA_AUDIT, IMA_AUDITED)
246          */
247         iint->flags |= action;
248         action &= IMA_DO_MASK;
249         action &= ~((iint->flags & (IMA_DONE_MASK ^ IMA_MEASURED)) >> 1);
250
251         /* If target pcr is already measured, unset IMA_MEASURE action */
252         if ((action & IMA_MEASURE) && (iint->measured_pcrs & (0x1 << pcr)))
253                 action ^= IMA_MEASURE;
254
255         /* HASH sets the digital signature and update flags, nothing else */
256         if ((action & IMA_HASH) &&
257             !(test_bit(IMA_DIGSIG, &iint->atomic_flags))) {
258                 xattr_len = ima_read_xattr(file_dentry(file), &xattr_value);
259                 if ((xattr_value && xattr_len > 2) &&
260                     (xattr_value->type == EVM_IMA_XATTR_DIGSIG))
261                         set_bit(IMA_DIGSIG, &iint->atomic_flags);
262                 iint->flags |= IMA_HASHED;
263                 action ^= IMA_HASH;
264                 set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
265         }
266
267         /* Nothing to do, just return existing appraised status */
268         if (!action) {
269                 if (must_appraise)
270                         rc = ima_get_cache_status(iint, func);
271                 goto out_locked;
272         }
273
274         template_desc = ima_template_desc_current();
275         if ((action & IMA_APPRAISE_SUBMASK) ||
276                     strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) != 0)
277                 /* read 'security.ima' */
278                 xattr_len = ima_read_xattr(file_dentry(file), &xattr_value);
279
280         hash_algo = ima_get_hash_algo(xattr_value, xattr_len);
281
282         rc = ima_collect_measurement(iint, file, buf, size, hash_algo);
283         if (rc != 0 && rc != -EBADF && rc != -EINVAL)
284                 goto out_locked;
285
286         if (!pathbuf)   /* ima_rdwr_violation possibly pre-fetched */
287                 pathname = ima_d_path(&file->f_path, &pathbuf, filename);
288
289         if (action & IMA_MEASURE)
290                 ima_store_measurement(iint, file, pathname,
291                                       xattr_value, xattr_len, pcr);
292         if (rc == 0 && (action & IMA_APPRAISE_SUBMASK)) {
293                 inode_lock(inode);
294                 rc = ima_appraise_measurement(func, iint, file, pathname,
295                                               xattr_value, xattr_len);
296                 inode_unlock(inode);
297         }
298         if (action & IMA_AUDIT)
299                 ima_audit_measurement(iint, pathname);
300
301         if ((file->f_flags & O_DIRECT) && (iint->flags & IMA_PERMIT_DIRECTIO))
302                 rc = 0;
303 out_locked:
304         if ((mask & MAY_WRITE) && test_bit(IMA_DIGSIG, &iint->atomic_flags) &&
305              !(iint->flags & IMA_NEW_FILE))
306                 rc = -EACCES;
307         mutex_unlock(&iint->mutex);
308         kfree(xattr_value);
309 out:
310         if (pathbuf)
311                 __putname(pathbuf);
312         if (must_appraise) {
313                 if (rc && (ima_appraise & IMA_APPRAISE_ENFORCE))
314                         return -EACCES;
315                 if (file->f_mode & FMODE_WRITE)
316                         set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
317         }
318         return 0;
319 }
320
321 /**
322  * ima_file_mmap - based on policy, collect/store measurement.
323  * @file: pointer to the file to be measured (May be NULL)
324  * @prot: contains the protection that will be applied by the kernel.
325  *
326  * Measure files being mmapped executable based on the ima_must_measure()
327  * policy decision.
328  *
329  * On success return 0.  On integrity appraisal error, assuming the file
330  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
331  */
332 int ima_file_mmap(struct file *file, unsigned long prot)
333 {
334         u32 secid;
335
336         if (file && (prot & PROT_EXEC)) {
337                 security_task_getsecid(current, &secid);
338                 return process_measurement(file, current_cred(), secid, NULL,
339                                            0, MAY_EXEC, MMAP_CHECK);
340         }
341
342         return 0;
343 }
344
345 /**
346  * ima_bprm_check - based on policy, collect/store measurement.
347  * @bprm: contains the linux_binprm structure
348  *
349  * The OS protects against an executable file, already open for write,
350  * from being executed in deny_write_access() and an executable file,
351  * already open for execute, from being modified in get_write_access().
352  * So we can be certain that what we verify and measure here is actually
353  * what is being executed.
354  *
355  * On success return 0.  On integrity appraisal error, assuming the file
356  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
357  */
358 int ima_bprm_check(struct linux_binprm *bprm)
359 {
360         int ret;
361         u32 secid;
362
363         security_task_getsecid(current, &secid);
364         ret = process_measurement(bprm->file, current_cred(), secid, NULL, 0,
365                                   MAY_EXEC, BPRM_CHECK);
366         if (ret)
367                 return ret;
368
369         security_cred_getsecid(bprm->cred, &secid);
370         return process_measurement(bprm->file, bprm->cred, secid, NULL, 0,
371                                    MAY_EXEC, CREDS_CHECK);
372 }
373
374 /**
375  * ima_path_check - based on policy, collect/store measurement.
376  * @file: pointer to the file to be measured
377  * @mask: contains MAY_READ, MAY_WRITE, MAY_EXEC or MAY_APPEND
378  *
379  * Measure files based on the ima_must_measure() policy decision.
380  *
381  * On success return 0.  On integrity appraisal error, assuming the file
382  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
383  */
384 int ima_file_check(struct file *file, int mask)
385 {
386         u32 secid;
387
388         security_task_getsecid(current, &secid);
389         return process_measurement(file, current_cred(), secid, NULL, 0,
390                                    mask & (MAY_READ | MAY_WRITE | MAY_EXEC |
391                                            MAY_APPEND), FILE_CHECK);
392 }
393 EXPORT_SYMBOL_GPL(ima_file_check);
394
395 /**
396  * ima_post_create_tmpfile - mark newly created tmpfile as new
397  * @file : newly created tmpfile
398  *
399  * No measuring, appraising or auditing of newly created tmpfiles is needed.
400  * Skip calling process_measurement(), but indicate which newly, created
401  * tmpfiles are in policy.
402  */
403 void ima_post_create_tmpfile(struct inode *inode)
404 {
405         struct integrity_iint_cache *iint;
406         int must_appraise;
407
408         must_appraise = ima_must_appraise(inode, MAY_ACCESS, FILE_CHECK);
409         if (!must_appraise)
410                 return;
411
412         /* Nothing to do if we can't allocate memory */
413         iint = integrity_inode_get(inode);
414         if (!iint)
415                 return;
416
417         /* needed for writing the security xattrs */
418         set_bit(IMA_UPDATE_XATTR, &iint->atomic_flags);
419         iint->ima_file_status = INTEGRITY_PASS;
420 }
421
422 /**
423  * ima_post_path_mknod - mark as a new inode
424  * @dentry: newly created dentry
425  *
426  * Mark files created via the mknodat syscall as new, so that the
427  * file data can be written later.
428  */
429 void ima_post_path_mknod(struct dentry *dentry)
430 {
431         struct integrity_iint_cache *iint;
432         struct inode *inode = dentry->d_inode;
433         int must_appraise;
434
435         must_appraise = ima_must_appraise(inode, MAY_ACCESS, FILE_CHECK);
436         if (!must_appraise)
437                 return;
438
439         /* Nothing to do if we can't allocate memory */
440         iint = integrity_inode_get(inode);
441         if (!iint)
442                 return;
443
444         /* needed for re-opening empty files */
445         iint->flags |= IMA_NEW_FILE;
446 }
447
448 /**
449  * ima_read_file - pre-measure/appraise hook decision based on policy
450  * @file: pointer to the file to be measured/appraised/audit
451  * @read_id: caller identifier
452  *
453  * Permit reading a file based on policy. The policy rules are written
454  * in terms of the policy identifier.  Appraising the integrity of
455  * a file requires a file descriptor.
456  *
457  * For permission return 0, otherwise return -EACCES.
458  */
459 int ima_read_file(struct file *file, enum kernel_read_file_id read_id)
460 {
461         /*
462          * READING_FIRMWARE_PREALLOC_BUFFER
463          *
464          * Do devices using pre-allocated memory run the risk of the
465          * firmware being accessible to the device prior to the completion
466          * of IMA's signature verification any more than when using two
467          * buffers?
468          */
469         return 0;
470 }
471
472 static const int read_idmap[READING_MAX_ID] = {
473         [READING_FIRMWARE] = FIRMWARE_CHECK,
474         [READING_FIRMWARE_PREALLOC_BUFFER] = FIRMWARE_CHECK,
475         [READING_MODULE] = MODULE_CHECK,
476         [READING_KEXEC_IMAGE] = KEXEC_KERNEL_CHECK,
477         [READING_KEXEC_INITRAMFS] = KEXEC_INITRAMFS_CHECK,
478         [READING_POLICY] = POLICY_CHECK
479 };
480
481 /**
482  * ima_post_read_file - in memory collect/appraise/audit measurement
483  * @file: pointer to the file to be measured/appraised/audit
484  * @buf: pointer to in memory file contents
485  * @size: size of in memory file contents
486  * @read_id: caller identifier
487  *
488  * Measure/appraise/audit in memory file based on policy.  Policy rules
489  * are written in terms of a policy identifier.
490  *
491  * On success return 0.  On integrity appraisal error, assuming the file
492  * is in policy and IMA-appraisal is in enforcing mode, return -EACCES.
493  */
494 int ima_post_read_file(struct file *file, void *buf, loff_t size,
495                        enum kernel_read_file_id read_id)
496 {
497         enum ima_hooks func;
498         u32 secid;
499
500         if (!file && read_id == READING_FIRMWARE) {
501                 if ((ima_appraise & IMA_APPRAISE_FIRMWARE) &&
502                     (ima_appraise & IMA_APPRAISE_ENFORCE)) {
503                         pr_err("Prevent firmware loading_store.\n");
504                         return -EACCES; /* INTEGRITY_UNKNOWN */
505                 }
506                 return 0;
507         }
508
509         /* permit signed certs */
510         if (!file && read_id == READING_X509_CERTIFICATE)
511                 return 0;
512
513         if (!file || !buf || size == 0) { /* should never happen */
514                 if (ima_appraise & IMA_APPRAISE_ENFORCE)
515                         return -EACCES;
516                 return 0;
517         }
518
519         func = read_idmap[read_id] ?: FILE_CHECK;
520         security_task_getsecid(current, &secid);
521         return process_measurement(file, current_cred(), secid, buf, size,
522                                    MAY_READ, func);
523 }
524
525 /**
526  * ima_load_data - appraise decision based on policy
527  * @id: kernel load data caller identifier
528  *
529  * Callers of this LSM hook can not measure, appraise, or audit the
530  * data provided by userspace.  Enforce policy rules requring a file
531  * signature (eg. kexec'ed kernel image).
532  *
533  * For permission return 0, otherwise return -EACCES.
534  */
535 int ima_load_data(enum kernel_load_data_id id)
536 {
537         bool ima_enforce, sig_enforce;
538
539         ima_enforce =
540                 (ima_appraise & IMA_APPRAISE_ENFORCE) == IMA_APPRAISE_ENFORCE;
541
542         switch (id) {
543         case LOADING_KEXEC_IMAGE:
544                 if (IS_ENABLED(CONFIG_KEXEC_VERIFY_SIG)
545                     && arch_ima_get_secureboot()) {
546                         pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
547                         return -EACCES;
548                 }
549
550                 if (ima_enforce && (ima_appraise & IMA_APPRAISE_KEXEC)) {
551                         pr_err("impossible to appraise a kernel image without a file descriptor; try using kexec_file_load syscall.\n");
552                         return -EACCES; /* INTEGRITY_UNKNOWN */
553                 }
554                 break;
555         case LOADING_FIRMWARE:
556                 if (ima_enforce && (ima_appraise & IMA_APPRAISE_FIRMWARE)) {
557                         pr_err("Prevent firmware sysfs fallback loading.\n");
558                         return -EACCES; /* INTEGRITY_UNKNOWN */
559                 }
560                 break;
561         case LOADING_MODULE:
562                 sig_enforce = is_module_sig_enforced();
563
564                 if (ima_enforce && (!sig_enforce
565                                     && (ima_appraise & IMA_APPRAISE_MODULES))) {
566                         pr_err("impossible to appraise a module without a file descriptor. sig_enforce kernel parameter might help\n");
567                         return -EACCES; /* INTEGRITY_UNKNOWN */
568                 }
569         default:
570                 break;
571         }
572         return 0;
573 }
574
575 static int __init init_ima(void)
576 {
577         int error;
578
579         ima_init_template_list();
580         hash_setup(CONFIG_IMA_DEFAULT_HASH);
581         error = ima_init();
582
583         if (error && strcmp(hash_algo_name[ima_hash_algo],
584                             CONFIG_IMA_DEFAULT_HASH) != 0) {
585                 pr_info("Allocating %s failed, going to use default hash algorithm %s\n",
586                         hash_algo_name[ima_hash_algo], CONFIG_IMA_DEFAULT_HASH);
587                 hash_setup_done = 0;
588                 hash_setup(CONFIG_IMA_DEFAULT_HASH);
589                 error = ima_init();
590         }
591
592         if (!error)
593                 ima_update_policy_flag();
594
595         return error;
596 }
597
598 late_initcall(init_ima);        /* Start IMA after the TPM is available */