cfb4f980936951f14d98a16f8c723442a85a8086
[linux-2.6-block.git] / security / integrity / evm / evm_main.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2005-2010 IBM Corporation
4  *
5  * Author:
6  * Mimi Zohar <zohar@us.ibm.com>
7  * Kylene Hall <kjhall@us.ibm.com>
8  *
9  * File: evm_main.c
10  *      implements evm_inode_setxattr, evm_inode_post_setxattr,
11  *      evm_inode_removexattr, evm_verifyxattr, and evm_inode_set_acl.
12  */
13
14 #define pr_fmt(fmt) "EVM: "fmt
15
16 #include <linux/init.h>
17 #include <linux/audit.h>
18 #include <linux/xattr.h>
19 #include <linux/integrity.h>
20 #include <linux/evm.h>
21 #include <linux/magic.h>
22 #include <linux/posix_acl_xattr.h>
23 #include <linux/lsm_hooks.h>
24
25 #include <crypto/hash.h>
26 #include <crypto/hash_info.h>
27 #include <crypto/utils.h>
28 #include "evm.h"
29
30 int evm_initialized;
31
32 static const char * const integrity_status_msg[] = {
33         "pass", "pass_immutable", "fail", "fail_immutable", "no_label",
34         "no_xattrs", "unknown"
35 };
36 int evm_hmac_attrs;
37
38 static struct xattr_list evm_config_default_xattrnames[] = {
39         {
40          .name = XATTR_NAME_SELINUX,
41          .enabled = IS_ENABLED(CONFIG_SECURITY_SELINUX)
42         },
43         {
44          .name = XATTR_NAME_SMACK,
45          .enabled = IS_ENABLED(CONFIG_SECURITY_SMACK)
46         },
47         {
48          .name = XATTR_NAME_SMACKEXEC,
49          .enabled = IS_ENABLED(CONFIG_EVM_EXTRA_SMACK_XATTRS)
50         },
51         {
52          .name = XATTR_NAME_SMACKTRANSMUTE,
53          .enabled = IS_ENABLED(CONFIG_EVM_EXTRA_SMACK_XATTRS)
54         },
55         {
56          .name = XATTR_NAME_SMACKMMAP,
57          .enabled = IS_ENABLED(CONFIG_EVM_EXTRA_SMACK_XATTRS)
58         },
59         {
60          .name = XATTR_NAME_APPARMOR,
61          .enabled = IS_ENABLED(CONFIG_SECURITY_APPARMOR)
62         },
63         {
64          .name = XATTR_NAME_IMA,
65          .enabled = IS_ENABLED(CONFIG_IMA_APPRAISE)
66         },
67         {
68          .name = XATTR_NAME_CAPS,
69          .enabled = true
70         },
71 };
72
73 LIST_HEAD(evm_config_xattrnames);
74
75 static int evm_fixmode __ro_after_init;
76 static int __init evm_set_fixmode(char *str)
77 {
78         if (strncmp(str, "fix", 3) == 0)
79                 evm_fixmode = 1;
80         else
81                 pr_err("invalid \"%s\" mode", str);
82
83         return 1;
84 }
85 __setup("evm=", evm_set_fixmode);
86
87 static void __init evm_init_config(void)
88 {
89         int i, xattrs;
90
91         xattrs = ARRAY_SIZE(evm_config_default_xattrnames);
92
93         pr_info("Initialising EVM extended attributes:\n");
94         for (i = 0; i < xattrs; i++) {
95                 pr_info("%s%s\n", evm_config_default_xattrnames[i].name,
96                         !evm_config_default_xattrnames[i].enabled ?
97                         " (disabled)" : "");
98                 list_add_tail(&evm_config_default_xattrnames[i].list,
99                               &evm_config_xattrnames);
100         }
101
102 #ifdef CONFIG_EVM_ATTR_FSUUID
103         evm_hmac_attrs |= EVM_ATTR_FSUUID;
104 #endif
105         pr_info("HMAC attrs: 0x%x\n", evm_hmac_attrs);
106 }
107
108 static bool evm_key_loaded(void)
109 {
110         return (bool)(evm_initialized & EVM_KEY_MASK);
111 }
112
113 /*
114  * This function determines whether or not it is safe to ignore verification
115  * errors, based on the ability of EVM to calculate HMACs. If the HMAC key
116  * is not loaded, and it cannot be loaded in the future due to the
117  * EVM_SETUP_COMPLETE initialization flag, allowing an operation despite the
118  * attrs/xattrs being found invalid will not make them valid.
119  */
120 static bool evm_hmac_disabled(void)
121 {
122         if (evm_initialized & EVM_INIT_HMAC)
123                 return false;
124
125         if (!(evm_initialized & EVM_SETUP_COMPLETE))
126                 return false;
127
128         return true;
129 }
130
131 static int evm_find_protected_xattrs(struct dentry *dentry)
132 {
133         struct inode *inode = d_backing_inode(dentry);
134         struct xattr_list *xattr;
135         int error;
136         int count = 0;
137
138         if (!(inode->i_opflags & IOP_XATTR))
139                 return -EOPNOTSUPP;
140
141         list_for_each_entry_lockless(xattr, &evm_config_xattrnames, list) {
142                 error = __vfs_getxattr(dentry, inode, xattr->name, NULL, 0);
143                 if (error < 0) {
144                         if (error == -ENODATA)
145                                 continue;
146                         return error;
147                 }
148                 count++;
149         }
150
151         return count;
152 }
153
154 static int is_unsupported_fs(struct dentry *dentry)
155 {
156         struct inode *inode = d_backing_inode(dentry);
157
158         if (inode->i_sb->s_iflags & SB_I_EVM_UNSUPPORTED) {
159                 pr_info_once("%s not supported\n", inode->i_sb->s_type->name);
160                 return 1;
161         }
162         return 0;
163 }
164
165 /*
166  * evm_verify_hmac - calculate and compare the HMAC with the EVM xattr
167  *
168  * Compute the HMAC on the dentry's protected set of extended attributes
169  * and compare it against the stored security.evm xattr.
170  *
171  * For performance:
172  * - use the previoulsy retrieved xattr value and length to calculate the
173  *   HMAC.)
174  * - cache the verification result in the iint, when available.
175  *
176  * Returns integrity status
177  */
178 static enum integrity_status evm_verify_hmac(struct dentry *dentry,
179                                              const char *xattr_name,
180                                              char *xattr_value,
181                                              size_t xattr_value_len)
182 {
183         struct evm_ima_xattr_data *xattr_data = NULL;
184         struct signature_v2_hdr *hdr;
185         enum integrity_status evm_status = INTEGRITY_PASS;
186         struct evm_digest digest;
187         struct inode *inode = d_backing_inode(dentry);
188         struct evm_iint_cache *iint = evm_iint_inode(inode);
189         int rc, xattr_len, evm_immutable = 0;
190
191         if (iint && (iint->evm_status == INTEGRITY_PASS ||
192                      iint->evm_status == INTEGRITY_PASS_IMMUTABLE))
193                 return iint->evm_status;
194
195         /*
196          * On unsupported filesystems without EVM_INIT_X509 enabled, skip
197          * signature verification.
198          */
199         if (!(evm_initialized & EVM_INIT_X509) && is_unsupported_fs(dentry))
200                 return INTEGRITY_UNKNOWN;
201
202         /* if status is not PASS, try to check again - against -ENOMEM */
203
204         /* first need to know the sig type */
205         rc = vfs_getxattr_alloc(&nop_mnt_idmap, dentry, XATTR_NAME_EVM,
206                                 (char **)&xattr_data, 0, GFP_NOFS);
207         if (rc <= 0) {
208                 evm_status = INTEGRITY_FAIL;
209                 if (rc == -ENODATA) {
210                         rc = evm_find_protected_xattrs(dentry);
211                         if (rc > 0)
212                                 evm_status = INTEGRITY_NOLABEL;
213                         else if (rc == 0)
214                                 evm_status = INTEGRITY_NOXATTRS; /* new file */
215                 } else if (rc == -EOPNOTSUPP) {
216                         evm_status = INTEGRITY_UNKNOWN;
217                 }
218                 goto out;
219         }
220
221         xattr_len = rc;
222
223         /* check value type */
224         switch (xattr_data->type) {
225         case EVM_XATTR_HMAC:
226                 if (xattr_len != sizeof(struct evm_xattr)) {
227                         evm_status = INTEGRITY_FAIL;
228                         goto out;
229                 }
230
231                 digest.hdr.algo = HASH_ALGO_SHA1;
232                 rc = evm_calc_hmac(dentry, xattr_name, xattr_value,
233                                    xattr_value_len, &digest, iint);
234                 if (rc)
235                         break;
236                 rc = crypto_memneq(xattr_data->data, digest.digest,
237                                    SHA1_DIGEST_SIZE);
238                 if (rc)
239                         rc = -EINVAL;
240                 break;
241         case EVM_XATTR_PORTABLE_DIGSIG:
242                 evm_immutable = 1;
243                 fallthrough;
244         case EVM_IMA_XATTR_DIGSIG:
245                 /* accept xattr with non-empty signature field */
246                 if (xattr_len <= sizeof(struct signature_v2_hdr)) {
247                         evm_status = INTEGRITY_FAIL;
248                         goto out;
249                 }
250
251                 hdr = (struct signature_v2_hdr *)xattr_data;
252                 digest.hdr.algo = hdr->hash_algo;
253                 rc = evm_calc_hash(dentry, xattr_name, xattr_value,
254                                    xattr_value_len, xattr_data->type, &digest,
255                                    iint);
256                 if (rc)
257                         break;
258                 rc = integrity_digsig_verify(INTEGRITY_KEYRING_EVM,
259                                         (const char *)xattr_data, xattr_len,
260                                         digest.digest, digest.hdr.length);
261                 if (!rc) {
262                         if (xattr_data->type == EVM_XATTR_PORTABLE_DIGSIG) {
263                                 if (iint)
264                                         iint->flags |= EVM_IMMUTABLE_DIGSIG;
265                                 evm_status = INTEGRITY_PASS_IMMUTABLE;
266                         } else if (!IS_RDONLY(inode) &&
267                                    !(inode->i_sb->s_readonly_remount) &&
268                                    !IS_IMMUTABLE(inode) &&
269                                    !is_unsupported_fs(dentry)) {
270                                 evm_update_evmxattr(dentry, xattr_name,
271                                                     xattr_value,
272                                                     xattr_value_len);
273                         }
274                 }
275                 break;
276         default:
277                 rc = -EINVAL;
278                 break;
279         }
280
281         if (rc) {
282                 if (rc == -ENODATA)
283                         evm_status = INTEGRITY_NOXATTRS;
284                 else if (evm_immutable)
285                         evm_status = INTEGRITY_FAIL_IMMUTABLE;
286                 else
287                         evm_status = INTEGRITY_FAIL;
288         }
289         pr_debug("digest: (%d) [%*phN]\n", digest.hdr.length, digest.hdr.length,
290                   digest.digest);
291 out:
292         if (iint)
293                 iint->evm_status = evm_status;
294         kfree(xattr_data);
295         return evm_status;
296 }
297
298 static int evm_protected_xattr_common(const char *req_xattr_name,
299                                       bool all_xattrs)
300 {
301         int namelen;
302         int found = 0;
303         struct xattr_list *xattr;
304
305         namelen = strlen(req_xattr_name);
306         list_for_each_entry_lockless(xattr, &evm_config_xattrnames, list) {
307                 if (!all_xattrs && !xattr->enabled)
308                         continue;
309
310                 if ((strlen(xattr->name) == namelen)
311                     && (strncmp(req_xattr_name, xattr->name, namelen) == 0)) {
312                         found = 1;
313                         break;
314                 }
315                 if (strncmp(req_xattr_name,
316                             xattr->name + XATTR_SECURITY_PREFIX_LEN,
317                             strlen(req_xattr_name)) == 0) {
318                         found = 1;
319                         break;
320                 }
321         }
322
323         return found;
324 }
325
326 int evm_protected_xattr(const char *req_xattr_name)
327 {
328         return evm_protected_xattr_common(req_xattr_name, false);
329 }
330
331 int evm_protected_xattr_if_enabled(const char *req_xattr_name)
332 {
333         return evm_protected_xattr_common(req_xattr_name, true);
334 }
335
336 /**
337  * evm_read_protected_xattrs - read EVM protected xattr names, lengths, values
338  * @dentry: dentry of the read xattrs
339  * @buffer: buffer xattr names, lengths or values are copied to
340  * @buffer_size: size of buffer
341  * @type: n: names, l: lengths, v: values
342  * @canonical_fmt: data format (true: little endian, false: native format)
343  *
344  * Read protected xattr names (separated by |), lengths (u32) or values for a
345  * given dentry and return the total size of copied data. If buffer is NULL,
346  * just return the total size.
347  *
348  * Returns the total size on success, a negative value on error.
349  */
350 int evm_read_protected_xattrs(struct dentry *dentry, u8 *buffer,
351                               int buffer_size, char type, bool canonical_fmt)
352 {
353         struct xattr_list *xattr;
354         int rc, size, total_size = 0;
355
356         list_for_each_entry_lockless(xattr, &evm_config_xattrnames, list) {
357                 rc = __vfs_getxattr(dentry, d_backing_inode(dentry),
358                                     xattr->name, NULL, 0);
359                 if (rc < 0 && rc == -ENODATA)
360                         continue;
361                 else if (rc < 0)
362                         return rc;
363
364                 switch (type) {
365                 case 'n':
366                         size = strlen(xattr->name) + 1;
367                         if (buffer) {
368                                 if (total_size)
369                                         *(buffer + total_size - 1) = '|';
370
371                                 memcpy(buffer + total_size, xattr->name, size);
372                         }
373                         break;
374                 case 'l':
375                         size = sizeof(u32);
376                         if (buffer) {
377                                 if (canonical_fmt)
378                                         rc = (__force int)cpu_to_le32(rc);
379
380                                 *(u32 *)(buffer + total_size) = rc;
381                         }
382                         break;
383                 case 'v':
384                         size = rc;
385                         if (buffer) {
386                                 rc = __vfs_getxattr(dentry,
387                                         d_backing_inode(dentry), xattr->name,
388                                         buffer + total_size,
389                                         buffer_size - total_size);
390                                 if (rc < 0)
391                                         return rc;
392                         }
393                         break;
394                 default:
395                         return -EINVAL;
396                 }
397
398                 total_size += size;
399         }
400
401         return total_size;
402 }
403
404 /**
405  * evm_verifyxattr - verify the integrity of the requested xattr
406  * @dentry: object of the verify xattr
407  * @xattr_name: requested xattr
408  * @xattr_value: requested xattr value
409  * @xattr_value_len: requested xattr value length
410  *
411  * Calculate the HMAC for the given dentry and verify it against the stored
412  * security.evm xattr. For performance, use the xattr value and length
413  * previously retrieved to calculate the HMAC.
414  *
415  * Returns the xattr integrity status.
416  *
417  * This function requires the caller to lock the inode's i_mutex before it
418  * is executed.
419  */
420 enum integrity_status evm_verifyxattr(struct dentry *dentry,
421                                       const char *xattr_name,
422                                       void *xattr_value, size_t xattr_value_len)
423 {
424         if (!evm_key_loaded() || !evm_protected_xattr(xattr_name))
425                 return INTEGRITY_UNKNOWN;
426
427         return evm_verify_hmac(dentry, xattr_name, xattr_value,
428                                  xattr_value_len);
429 }
430 EXPORT_SYMBOL_GPL(evm_verifyxattr);
431
432 /*
433  * evm_verify_current_integrity - verify the dentry's metadata integrity
434  * @dentry: pointer to the affected dentry
435  *
436  * Verify and return the dentry's metadata integrity. The exceptions are
437  * before EVM is initialized or in 'fix' mode.
438  */
439 static enum integrity_status evm_verify_current_integrity(struct dentry *dentry)
440 {
441         struct inode *inode = d_backing_inode(dentry);
442
443         if (!evm_key_loaded() || !S_ISREG(inode->i_mode) || evm_fixmode)
444                 return INTEGRITY_PASS;
445         return evm_verify_hmac(dentry, NULL, NULL, 0);
446 }
447
448 /*
449  * evm_xattr_change - check if passed xattr value differs from current value
450  * @idmap: idmap of the mount
451  * @dentry: pointer to the affected dentry
452  * @xattr_name: requested xattr
453  * @xattr_value: requested xattr value
454  * @xattr_value_len: requested xattr value length
455  *
456  * Check if passed xattr value differs from current value.
457  *
458  * Returns 1 if passed xattr value differs from current value, 0 otherwise.
459  */
460 static int evm_xattr_change(struct mnt_idmap *idmap,
461                             struct dentry *dentry, const char *xattr_name,
462                             const void *xattr_value, size_t xattr_value_len)
463 {
464         char *xattr_data = NULL;
465         int rc = 0;
466
467         rc = vfs_getxattr_alloc(&nop_mnt_idmap, dentry, xattr_name, &xattr_data,
468                                 0, GFP_NOFS);
469         if (rc < 0) {
470                 rc = 1;
471                 goto out;
472         }
473
474         if (rc == xattr_value_len)
475                 rc = !!memcmp(xattr_value, xattr_data, rc);
476         else
477                 rc = 1;
478
479 out:
480         kfree(xattr_data);
481         return rc;
482 }
483
484 /*
485  * evm_protect_xattr - protect the EVM extended attribute
486  *
487  * Prevent security.evm from being modified or removed without the
488  * necessary permissions or when the existing value is invalid.
489  *
490  * The posix xattr acls are 'system' prefixed, which normally would not
491  * affect security.evm.  An interesting side affect of writing posix xattr
492  * acls is their modifying of the i_mode, which is included in security.evm.
493  * For posix xattr acls only, permit security.evm, even if it currently
494  * doesn't exist, to be updated unless the EVM signature is immutable.
495  */
496 static int evm_protect_xattr(struct mnt_idmap *idmap,
497                              struct dentry *dentry, const char *xattr_name,
498                              const void *xattr_value, size_t xattr_value_len)
499 {
500         enum integrity_status evm_status;
501
502         if (strcmp(xattr_name, XATTR_NAME_EVM) == 0) {
503                 if (!capable(CAP_SYS_ADMIN))
504                         return -EPERM;
505                 if (is_unsupported_fs(dentry))
506                         return -EPERM;
507         } else if (!evm_protected_xattr(xattr_name)) {
508                 if (!posix_xattr_acl(xattr_name))
509                         return 0;
510                 if (is_unsupported_fs(dentry))
511                         return 0;
512
513                 evm_status = evm_verify_current_integrity(dentry);
514                 if ((evm_status == INTEGRITY_PASS) ||
515                     (evm_status == INTEGRITY_NOXATTRS))
516                         return 0;
517                 goto out;
518         } else if (is_unsupported_fs(dentry))
519                 return 0;
520
521         evm_status = evm_verify_current_integrity(dentry);
522         if (evm_status == INTEGRITY_NOXATTRS) {
523                 struct evm_iint_cache *iint;
524
525                 /* Exception if the HMAC is not going to be calculated. */
526                 if (evm_hmac_disabled())
527                         return 0;
528
529                 iint = evm_iint_inode(d_backing_inode(dentry));
530                 if (iint && (iint->flags & EVM_NEW_FILE))
531                         return 0;
532
533                 /* exception for pseudo filesystems */
534                 if (dentry->d_sb->s_magic == TMPFS_MAGIC
535                     || dentry->d_sb->s_magic == SYSFS_MAGIC)
536                         return 0;
537
538                 integrity_audit_msg(AUDIT_INTEGRITY_METADATA,
539                                     dentry->d_inode, dentry->d_name.name,
540                                     "update_metadata",
541                                     integrity_status_msg[evm_status],
542                                     -EPERM, 0);
543         }
544 out:
545         /* Exception if the HMAC is not going to be calculated. */
546         if (evm_hmac_disabled() && (evm_status == INTEGRITY_NOLABEL ||
547             evm_status == INTEGRITY_UNKNOWN))
548                 return 0;
549
550         /*
551          * Writing other xattrs is safe for portable signatures, as portable
552          * signatures are immutable and can never be updated.
553          */
554         if (evm_status == INTEGRITY_FAIL_IMMUTABLE)
555                 return 0;
556
557         if (evm_status == INTEGRITY_PASS_IMMUTABLE &&
558             !evm_xattr_change(idmap, dentry, xattr_name, xattr_value,
559                               xattr_value_len))
560                 return 0;
561
562         if (evm_status != INTEGRITY_PASS &&
563             evm_status != INTEGRITY_PASS_IMMUTABLE)
564                 integrity_audit_msg(AUDIT_INTEGRITY_METADATA, d_backing_inode(dentry),
565                                     dentry->d_name.name, "appraise_metadata",
566                                     integrity_status_msg[evm_status],
567                                     -EPERM, 0);
568         return evm_status == INTEGRITY_PASS ? 0 : -EPERM;
569 }
570
571 /**
572  * evm_inode_setxattr - protect the EVM extended attribute
573  * @idmap: idmap of the mount
574  * @dentry: pointer to the affected dentry
575  * @xattr_name: pointer to the affected extended attribute name
576  * @xattr_value: pointer to the new extended attribute value
577  * @xattr_value_len: pointer to the new extended attribute value length
578  * @flags: flags to pass into filesystem operations
579  *
580  * Before allowing the 'security.evm' protected xattr to be updated,
581  * verify the existing value is valid.  As only the kernel should have
582  * access to the EVM encrypted key needed to calculate the HMAC, prevent
583  * userspace from writing HMAC value.  Writing 'security.evm' requires
584  * requires CAP_SYS_ADMIN privileges.
585  */
586 static int evm_inode_setxattr(struct mnt_idmap *idmap, struct dentry *dentry,
587                               const char *xattr_name, const void *xattr_value,
588                               size_t xattr_value_len, int flags)
589 {
590         const struct evm_ima_xattr_data *xattr_data = xattr_value;
591
592         /* Policy permits modification of the protected xattrs even though
593          * there's no HMAC key loaded
594          */
595         if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
596                 return 0;
597
598         if (strcmp(xattr_name, XATTR_NAME_EVM) == 0) {
599                 if (!xattr_value_len)
600                         return -EINVAL;
601                 if (xattr_data->type != EVM_IMA_XATTR_DIGSIG &&
602                     xattr_data->type != EVM_XATTR_PORTABLE_DIGSIG)
603                         return -EPERM;
604         }
605         return evm_protect_xattr(idmap, dentry, xattr_name, xattr_value,
606                                  xattr_value_len);
607 }
608
609 /**
610  * evm_inode_removexattr - protect the EVM extended attribute
611  * @idmap: idmap of the mount
612  * @dentry: pointer to the affected dentry
613  * @xattr_name: pointer to the affected extended attribute name
614  *
615  * Removing 'security.evm' requires CAP_SYS_ADMIN privileges and that
616  * the current value is valid.
617  */
618 static int evm_inode_removexattr(struct mnt_idmap *idmap, struct dentry *dentry,
619                                  const char *xattr_name)
620 {
621         /* Policy permits modification of the protected xattrs even though
622          * there's no HMAC key loaded
623          */
624         if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
625                 return 0;
626
627         return evm_protect_xattr(idmap, dentry, xattr_name, NULL, 0);
628 }
629
630 #ifdef CONFIG_FS_POSIX_ACL
631 static int evm_inode_set_acl_change(struct mnt_idmap *idmap,
632                                     struct dentry *dentry, const char *name,
633                                     struct posix_acl *kacl)
634 {
635         int rc;
636
637         umode_t mode;
638         struct inode *inode = d_backing_inode(dentry);
639
640         if (!kacl)
641                 return 1;
642
643         rc = posix_acl_update_mode(idmap, inode, &mode, &kacl);
644         if (rc || (inode->i_mode != mode))
645                 return 1;
646
647         return 0;
648 }
649 #else
650 static inline int evm_inode_set_acl_change(struct mnt_idmap *idmap,
651                                            struct dentry *dentry,
652                                            const char *name,
653                                            struct posix_acl *kacl)
654 {
655         return 0;
656 }
657 #endif
658
659 /**
660  * evm_inode_set_acl - protect the EVM extended attribute from posix acls
661  * @idmap: idmap of the idmapped mount
662  * @dentry: pointer to the affected dentry
663  * @acl_name: name of the posix acl
664  * @kacl: pointer to the posix acls
665  *
666  * Prevent modifying posix acls causing the EVM HMAC to be re-calculated
667  * and 'security.evm' xattr updated, unless the existing 'security.evm' is
668  * valid.
669  *
670  * Return: zero on success, -EPERM on failure.
671  */
672 static int evm_inode_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
673                              const char *acl_name, struct posix_acl *kacl)
674 {
675         enum integrity_status evm_status;
676
677         /* Policy permits modification of the protected xattrs even though
678          * there's no HMAC key loaded
679          */
680         if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
681                 return 0;
682
683         evm_status = evm_verify_current_integrity(dentry);
684         if ((evm_status == INTEGRITY_PASS) ||
685             (evm_status == INTEGRITY_NOXATTRS))
686                 return 0;
687
688         /* Exception if the HMAC is not going to be calculated. */
689         if (evm_hmac_disabled() && (evm_status == INTEGRITY_NOLABEL ||
690             evm_status == INTEGRITY_UNKNOWN))
691                 return 0;
692
693         /*
694          * Writing other xattrs is safe for portable signatures, as portable
695          * signatures are immutable and can never be updated.
696          */
697         if (evm_status == INTEGRITY_FAIL_IMMUTABLE)
698                 return 0;
699
700         if (evm_status == INTEGRITY_PASS_IMMUTABLE &&
701             !evm_inode_set_acl_change(idmap, dentry, acl_name, kacl))
702                 return 0;
703
704         if (evm_status != INTEGRITY_PASS_IMMUTABLE)
705                 integrity_audit_msg(AUDIT_INTEGRITY_METADATA, d_backing_inode(dentry),
706                                     dentry->d_name.name, "appraise_metadata",
707                                     integrity_status_msg[evm_status],
708                                     -EPERM, 0);
709         return -EPERM;
710 }
711
712 /**
713  * evm_inode_remove_acl - Protect the EVM extended attribute from posix acls
714  * @idmap: idmap of the mount
715  * @dentry: pointer to the affected dentry
716  * @acl_name: name of the posix acl
717  *
718  * Prevent removing posix acls causing the EVM HMAC to be re-calculated
719  * and 'security.evm' xattr updated, unless the existing 'security.evm' is
720  * valid.
721  *
722  * Return: zero on success, -EPERM on failure.
723  */
724 static int evm_inode_remove_acl(struct mnt_idmap *idmap, struct dentry *dentry,
725                                 const char *acl_name)
726 {
727         return evm_inode_set_acl(idmap, dentry, acl_name, NULL);
728 }
729
730 static void evm_reset_status(struct inode *inode)
731 {
732         struct evm_iint_cache *iint;
733
734         iint = evm_iint_inode(inode);
735         if (iint)
736                 iint->evm_status = INTEGRITY_UNKNOWN;
737 }
738
739 /**
740  * evm_metadata_changed: Detect changes to the metadata
741  * @inode: a file's inode
742  * @metadata_inode: metadata inode
743  *
744  * On a stacked filesystem detect whether the metadata has changed. If this is
745  * the case reset the evm_status associated with the inode that represents the
746  * file.
747  */
748 bool evm_metadata_changed(struct inode *inode, struct inode *metadata_inode)
749 {
750         struct evm_iint_cache *iint = evm_iint_inode(inode);
751         bool ret = false;
752
753         if (iint) {
754                 ret = (!IS_I_VERSION(metadata_inode) ||
755                        integrity_inode_attrs_changed(&iint->metadata_inode,
756                                                      metadata_inode));
757                 if (ret)
758                         iint->evm_status = INTEGRITY_UNKNOWN;
759         }
760
761         return ret;
762 }
763
764 /**
765  * evm_revalidate_status - report whether EVM status re-validation is necessary
766  * @xattr_name: pointer to the affected extended attribute name
767  *
768  * Report whether callers of evm_verifyxattr() should re-validate the
769  * EVM status.
770  *
771  * Return true if re-validation is necessary, false otherwise.
772  */
773 bool evm_revalidate_status(const char *xattr_name)
774 {
775         if (!evm_key_loaded())
776                 return false;
777
778         /* evm_inode_post_setattr() passes NULL */
779         if (!xattr_name)
780                 return true;
781
782         if (!evm_protected_xattr(xattr_name) && !posix_xattr_acl(xattr_name) &&
783             strcmp(xattr_name, XATTR_NAME_EVM))
784                 return false;
785
786         return true;
787 }
788
789 /**
790  * evm_inode_post_setxattr - update 'security.evm' to reflect the changes
791  * @dentry: pointer to the affected dentry
792  * @xattr_name: pointer to the affected extended attribute name
793  * @xattr_value: pointer to the new extended attribute value
794  * @xattr_value_len: pointer to the new extended attribute value length
795  * @flags: flags to pass into filesystem operations
796  *
797  * Update the HMAC stored in 'security.evm' to reflect the change.
798  *
799  * No need to take the i_mutex lock here, as this function is called from
800  * __vfs_setxattr_noperm().  The caller of which has taken the inode's
801  * i_mutex lock.
802  */
803 static void evm_inode_post_setxattr(struct dentry *dentry,
804                                     const char *xattr_name,
805                                     const void *xattr_value,
806                                     size_t xattr_value_len,
807                                     int flags)
808 {
809         if (!evm_revalidate_status(xattr_name))
810                 return;
811
812         evm_reset_status(dentry->d_inode);
813
814         if (!strcmp(xattr_name, XATTR_NAME_EVM))
815                 return;
816
817         if (!(evm_initialized & EVM_INIT_HMAC))
818                 return;
819
820         if (is_unsupported_fs(dentry))
821                 return;
822
823         evm_update_evmxattr(dentry, xattr_name, xattr_value, xattr_value_len);
824 }
825
826 /**
827  * evm_inode_post_set_acl - Update the EVM extended attribute from posix acls
828  * @dentry: pointer to the affected dentry
829  * @acl_name: name of the posix acl
830  * @kacl: pointer to the posix acls
831  *
832  * Update the 'security.evm' xattr with the EVM HMAC re-calculated after setting
833  * posix acls.
834  */
835 static void evm_inode_post_set_acl(struct dentry *dentry, const char *acl_name,
836                                    struct posix_acl *kacl)
837 {
838         return evm_inode_post_setxattr(dentry, acl_name, NULL, 0, 0);
839 }
840
841 /**
842  * evm_inode_post_removexattr - update 'security.evm' after removing the xattr
843  * @dentry: pointer to the affected dentry
844  * @xattr_name: pointer to the affected extended attribute name
845  *
846  * Update the HMAC stored in 'security.evm' to reflect removal of the xattr.
847  *
848  * No need to take the i_mutex lock here, as this function is called from
849  * vfs_removexattr() which takes the i_mutex.
850  */
851 static void evm_inode_post_removexattr(struct dentry *dentry,
852                                        const char *xattr_name)
853 {
854         if (!evm_revalidate_status(xattr_name))
855                 return;
856
857         evm_reset_status(dentry->d_inode);
858
859         if (!strcmp(xattr_name, XATTR_NAME_EVM))
860                 return;
861
862         if (!(evm_initialized & EVM_INIT_HMAC))
863                 return;
864
865         evm_update_evmxattr(dentry, xattr_name, NULL, 0);
866 }
867
868 /**
869  * evm_inode_post_remove_acl - Update the EVM extended attribute from posix acls
870  * @idmap: idmap of the mount
871  * @dentry: pointer to the affected dentry
872  * @acl_name: name of the posix acl
873  *
874  * Update the 'security.evm' xattr with the EVM HMAC re-calculated after
875  * removing posix acls.
876  */
877 static inline void evm_inode_post_remove_acl(struct mnt_idmap *idmap,
878                                              struct dentry *dentry,
879                                              const char *acl_name)
880 {
881         evm_inode_post_removexattr(dentry, acl_name);
882 }
883
884 static int evm_attr_change(struct mnt_idmap *idmap,
885                            struct dentry *dentry, struct iattr *attr)
886 {
887         struct inode *inode = d_backing_inode(dentry);
888         unsigned int ia_valid = attr->ia_valid;
889
890         if (!i_uid_needs_update(idmap, attr, inode) &&
891             !i_gid_needs_update(idmap, attr, inode) &&
892             (!(ia_valid & ATTR_MODE) || attr->ia_mode == inode->i_mode))
893                 return 0;
894
895         return 1;
896 }
897
898 /**
899  * evm_inode_setattr - prevent updating an invalid EVM extended attribute
900  * @idmap: idmap of the mount
901  * @dentry: pointer to the affected dentry
902  * @attr: iattr structure containing the new file attributes
903  *
904  * Permit update of file attributes when files have a valid EVM signature,
905  * except in the case of them having an immutable portable signature.
906  */
907 static int evm_inode_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
908                              struct iattr *attr)
909 {
910         unsigned int ia_valid = attr->ia_valid;
911         enum integrity_status evm_status;
912
913         /* Policy permits modification of the protected attrs even though
914          * there's no HMAC key loaded
915          */
916         if (evm_initialized & EVM_ALLOW_METADATA_WRITES)
917                 return 0;
918
919         if (is_unsupported_fs(dentry))
920                 return 0;
921
922         if (!(ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID)))
923                 return 0;
924
925         evm_status = evm_verify_current_integrity(dentry);
926         /*
927          * Writing attrs is safe for portable signatures, as portable signatures
928          * are immutable and can never be updated.
929          */
930         if ((evm_status == INTEGRITY_PASS) ||
931             (evm_status == INTEGRITY_NOXATTRS) ||
932             (evm_status == INTEGRITY_FAIL_IMMUTABLE) ||
933             (evm_hmac_disabled() && (evm_status == INTEGRITY_NOLABEL ||
934              evm_status == INTEGRITY_UNKNOWN)))
935                 return 0;
936
937         if (evm_status == INTEGRITY_PASS_IMMUTABLE &&
938             !evm_attr_change(idmap, dentry, attr))
939                 return 0;
940
941         integrity_audit_msg(AUDIT_INTEGRITY_METADATA, d_backing_inode(dentry),
942                             dentry->d_name.name, "appraise_metadata",
943                             integrity_status_msg[evm_status], -EPERM, 0);
944         return -EPERM;
945 }
946
947 /**
948  * evm_inode_post_setattr - update 'security.evm' after modifying metadata
949  * @idmap: idmap of the idmapped mount
950  * @dentry: pointer to the affected dentry
951  * @ia_valid: for the UID and GID status
952  *
953  * For now, update the HMAC stored in 'security.evm' to reflect UID/GID
954  * changes.
955  *
956  * This function is called from notify_change(), which expects the caller
957  * to lock the inode's i_mutex.
958  */
959 static void evm_inode_post_setattr(struct mnt_idmap *idmap,
960                                    struct dentry *dentry, int ia_valid)
961 {
962         if (!evm_revalidate_status(NULL))
963                 return;
964
965         evm_reset_status(dentry->d_inode);
966
967         if (!(evm_initialized & EVM_INIT_HMAC))
968                 return;
969
970         if (is_unsupported_fs(dentry))
971                 return;
972
973         if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID))
974                 evm_update_evmxattr(dentry, NULL, NULL, 0);
975 }
976
977 static int evm_inode_copy_up_xattr(struct dentry *src, const char *name)
978 {
979         struct evm_ima_xattr_data *xattr_data = NULL;
980         int rc;
981
982         if (strcmp(name, XATTR_NAME_EVM) != 0)
983                 return -EOPNOTSUPP;
984
985         /* first need to know the sig type */
986         rc = vfs_getxattr_alloc(&nop_mnt_idmap, src, XATTR_NAME_EVM,
987                                 (char **)&xattr_data, 0, GFP_NOFS);
988         if (rc <= 0)
989                 return -EPERM;
990
991         if (rc < offsetof(struct evm_ima_xattr_data, type) +
992                  sizeof(xattr_data->type))
993                 return -EPERM;
994
995         switch (xattr_data->type) {
996         case EVM_XATTR_PORTABLE_DIGSIG:
997                 rc = 0; /* allow copy-up */
998                 break;
999         case EVM_XATTR_HMAC:
1000         case EVM_IMA_XATTR_DIGSIG:
1001         default:
1002                 rc = 1; /* discard */
1003         }
1004
1005         kfree(xattr_data);
1006         return rc;
1007 }
1008
1009 /*
1010  * evm_inode_init_security - initializes security.evm HMAC value
1011  */
1012 int evm_inode_init_security(struct inode *inode, struct inode *dir,
1013                             const struct qstr *qstr, struct xattr *xattrs,
1014                             int *xattr_count)
1015 {
1016         struct evm_xattr *xattr_data;
1017         struct xattr *xattr, *evm_xattr;
1018         bool evm_protected_xattrs = false;
1019         int rc;
1020
1021         if (!(evm_initialized & EVM_INIT_HMAC) || !xattrs)
1022                 return 0;
1023
1024         /*
1025          * security_inode_init_security() makes sure that the xattrs array is
1026          * contiguous, there is enough space for security.evm, and that there is
1027          * a terminator at the end of the array.
1028          */
1029         for (xattr = xattrs; xattr->name; xattr++) {
1030                 if (evm_protected_xattr(xattr->name))
1031                         evm_protected_xattrs = true;
1032         }
1033
1034         /* EVM xattr not needed. */
1035         if (!evm_protected_xattrs)
1036                 return 0;
1037
1038         evm_xattr = lsm_get_xattr_slot(xattrs, xattr_count);
1039         /*
1040          * Array terminator (xattr name = NULL) must be the first non-filled
1041          * xattr slot.
1042          */
1043         WARN_ONCE(evm_xattr != xattr,
1044                   "%s: xattrs terminator is not the first non-filled slot\n",
1045                   __func__);
1046
1047         xattr_data = kzalloc(sizeof(*xattr_data), GFP_NOFS);
1048         if (!xattr_data)
1049                 return -ENOMEM;
1050
1051         xattr_data->data.type = EVM_XATTR_HMAC;
1052         rc = evm_init_hmac(inode, xattrs, xattr_data->digest);
1053         if (rc < 0)
1054                 goto out;
1055
1056         evm_xattr->value = xattr_data;
1057         evm_xattr->value_len = sizeof(*xattr_data);
1058         evm_xattr->name = XATTR_EVM_SUFFIX;
1059         return 0;
1060 out:
1061         kfree(xattr_data);
1062         return rc;
1063 }
1064 EXPORT_SYMBOL_GPL(evm_inode_init_security);
1065
1066 static int evm_inode_alloc_security(struct inode *inode)
1067 {
1068         struct evm_iint_cache *iint = evm_iint_inode(inode);
1069
1070         /* Called by security_inode_alloc(), it cannot be NULL. */
1071         iint->flags = 0UL;
1072         iint->evm_status = INTEGRITY_UNKNOWN;
1073
1074         return 0;
1075 }
1076
1077 static void evm_file_release(struct file *file)
1078 {
1079         struct inode *inode = file_inode(file);
1080         struct evm_iint_cache *iint = evm_iint_inode(inode);
1081         fmode_t mode = file->f_mode;
1082
1083         if (!S_ISREG(inode->i_mode) || !(mode & FMODE_WRITE))
1084                 return;
1085
1086         if (iint && atomic_read(&inode->i_writecount) == 1)
1087                 iint->flags &= ~EVM_NEW_FILE;
1088 }
1089
1090 static void evm_post_path_mknod(struct mnt_idmap *idmap, struct dentry *dentry)
1091 {
1092         struct inode *inode = d_backing_inode(dentry);
1093         struct evm_iint_cache *iint = evm_iint_inode(inode);
1094
1095         if (!S_ISREG(inode->i_mode))
1096                 return;
1097
1098         if (iint)
1099                 iint->flags |= EVM_NEW_FILE;
1100 }
1101
1102 #ifdef CONFIG_EVM_LOAD_X509
1103 void __init evm_load_x509(void)
1104 {
1105         int rc;
1106
1107         rc = integrity_load_x509(INTEGRITY_KEYRING_EVM, CONFIG_EVM_X509_PATH);
1108         if (!rc)
1109                 evm_initialized |= EVM_INIT_X509;
1110 }
1111 #endif
1112
1113 static int __init init_evm(void)
1114 {
1115         int error;
1116         struct list_head *pos, *q;
1117
1118         evm_init_config();
1119
1120         error = integrity_init_keyring(INTEGRITY_KEYRING_EVM);
1121         if (error)
1122                 goto error;
1123
1124         error = evm_init_secfs();
1125         if (error < 0) {
1126                 pr_info("Error registering secfs\n");
1127                 goto error;
1128         }
1129
1130 error:
1131         if (error != 0) {
1132                 if (!list_empty(&evm_config_xattrnames)) {
1133                         list_for_each_safe(pos, q, &evm_config_xattrnames)
1134                                 list_del(pos);
1135                 }
1136         }
1137
1138         return error;
1139 }
1140
1141 static struct security_hook_list evm_hooks[] __ro_after_init = {
1142         LSM_HOOK_INIT(inode_setattr, evm_inode_setattr),
1143         LSM_HOOK_INIT(inode_post_setattr, evm_inode_post_setattr),
1144         LSM_HOOK_INIT(inode_copy_up_xattr, evm_inode_copy_up_xattr),
1145         LSM_HOOK_INIT(inode_setxattr, evm_inode_setxattr),
1146         LSM_HOOK_INIT(inode_post_setxattr, evm_inode_post_setxattr),
1147         LSM_HOOK_INIT(inode_set_acl, evm_inode_set_acl),
1148         LSM_HOOK_INIT(inode_post_set_acl, evm_inode_post_set_acl),
1149         LSM_HOOK_INIT(inode_remove_acl, evm_inode_remove_acl),
1150         LSM_HOOK_INIT(inode_post_remove_acl, evm_inode_post_remove_acl),
1151         LSM_HOOK_INIT(inode_removexattr, evm_inode_removexattr),
1152         LSM_HOOK_INIT(inode_post_removexattr, evm_inode_post_removexattr),
1153         LSM_HOOK_INIT(inode_init_security, evm_inode_init_security),
1154         LSM_HOOK_INIT(inode_alloc_security, evm_inode_alloc_security),
1155         LSM_HOOK_INIT(file_release, evm_file_release),
1156         LSM_HOOK_INIT(path_post_mknod, evm_post_path_mknod),
1157 };
1158
1159 static const struct lsm_id evm_lsmid = {
1160         .name = "evm",
1161         .id = LSM_ID_EVM,
1162 };
1163
1164 static int __init init_evm_lsm(void)
1165 {
1166         security_add_hooks(evm_hooks, ARRAY_SIZE(evm_hooks), &evm_lsmid);
1167         return 0;
1168 }
1169
1170 struct lsm_blob_sizes evm_blob_sizes __ro_after_init = {
1171         .lbs_inode = sizeof(struct evm_iint_cache),
1172         .lbs_xattr_count = 1,
1173 };
1174
1175 DEFINE_LSM(evm) = {
1176         .name = "evm",
1177         .init = init_evm_lsm,
1178         .order = LSM_ORDER_LAST,
1179         .blobs = &evm_blob_sizes,
1180 };
1181
1182 late_initcall(init_evm);