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