aboutsummaryrefslogtreecommitdiffstats
path: root/security
diff options
context:
space:
mode:
authorJames Morris <james.l.morris@oracle.com>2017-12-11 01:01:08 -0500
committerJames Morris <james.l.morris@oracle.com>2017-12-11 01:01:08 -0500
commitd21bd6898336a7892914d308d5e0868f0b863571 (patch)
treef5f756c25348b5a6c1ce9ddbaa7d1ecd1bef40b0 /security
parent34d8751fd4ffa34e85ee7e85d34168b3f3f62b42 (diff)
parent50c4c4e268a2d7a3e58ebb698ac74da0de40ae36 (diff)
Sync to v4.15-rc3 for security subsystem developers to work against.
Diffstat (limited to 'security')
-rw-r--r--security/Makefile1
-rw-r--r--security/apparmor/.gitignore1
-rw-r--r--security/apparmor/Makefile44
-rw-r--r--security/apparmor/apparmorfs.c25
-rw-r--r--security/apparmor/domain.c68
-rw-r--r--security/apparmor/file.c38
-rw-r--r--security/apparmor/include/audit.h16
-rw-r--r--security/apparmor/include/lib.h13
-rw-r--r--security/apparmor/include/net.h114
-rw-r--r--security/apparmor/include/perms.h5
-rw-r--r--security/apparmor/include/policy.h13
-rw-r--r--security/apparmor/ipc.c4
-rw-r--r--security/apparmor/label.c10
-rw-r--r--security/apparmor/lib.c21
-rw-r--r--security/apparmor/lsm.c411
-rw-r--r--security/apparmor/mount.c13
-rw-r--r--security/apparmor/net.c184
-rw-r--r--security/apparmor/policy.c11
-rw-r--r--security/apparmor/policy_ns.c8
-rw-r--r--security/apparmor/policy_unpack.c49
-rw-r--r--security/apparmor/resource.c4
-rw-r--r--security/commoncap.c3
-rw-r--r--security/device_cgroup.c92
-rw-r--r--security/integrity/Makefile1
-rw-r--r--security/integrity/digsig.c14
-rw-r--r--security/integrity/evm/evm.h3
-rw-r--r--security/integrity/evm/evm_crypto.c2
-rw-r--r--security/integrity/evm/evm_main.c3
-rw-r--r--security/integrity/evm/evm_secfs.c29
-rw-r--r--security/integrity/iint.c49
-rw-r--r--security/integrity/ima/Makefile1
-rw-r--r--security/integrity/ima/ima_api.c67
-rw-r--r--security/integrity/ima/ima_appraise.c7
-rw-r--r--security/integrity/ima/ima_crypto.c66
-rw-r--r--security/integrity/ima/ima_fs.c6
-rw-r--r--security/integrity/ima/ima_main.c23
-rw-r--r--security/integrity/ima/ima_policy.c6
-rw-r--r--security/integrity/integrity.h2
-rw-r--r--security/keys/Kconfig5
-rw-r--r--security/keys/Makefile1
-rw-r--r--security/keys/big_key.c143
-rw-r--r--security/keys/encrypted-keys/Makefile1
-rw-r--r--security/keys/encrypted-keys/encrypted.c9
-rw-r--r--security/keys/encrypted-keys/encrypted.h1
-rw-r--r--security/keys/gc.c34
-rw-r--r--security/keys/internal.h10
-rw-r--r--security/keys/key.c75
-rw-r--r--security/keys/keyctl.c38
-rw-r--r--security/keys/keyring.c102
-rw-r--r--security/keys/permission.c8
-rw-r--r--security/keys/proc.c54
-rw-r--r--security/keys/process_keys.c10
-rw-r--r--security/keys/request_key.c55
-rw-r--r--security/keys/request_key_auth.c76
-rw-r--r--security/keys/trusted.c25
-rw-r--r--security/keys/trusted.h1
-rw-r--r--security/keys/user_defined.c4
-rw-r--r--security/min_addr.c1
-rw-r--r--security/security.c32
-rw-r--r--security/selinux/Makefile1
-rw-r--r--security/selinux/hooks.c215
-rw-r--r--security/selinux/include/avc.h1
-rw-r--r--security/selinux/include/avc_ss.h1
-rw-r--r--security/selinux/include/classmap.h3
-rw-r--r--security/selinux/include/initial_sid_to_string.h1
-rw-r--r--security/selinux/include/objsec.h4
-rw-r--r--security/selinux/include/security.h1
-rw-r--r--security/selinux/include/xfrm.h1
-rw-r--r--security/selinux/ss/conditional.c1
-rw-r--r--security/selinux/ss/constraint.h1
-rw-r--r--security/selinux/ss/context.h1
-rw-r--r--security/selinux/ss/ebitmap.c1
-rw-r--r--security/selinux/ss/ebitmap.h1
-rw-r--r--security/selinux/ss/hashtab.c20
-rw-r--r--security/selinux/ss/hashtab.h5
-rw-r--r--security/selinux/ss/mls.c1
-rw-r--r--security/selinux/ss/mls.h1
-rw-r--r--security/selinux/ss/mls_types.h1
-rw-r--r--security/selinux/ss/services.c4
-rw-r--r--security/selinux/ss/services.h1
-rw-r--r--security/selinux/ss/sidtab.c1
-rw-r--r--security/selinux/ss/sidtab.h1
-rw-r--r--security/selinux/ss/symtab.c1
-rw-r--r--security/selinux/ss/symtab.h1
-rw-r--r--security/smack/smack_lsm.c55
-rw-r--r--security/tomoyo/Makefile1
-rw-r--r--security/tomoyo/audit.c1
-rw-r--r--security/tomoyo/common.c1
-rw-r--r--security/tomoyo/common.h1
-rw-r--r--security/tomoyo/condition.c1
-rw-r--r--security/tomoyo/domain.c1
-rw-r--r--security/tomoyo/environ.c1
-rw-r--r--security/tomoyo/file.c1
-rw-r--r--security/tomoyo/gc.c1
-rw-r--r--security/tomoyo/group.c1
-rw-r--r--security/tomoyo/load_policy.c1
-rw-r--r--security/tomoyo/memory.c1
-rw-r--r--security/tomoyo/mount.c1
-rw-r--r--security/tomoyo/network.c1
-rw-r--r--security/tomoyo/realpath.c1
-rw-r--r--security/tomoyo/securityfs_if.c1
-rw-r--r--security/tomoyo/tomoyo.c1
-rw-r--r--security/tomoyo/util.c1
103 files changed, 932 insertions, 1523 deletions
diff --git a/security/Makefile b/security/Makefile
index f2d71cdb8e19..4d2d3782ddef 100644
--- a/security/Makefile
+++ b/security/Makefile
@@ -1,3 +1,4 @@
1# SPDX-License-Identifier: GPL-2.0
1# 2#
2# Makefile for the kernel security code 3# Makefile for the kernel security code
3# 4#
diff --git a/security/apparmor/.gitignore b/security/apparmor/.gitignore
index d5b291e94264..9cdec70d72b8 100644
--- a/security/apparmor/.gitignore
+++ b/security/apparmor/.gitignore
@@ -1,6 +1,5 @@
1# 1#
2# Generated include files 2# Generated include files
3# 3#
4net_names.h
5capability_names.h 4capability_names.h
6rlim_names.h 5rlim_names.h
diff --git a/security/apparmor/Makefile b/security/apparmor/Makefile
index dafdd387d42b..9a6b4033d52b 100644
--- a/security/apparmor/Makefile
+++ b/security/apparmor/Makefile
@@ -1,47 +1,15 @@
1# SPDX-License-Identifier: GPL-2.0
1# Makefile for AppArmor Linux Security Module 2# Makefile for AppArmor Linux Security Module
2# 3#
3obj-$(CONFIG_SECURITY_APPARMOR) += apparmor.o 4obj-$(CONFIG_SECURITY_APPARMOR) += apparmor.o
4 5
5apparmor-y := apparmorfs.o audit.o capability.o context.o ipc.o lib.o match.o \ 6apparmor-y := apparmorfs.o audit.o capability.o context.o ipc.o lib.o match.o \
6 path.o domain.o policy.o policy_unpack.o procattr.o lsm.o \ 7 path.o domain.o policy.o policy_unpack.o procattr.o lsm.o \
7 resource.o secid.o file.o policy_ns.o label.o mount.o net.o 8 resource.o secid.o file.o policy_ns.o label.o mount.o
8apparmor-$(CONFIG_SECURITY_APPARMOR_HASH) += crypto.o 9apparmor-$(CONFIG_SECURITY_APPARMOR_HASH) += crypto.o
9 10
10clean-files := capability_names.h rlim_names.h net_names.h 11clean-files := capability_names.h rlim_names.h
11 12
12# Build a lower case string table of address family names
13# Transform lines from
14# #define AF_LOCAL 1 /* POSIX name for AF_UNIX */
15# #define AF_INET 2 /* Internet IP Protocol */
16# to
17# [1] = "local",
18# [2] = "inet",
19#
20# and build the securityfs entries for the mapping.
21# Transforms lines from
22# #define AF_INET 2 /* Internet IP Protocol */
23# to
24# #define AA_SFS_AF_MASK "local inet"
25quiet_cmd_make-af = GEN $@
26cmd_make-af = echo "static const char *address_family_names[] = {" > $@ ;\
27 sed $< >>$@ -r -n -e "/AF_MAX/d" -e "/AF_LOCAL/d" -e "/AF_ROUTE/d" -e \
28 's/^\#define[ \t]+AF_([A-Z0-9_]+)[ \t]+([0-9]+)(.*)/[\2] = "\L\1",/p';\
29 echo "};" >> $@ ;\
30 printf '%s' '\#define AA_SFS_AF_MASK "' >> $@ ;\
31 sed -r -n -e "/AF_MAX/d" -e "/AF_LOCAL/d" -e "/AF_ROUTE/d" -e \
32 's/^\#define[ \t]+AF_([A-Z0-9_]+)[ \t]+([0-9]+)(.*)/\L\1/p'\
33 $< | tr '\n' ' ' | sed -e 's/ $$/"\n/' >> $@
34
35# Build a lower case string table of sock type names
36# Transform lines from
37# SOCK_STREAM = 1,
38# to
39# [1] = "stream",
40quiet_cmd_make-sock = GEN $@
41cmd_make-sock = echo "static const char *sock_type_names[] = {" >> $@ ;\
42 sed $^ >>$@ -r -n \
43 -e 's/^\tSOCK_([A-Z0-9_]+)[\t]+=[ \t]+([0-9]+)(.*)/[\2] = "\L\1",/p';\
44 echo "};" >> $@
45 13
46# Build a lower case string table of capability names 14# Build a lower case string table of capability names
47# Transforms lines from 15# Transforms lines from
@@ -94,7 +62,6 @@ cmd_make-rlim = echo "static const char *const rlim_names[RLIM_NLIMITS] = {" \
94 tr '\n' ' ' | sed -e 's/ $$/"\n/' >> $@ 62 tr '\n' ' ' | sed -e 's/ $$/"\n/' >> $@
95 63
96$(obj)/capability.o : $(obj)/capability_names.h 64$(obj)/capability.o : $(obj)/capability_names.h
97$(obj)/net.o : $(obj)/net_names.h
98$(obj)/resource.o : $(obj)/rlim_names.h 65$(obj)/resource.o : $(obj)/rlim_names.h
99$(obj)/capability_names.h : $(srctree)/include/uapi/linux/capability.h \ 66$(obj)/capability_names.h : $(srctree)/include/uapi/linux/capability.h \
100 $(src)/Makefile 67 $(src)/Makefile
@@ -102,8 +69,3 @@ $(obj)/capability_names.h : $(srctree)/include/uapi/linux/capability.h \
102$(obj)/rlim_names.h : $(srctree)/include/uapi/asm-generic/resource.h \ 69$(obj)/rlim_names.h : $(srctree)/include/uapi/asm-generic/resource.h \
103 $(src)/Makefile 70 $(src)/Makefile
104 $(call cmd,make-rlim) 71 $(call cmd,make-rlim)
105$(obj)/net_names.h : $(srctree)/include/linux/socket.h \
106 $(srctree)/include/linux/net.h \
107 $(src)/Makefile
108 $(call cmd,make-af)
109 $(call cmd,make-sock)
diff --git a/security/apparmor/apparmorfs.c b/security/apparmor/apparmorfs.c
index 518d5928661b..d4fa04d91439 100644
--- a/security/apparmor/apparmorfs.c
+++ b/security/apparmor/apparmorfs.c
@@ -533,7 +533,7 @@ static ssize_t ns_revision_read(struct file *file, char __user *buf,
533 long last_read; 533 long last_read;
534 int avail; 534 int avail;
535 535
536 mutex_lock(&rev->ns->lock); 536 mutex_lock_nested(&rev->ns->lock, rev->ns->level);
537 last_read = rev->last_read; 537 last_read = rev->last_read;
538 if (last_read == rev->ns->revision) { 538 if (last_read == rev->ns->revision) {
539 mutex_unlock(&rev->ns->lock); 539 mutex_unlock(&rev->ns->lock);
@@ -543,7 +543,7 @@ static ssize_t ns_revision_read(struct file *file, char __user *buf,
543 last_read != 543 last_read !=
544 READ_ONCE(rev->ns->revision))) 544 READ_ONCE(rev->ns->revision)))
545 return -ERESTARTSYS; 545 return -ERESTARTSYS;
546 mutex_lock(&rev->ns->lock); 546 mutex_lock_nested(&rev->ns->lock, rev->ns->level);
547 } 547 }
548 548
549 avail = sprintf(buffer, "%ld\n", rev->ns->revision); 549 avail = sprintf(buffer, "%ld\n", rev->ns->revision);
@@ -577,7 +577,7 @@ static unsigned int ns_revision_poll(struct file *file, poll_table *pt)
577 unsigned int mask = 0; 577 unsigned int mask = 0;
578 578
579 if (rev) { 579 if (rev) {
580 mutex_lock(&rev->ns->lock); 580 mutex_lock_nested(&rev->ns->lock, rev->ns->level);
581 poll_wait(file, &rev->ns->wait, pt); 581 poll_wait(file, &rev->ns->wait, pt);
582 if (rev->last_read < rev->ns->revision) 582 if (rev->last_read < rev->ns->revision)
583 mask |= POLLIN | POLLRDNORM; 583 mask |= POLLIN | POLLRDNORM;
@@ -1643,7 +1643,7 @@ static int ns_mkdir_op(struct inode *dir, struct dentry *dentry, umode_t mode)
1643 */ 1643 */
1644 inode_unlock(dir); 1644 inode_unlock(dir);
1645 error = simple_pin_fs(&aafs_ops, &aafs_mnt, &aafs_count); 1645 error = simple_pin_fs(&aafs_ops, &aafs_mnt, &aafs_count);
1646 mutex_lock(&parent->lock); 1646 mutex_lock_nested(&parent->lock, parent->level);
1647 inode_lock_nested(dir, I_MUTEX_PARENT); 1647 inode_lock_nested(dir, I_MUTEX_PARENT);
1648 if (error) 1648 if (error)
1649 goto out; 1649 goto out;
@@ -1692,7 +1692,7 @@ static int ns_rmdir_op(struct inode *dir, struct dentry *dentry)
1692 inode_unlock(dir); 1692 inode_unlock(dir);
1693 inode_unlock(dentry->d_inode); 1693 inode_unlock(dentry->d_inode);
1694 1694
1695 mutex_lock(&parent->lock); 1695 mutex_lock_nested(&parent->lock, parent->level);
1696 ns = aa_get_ns(__aa_findn_ns(&parent->sub_ns, dentry->d_name.name, 1696 ns = aa_get_ns(__aa_findn_ns(&parent->sub_ns, dentry->d_name.name,
1697 dentry->d_name.len)); 1697 dentry->d_name.len));
1698 if (!ns) { 1698 if (!ns) {
@@ -1747,7 +1747,7 @@ void __aafs_ns_rmdir(struct aa_ns *ns)
1747 __aafs_profile_rmdir(child); 1747 __aafs_profile_rmdir(child);
1748 1748
1749 list_for_each_entry(sub, &ns->sub_ns, base.list) { 1749 list_for_each_entry(sub, &ns->sub_ns, base.list) {
1750 mutex_lock(&sub->lock); 1750 mutex_lock_nested(&sub->lock, sub->level);
1751 __aafs_ns_rmdir(sub); 1751 __aafs_ns_rmdir(sub);
1752 mutex_unlock(&sub->lock); 1752 mutex_unlock(&sub->lock);
1753 } 1753 }
@@ -1877,7 +1877,7 @@ int __aafs_ns_mkdir(struct aa_ns *ns, struct dentry *parent, const char *name,
1877 1877
1878 /* subnamespaces */ 1878 /* subnamespaces */
1879 list_for_each_entry(sub, &ns->sub_ns, base.list) { 1879 list_for_each_entry(sub, &ns->sub_ns, base.list) {
1880 mutex_lock(&sub->lock); 1880 mutex_lock_nested(&sub->lock, sub->level);
1881 error = __aafs_ns_mkdir(sub, ns_subns_dir(ns), NULL, NULL); 1881 error = __aafs_ns_mkdir(sub, ns_subns_dir(ns), NULL, NULL);
1882 mutex_unlock(&sub->lock); 1882 mutex_unlock(&sub->lock);
1883 if (error) 1883 if (error)
@@ -1921,7 +1921,7 @@ static struct aa_ns *__next_ns(struct aa_ns *root, struct aa_ns *ns)
1921 /* is next namespace a child */ 1921 /* is next namespace a child */
1922 if (!list_empty(&ns->sub_ns)) { 1922 if (!list_empty(&ns->sub_ns)) {
1923 next = list_first_entry(&ns->sub_ns, typeof(*ns), base.list); 1923 next = list_first_entry(&ns->sub_ns, typeof(*ns), base.list);
1924 mutex_lock(&next->lock); 1924 mutex_lock_nested(&next->lock, next->level);
1925 return next; 1925 return next;
1926 } 1926 }
1927 1927
@@ -1931,7 +1931,7 @@ static struct aa_ns *__next_ns(struct aa_ns *root, struct aa_ns *ns)
1931 mutex_unlock(&ns->lock); 1931 mutex_unlock(&ns->lock);
1932 next = list_next_entry(ns, base.list); 1932 next = list_next_entry(ns, base.list);
1933 if (!list_entry_is_head(next, &parent->sub_ns, base.list)) { 1933 if (!list_entry_is_head(next, &parent->sub_ns, base.list)) {
1934 mutex_lock(&next->lock); 1934 mutex_lock_nested(&next->lock, next->level);
1935 return next; 1935 return next;
1936 } 1936 }
1937 ns = parent; 1937 ns = parent;
@@ -2039,7 +2039,7 @@ static void *p_start(struct seq_file *f, loff_t *pos)
2039 f->private = root; 2039 f->private = root;
2040 2040
2041 /* find the first profile */ 2041 /* find the first profile */
2042 mutex_lock(&root->lock); 2042 mutex_lock_nested(&root->lock, root->level);
2043 profile = __first_profile(root, root); 2043 profile = __first_profile(root, root);
2044 2044
2045 /* skip to position */ 2045 /* skip to position */
@@ -2202,7 +2202,6 @@ static struct aa_sfs_entry aa_sfs_entry_features[] = {
2202 AA_SFS_DIR("policy", aa_sfs_entry_policy), 2202 AA_SFS_DIR("policy", aa_sfs_entry_policy),
2203 AA_SFS_DIR("domain", aa_sfs_entry_domain), 2203 AA_SFS_DIR("domain", aa_sfs_entry_domain),
2204 AA_SFS_DIR("file", aa_sfs_entry_file), 2204 AA_SFS_DIR("file", aa_sfs_entry_file),
2205 AA_SFS_DIR("network", aa_sfs_entry_network),
2206 AA_SFS_DIR("mount", aa_sfs_entry_mount), 2205 AA_SFS_DIR("mount", aa_sfs_entry_mount),
2207 AA_SFS_DIR("namespaces", aa_sfs_entry_ns), 2206 AA_SFS_DIR("namespaces", aa_sfs_entry_ns),
2208 AA_SFS_FILE_U64("capability", VFS_CAP_FLAGS_MASK), 2207 AA_SFS_FILE_U64("capability", VFS_CAP_FLAGS_MASK),
@@ -2452,7 +2451,7 @@ static int __init aa_create_aafs(void)
2452 aafs_mnt = kern_mount(&aafs_ops); 2451 aafs_mnt = kern_mount(&aafs_ops);
2453 if (IS_ERR(aafs_mnt)) 2452 if (IS_ERR(aafs_mnt))
2454 panic("can't set apparmorfs up\n"); 2453 panic("can't set apparmorfs up\n");
2455 aafs_mnt->mnt_sb->s_flags &= ~MS_NOUSER; 2454 aafs_mnt->mnt_sb->s_flags &= ~SB_NOUSER;
2456 2455
2457 /* Populate fs tree. */ 2456 /* Populate fs tree. */
2458 error = entry_create_dir(&aa_sfs_entry, NULL); 2457 error = entry_create_dir(&aa_sfs_entry, NULL);
@@ -2492,7 +2491,7 @@ static int __init aa_create_aafs(void)
2492 ns_subrevision(root_ns) = dent; 2491 ns_subrevision(root_ns) = dent;
2493 2492
2494 /* policy tree referenced by magic policy symlink */ 2493 /* policy tree referenced by magic policy symlink */
2495 mutex_lock(&root_ns->lock); 2494 mutex_lock_nested(&root_ns->lock, root_ns->level);
2496 error = __aafs_ns_mkdir(root_ns, aafs_mnt->mnt_root, ".policy", 2495 error = __aafs_ns_mkdir(root_ns, aafs_mnt->mnt_root, ".policy",
2497 aafs_mnt->mnt_root); 2496 aafs_mnt->mnt_root);
2498 mutex_unlock(&root_ns->lock); 2497 mutex_unlock(&root_ns->lock);
diff --git a/security/apparmor/domain.c b/security/apparmor/domain.c
index dd754b7850a8..04ba9d0718ea 100644
--- a/security/apparmor/domain.c
+++ b/security/apparmor/domain.c
@@ -305,6 +305,7 @@ static int change_profile_perms(struct aa_profile *profile,
305 * __attach_match_ - find an attachment match 305 * __attach_match_ - find an attachment match
306 * @name - to match against (NOT NULL) 306 * @name - to match against (NOT NULL)
307 * @head - profile list to walk (NOT NULL) 307 * @head - profile list to walk (NOT NULL)
308 * @info - info message if there was an error (NOT NULL)
308 * 309 *
309 * Do a linear search on the profiles in the list. There is a matching 310 * Do a linear search on the profiles in the list. There is a matching
310 * preference where an exact match is preferred over a name which uses 311 * preference where an exact match is preferred over a name which uses
@@ -316,28 +317,46 @@ static int change_profile_perms(struct aa_profile *profile,
316 * Returns: profile or NULL if no match found 317 * Returns: profile or NULL if no match found
317 */ 318 */
318static struct aa_profile *__attach_match(const char *name, 319static struct aa_profile *__attach_match(const char *name,
319 struct list_head *head) 320 struct list_head *head,
321 const char **info)
320{ 322{
321 int len = 0; 323 int len = 0;
324 bool conflict = false;
322 struct aa_profile *profile, *candidate = NULL; 325 struct aa_profile *profile, *candidate = NULL;
323 326
324 list_for_each_entry_rcu(profile, head, base.list) { 327 list_for_each_entry_rcu(profile, head, base.list) {
325 if (profile->label.flags & FLAG_NULL) 328 if (profile->label.flags & FLAG_NULL &&
329 &profile->label == ns_unconfined(profile->ns))
326 continue; 330 continue;
327 if (profile->xmatch && profile->xmatch_len > len) { 331
328 unsigned int state = aa_dfa_match(profile->xmatch, 332 if (profile->xmatch) {
329 DFA_START, name); 333 if (profile->xmatch_len == len) {
330 u32 perm = dfa_user_allow(profile->xmatch, state); 334 conflict = true;
331 /* any accepting state means a valid match. */ 335 continue;
332 if (perm & MAY_EXEC) { 336 } else if (profile->xmatch_len > len) {
333 candidate = profile; 337 unsigned int state;
334 len = profile->xmatch_len; 338 u32 perm;
339
340 state = aa_dfa_match(profile->xmatch,
341 DFA_START, name);
342 perm = dfa_user_allow(profile->xmatch, state);
343 /* any accepting state means a valid match. */
344 if (perm & MAY_EXEC) {
345 candidate = profile;
346 len = profile->xmatch_len;
347 conflict = false;
348 }
335 } 349 }
336 } else if (!strcmp(profile->base.name, name)) 350 } else if (!strcmp(profile->base.name, name))
337 /* exact non-re match, no more searching required */ 351 /* exact non-re match, no more searching required */
338 return profile; 352 return profile;
339 } 353 }
340 354
355 if (conflict) {
356 *info = "conflicting profile attachments";
357 return NULL;
358 }
359
341 return candidate; 360 return candidate;
342} 361}
343 362
@@ -346,16 +365,17 @@ static struct aa_profile *__attach_match(const char *name,
346 * @ns: the current namespace (NOT NULL) 365 * @ns: the current namespace (NOT NULL)
347 * @list: list to search (NOT NULL) 366 * @list: list to search (NOT NULL)
348 * @name: the executable name to match against (NOT NULL) 367 * @name: the executable name to match against (NOT NULL)
368 * @info: info message if there was an error
349 * 369 *
350 * Returns: label or NULL if no match found 370 * Returns: label or NULL if no match found
351 */ 371 */
352static struct aa_label *find_attach(struct aa_ns *ns, struct list_head *list, 372static struct aa_label *find_attach(struct aa_ns *ns, struct list_head *list,
353 const char *name) 373 const char *name, const char **info)
354{ 374{
355 struct aa_profile *profile; 375 struct aa_profile *profile;
356 376
357 rcu_read_lock(); 377 rcu_read_lock();
358 profile = aa_get_profile(__attach_match(name, list)); 378 profile = aa_get_profile(__attach_match(name, list, info));
359 rcu_read_unlock(); 379 rcu_read_unlock();
360 380
361 return profile ? &profile->label : NULL; 381 return profile ? &profile->label : NULL;
@@ -448,11 +468,11 @@ static struct aa_label *x_to_label(struct aa_profile *profile,
448 if (xindex & AA_X_CHILD) 468 if (xindex & AA_X_CHILD)
449 /* released by caller */ 469 /* released by caller */
450 new = find_attach(ns, &profile->base.profiles, 470 new = find_attach(ns, &profile->base.profiles,
451 name); 471 name, info);
452 else 472 else
453 /* released by caller */ 473 /* released by caller */
454 new = find_attach(ns, &ns->base.profiles, 474 new = find_attach(ns, &ns->base.profiles,
455 name); 475 name, info);
456 *lookupname = name; 476 *lookupname = name;
457 break; 477 break;
458 } 478 }
@@ -516,7 +536,7 @@ static struct aa_label *profile_transition(struct aa_profile *profile,
516 536
517 if (profile_unconfined(profile)) { 537 if (profile_unconfined(profile)) {
518 new = find_attach(profile->ns, &profile->ns->base.profiles, 538 new = find_attach(profile->ns, &profile->ns->base.profiles,
519 name); 539 name, &info);
520 if (new) { 540 if (new) {
521 AA_DEBUG("unconfined attached to new label"); 541 AA_DEBUG("unconfined attached to new label");
522 return new; 542 return new;
@@ -541,9 +561,21 @@ static struct aa_label *profile_transition(struct aa_profile *profile,
541 } 561 }
542 } else if (COMPLAIN_MODE(profile)) { 562 } else if (COMPLAIN_MODE(profile)) {
543 /* no exec permission - learning mode */ 563 /* no exec permission - learning mode */
544 struct aa_profile *new_profile = aa_new_null_profile(profile, 564 struct aa_profile *new_profile = NULL;
545 false, name, 565 char *n = kstrdup(name, GFP_ATOMIC);
546 GFP_ATOMIC); 566
567 if (n) {
568 /* name is ptr into buffer */
569 long pos = name - buffer;
570 /* break per cpu buffer hold */
571 put_buffers(buffer);
572 new_profile = aa_new_null_profile(profile, false, n,
573 GFP_KERNEL);
574 get_buffers(buffer);
575 name = buffer + pos;
576 strcpy((char *)name, n);
577 kfree(n);
578 }
547 if (!new_profile) { 579 if (!new_profile) {
548 error = -ENOMEM; 580 error = -ENOMEM;
549 info = "could not create null profile"; 581 info = "could not create null profile";
diff --git a/security/apparmor/file.c b/security/apparmor/file.c
index db80221891c6..e79bf44396a3 100644
--- a/security/apparmor/file.c
+++ b/security/apparmor/file.c
@@ -21,7 +21,6 @@
21#include "include/context.h" 21#include "include/context.h"
22#include "include/file.h" 22#include "include/file.h"
23#include "include/match.h" 23#include "include/match.h"
24#include "include/net.h"
25#include "include/path.h" 24#include "include/path.h"
26#include "include/policy.h" 25#include "include/policy.h"
27#include "include/label.h" 26#include "include/label.h"
@@ -227,18 +226,12 @@ static u32 map_old_perms(u32 old)
227struct aa_perms aa_compute_fperms(struct aa_dfa *dfa, unsigned int state, 226struct aa_perms aa_compute_fperms(struct aa_dfa *dfa, unsigned int state,
228 struct path_cond *cond) 227 struct path_cond *cond)
229{ 228{
230 struct aa_perms perms;
231
232 /* FIXME: change over to new dfa format 229 /* FIXME: change over to new dfa format
233 * currently file perms are encoded in the dfa, new format 230 * currently file perms are encoded in the dfa, new format
234 * splits the permissions from the dfa. This mapping can be 231 * splits the permissions from the dfa. This mapping can be
235 * done at profile load 232 * done at profile load
236 */ 233 */
237 perms.deny = 0; 234 struct aa_perms perms = { };
238 perms.kill = perms.stop = 0;
239 perms.complain = perms.cond = 0;
240 perms.hide = 0;
241 perms.prompt = 0;
242 235
243 if (uid_eq(current_fsuid(), cond->uid)) { 236 if (uid_eq(current_fsuid(), cond->uid)) {
244 perms.allow = map_old_perms(dfa_user_allow(dfa, state)); 237 perms.allow = map_old_perms(dfa_user_allow(dfa, state));
@@ -567,32 +560,6 @@ static int __file_path_perm(const char *op, struct aa_label *label,
567 return error; 560 return error;
568} 561}
569 562
570static int __file_sock_perm(const char *op, struct aa_label *label,
571 struct aa_label *flabel, struct file *file,
572 u32 request, u32 denied)
573{
574 struct socket *sock = (struct socket *) file->private_data;
575 int error;
576
577 AA_BUG(!sock);
578
579 /* revalidation due to label out of date. No revocation at this time */
580 if (!denied && aa_label_is_subset(flabel, label))
581 return 0;
582
583 /* TODO: improve to skip profiles cached in flabel */
584 error = aa_sock_file_perm(label, op, request, sock);
585 if (denied) {
586 /* TODO: improve to skip profiles checked above */
587 /* check every profile in file label to is cached */
588 last_error(error, aa_sock_file_perm(flabel, op, request, sock));
589 }
590 if (!error)
591 update_file_ctx(file_ctx(file), label, request);
592
593 return error;
594}
595
596/** 563/**
597 * aa_file_perm - do permission revalidation check & audit for @file 564 * aa_file_perm - do permission revalidation check & audit for @file
598 * @op: operation being checked 565 * @op: operation being checked
@@ -637,9 +604,6 @@ int aa_file_perm(const char *op, struct aa_label *label, struct file *file,
637 error = __file_path_perm(op, label, flabel, file, request, 604 error = __file_path_perm(op, label, flabel, file, request,
638 denied); 605 denied);
639 606
640 else if (S_ISSOCK(file_inode(file)->i_mode))
641 error = __file_sock_perm(op, label, flabel, file, request,
642 denied);
643done: 607done:
644 rcu_read_unlock(); 608 rcu_read_unlock();
645 609
diff --git a/security/apparmor/include/audit.h b/security/apparmor/include/audit.h
index ff4316e1068d..4ac095118717 100644
--- a/security/apparmor/include/audit.h
+++ b/security/apparmor/include/audit.h
@@ -123,20 +123,10 @@ struct apparmor_audit_data {
123 struct aa_label *peer; 123 struct aa_label *peer;
124 union { 124 union {
125 struct { 125 struct {
126 kuid_t ouid;
127 const char *target; 126 const char *target;
127 kuid_t ouid;
128 } fs; 128 } fs;
129 struct {
130 int type, protocol;
131 struct sock *peer_sk;
132 void *addr;
133 int addrlen;
134 } net;
135 int signal; 129 int signal;
136 struct {
137 int rlim;
138 unsigned long max;
139 } rlim;
140 }; 130 };
141 }; 131 };
142 struct { 132 struct {
@@ -145,6 +135,10 @@ struct apparmor_audit_data {
145 long pos; 135 long pos;
146 } iface; 136 } iface;
147 struct { 137 struct {
138 int rlim;
139 unsigned long max;
140 } rlim;
141 struct {
148 const char *src_name; 142 const char *src_name;
149 const char *type; 143 const char *type;
150 const char *trans; 144 const char *trans;
diff --git a/security/apparmor/include/lib.h b/security/apparmor/include/lib.h
index 436b3a722357..6505e1ad9e23 100644
--- a/security/apparmor/include/lib.h
+++ b/security/apparmor/include/lib.h
@@ -19,17 +19,6 @@
19 19
20#include "match.h" 20#include "match.h"
21 21
22/* Provide our own test for whether a write lock is held for asserts
23 * this is because on none SMP systems write_can_lock will always
24 * resolve to true, which is what you want for code making decisions
25 * based on it, but wrong for asserts checking that the lock is held
26 */
27#ifdef CONFIG_SMP
28#define write_is_locked(X) !write_can_lock(X)
29#else
30#define write_is_locked(X) (1)
31#endif /* CONFIG_SMP */
32
33/* 22/*
34 * DEBUG remains global (no per profile flag) since it is mostly used in sysctl 23 * DEBUG remains global (no per profile flag) since it is mostly used in sysctl
35 * which is not related to profile accesses. 24 * which is not related to profile accesses.
@@ -97,7 +86,7 @@ static inline unsigned int aa_dfa_null_transition(struct aa_dfa *dfa,
97 86
98static inline bool path_mediated_fs(struct dentry *dentry) 87static inline bool path_mediated_fs(struct dentry *dentry)
99{ 88{
100 return !(dentry->d_sb->s_flags & MS_NOUSER); 89 return !(dentry->d_sb->s_flags & SB_NOUSER);
101} 90}
102 91
103 92
diff --git a/security/apparmor/include/net.h b/security/apparmor/include/net.h
deleted file mode 100644
index 140c8efcf364..000000000000
--- a/security/apparmor/include/net.h
+++ /dev/null
@@ -1,114 +0,0 @@
1/*
2 * AppArmor security module
3 *
4 * This file contains AppArmor network mediation definitions.
5 *
6 * Copyright (C) 1998-2008 Novell/SUSE
7 * Copyright 2009-2017 Canonical Ltd.
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as
11 * published by the Free Software Foundation, version 2 of the
12 * License.
13 */
14
15#ifndef __AA_NET_H
16#define __AA_NET_H
17
18#include <net/sock.h>
19#include <linux/path.h>
20
21#include "apparmorfs.h"
22#include "label.h"
23#include "perms.h"
24#include "policy.h"
25
26#define AA_MAY_SEND AA_MAY_WRITE
27#define AA_MAY_RECEIVE AA_MAY_READ
28
29#define AA_MAY_SHUTDOWN AA_MAY_DELETE
30
31#define AA_MAY_CONNECT AA_MAY_OPEN
32#define AA_MAY_ACCEPT 0x00100000
33
34#define AA_MAY_BIND 0x00200000
35#define AA_MAY_LISTEN 0x00400000
36
37#define AA_MAY_SETOPT 0x01000000
38#define AA_MAY_GETOPT 0x02000000
39
40#define NET_PERMS_MASK (AA_MAY_SEND | AA_MAY_RECEIVE | AA_MAY_CREATE | \
41 AA_MAY_SHUTDOWN | AA_MAY_BIND | AA_MAY_LISTEN | \
42 AA_MAY_CONNECT | AA_MAY_ACCEPT | AA_MAY_SETATTR | \
43 AA_MAY_GETATTR | AA_MAY_SETOPT | AA_MAY_GETOPT)
44
45#define NET_FS_PERMS (AA_MAY_SEND | AA_MAY_RECEIVE | AA_MAY_CREATE | \
46 AA_MAY_SHUTDOWN | AA_MAY_CONNECT | AA_MAY_RENAME |\
47 AA_MAY_SETATTR | AA_MAY_GETATTR | AA_MAY_CHMOD | \
48 AA_MAY_CHOWN | AA_MAY_CHGRP | AA_MAY_LOCK | \
49 AA_MAY_MPROT)
50
51#define NET_PEER_MASK (AA_MAY_SEND | AA_MAY_RECEIVE | AA_MAY_CONNECT | \
52 AA_MAY_ACCEPT)
53struct aa_sk_ctx {
54 struct aa_label *label;
55 struct aa_label *peer;
56 struct path path;
57};
58
59#define SK_CTX(X) ((X)->sk_security)
60#define SOCK_ctx(X) SOCK_INODE(X)->i_security
61#define DEFINE_AUDIT_NET(NAME, OP, SK, F, T, P) \
62 struct lsm_network_audit NAME ## _net = { .sk = (SK), \
63 .family = (F)}; \
64 DEFINE_AUDIT_DATA(NAME, \
65 ((SK) && (F) != AF_UNIX) ? LSM_AUDIT_DATA_NET : \
66 LSM_AUDIT_DATA_NONE, \
67 OP); \
68 NAME.u.net = &(NAME ## _net); \
69 aad(&NAME)->net.type = (T); \
70 aad(&NAME)->net.protocol = (P)
71
72#define DEFINE_AUDIT_SK(NAME, OP, SK) \
73 DEFINE_AUDIT_NET(NAME, OP, SK, (SK)->sk_family, (SK)->sk_type, \
74 (SK)->sk_protocol)
75
76/* struct aa_net - network confinement data
77 * @allow: basic network families permissions
78 * @audit: which network permissions to force audit
79 * @quiet: which network permissions to quiet rejects
80 */
81struct aa_net {
82 u16 allow[AF_MAX];
83 u16 audit[AF_MAX];
84 u16 quiet[AF_MAX];
85};
86
87
88extern struct aa_sfs_entry aa_sfs_entry_network[];
89
90void audit_net_cb(struct audit_buffer *ab, void *va);
91int aa_profile_af_perm(struct aa_profile *profile, struct common_audit_data *sa,
92 u32 request, u16 family, int type);
93int aa_af_perm(struct aa_label *label, const char *op, u32 request, u16 family,
94 int type, int protocol);
95static inline int aa_profile_af_sk_perm(struct aa_profile *profile,
96 struct common_audit_data *sa,
97 u32 request,
98 struct sock *sk)
99{
100 return aa_profile_af_perm(profile, sa, request, sk->sk_family,
101 sk->sk_type);
102}
103int aa_sk_perm(const char *op, u32 request, struct sock *sk);
104
105int aa_sock_file_perm(struct aa_label *label, const char *op, u32 request,
106 struct socket *sock);
107
108
109static inline void aa_free_net_rules(struct aa_net *new)
110{
111 /* NOP */
112}
113
114#endif /* __AA_NET_H */
diff --git a/security/apparmor/include/perms.h b/security/apparmor/include/perms.h
index af04d5a7d73d..2b27bb79aec4 100644
--- a/security/apparmor/include/perms.h
+++ b/security/apparmor/include/perms.h
@@ -135,10 +135,9 @@ extern struct aa_perms allperms;
135 135
136 136
137void aa_perm_mask_to_str(char *str, const char *chrs, u32 mask); 137void aa_perm_mask_to_str(char *str, const char *chrs, u32 mask);
138void aa_audit_perm_names(struct audit_buffer *ab, const char * const *names, 138void aa_audit_perm_names(struct audit_buffer *ab, const char **names, u32 mask);
139 u32 mask);
140void aa_audit_perm_mask(struct audit_buffer *ab, u32 mask, const char *chrs, 139void aa_audit_perm_mask(struct audit_buffer *ab, u32 mask, const char *chrs,
141 u32 chrsmask, const char * const *names, u32 namesmask); 140 u32 chrsmask, const char **names, u32 namesmask);
142void aa_apply_modes_to_perms(struct aa_profile *profile, 141void aa_apply_modes_to_perms(struct aa_profile *profile,
143 struct aa_perms *perms); 142 struct aa_perms *perms);
144void aa_compute_perms(struct aa_dfa *dfa, unsigned int state, 143void aa_compute_perms(struct aa_dfa *dfa, unsigned int state,
diff --git a/security/apparmor/include/policy.h b/security/apparmor/include/policy.h
index 4364088a0b9e..17fe41a9cac3 100644
--- a/security/apparmor/include/policy.h
+++ b/security/apparmor/include/policy.h
@@ -30,7 +30,6 @@
30#include "file.h" 30#include "file.h"
31#include "lib.h" 31#include "lib.h"
32#include "label.h" 32#include "label.h"
33#include "net.h"
34#include "perms.h" 33#include "perms.h"
35#include "resource.h" 34#include "resource.h"
36 35
@@ -112,7 +111,6 @@ struct aa_data {
112 * @policy: general match rules governing policy 111 * @policy: general match rules governing policy
113 * @file: The set of rules governing basic file access and domain transitions 112 * @file: The set of rules governing basic file access and domain transitions
114 * @caps: capabilities for the profile 113 * @caps: capabilities for the profile
115 * @net: network controls for the profile
116 * @rlimits: rlimits for the profile 114 * @rlimits: rlimits for the profile
117 * 115 *
118 * @dents: dentries for the profiles file entries in apparmorfs 116 * @dents: dentries for the profiles file entries in apparmorfs
@@ -150,7 +148,6 @@ struct aa_profile {
150 struct aa_policydb policy; 148 struct aa_policydb policy;
151 struct aa_file_rules file; 149 struct aa_file_rules file;
152 struct aa_caps caps; 150 struct aa_caps caps;
153 struct aa_net net;
154 struct aa_rlimit rlimits; 151 struct aa_rlimit rlimits;
155 152
156 struct aa_loaddata *rawdata; 153 struct aa_loaddata *rawdata;
@@ -223,16 +220,6 @@ static inline unsigned int PROFILE_MEDIATES_SAFE(struct aa_profile *profile,
223 return 0; 220 return 0;
224} 221}
225 222
226static inline unsigned int PROFILE_MEDIATES_AF(struct aa_profile *profile,
227 u16 AF) {
228 unsigned int state = PROFILE_MEDIATES(profile, AA_CLASS_NET);
229 u16 be_af = cpu_to_be16(AF);
230
231 if (!state)
232 return 0;
233 return aa_dfa_match_len(profile->policy.dfa, state, (char *) &be_af, 2);
234}
235
236/** 223/**
237 * aa_get_profile - increment refcount on profile @p 224 * aa_get_profile - increment refcount on profile @p
238 * @p: profile (MAYBE NULL) 225 * @p: profile (MAYBE NULL)
diff --git a/security/apparmor/ipc.c b/security/apparmor/ipc.c
index 66fb9ede9447..7ca0032e7ba9 100644
--- a/security/apparmor/ipc.c
+++ b/security/apparmor/ipc.c
@@ -128,7 +128,7 @@ static inline int map_signal_num(int sig)
128 return SIGUNKNOWN; 128 return SIGUNKNOWN;
129 else if (sig >= SIGRTMIN) 129 else if (sig >= SIGRTMIN)
130 return sig - SIGRTMIN + 128; /* rt sigs mapped to 128 */ 130 return sig - SIGRTMIN + 128; /* rt sigs mapped to 128 */
131 else if (sig <= MAXMAPPED_SIG) 131 else if (sig < MAXMAPPED_SIG)
132 return sig_map[sig]; 132 return sig_map[sig];
133 return SIGUNKNOWN; 133 return SIGUNKNOWN;
134} 134}
@@ -163,7 +163,7 @@ static void audit_signal_cb(struct audit_buffer *ab, void *va)
163 audit_signal_mask(ab, aad(sa)->denied); 163 audit_signal_mask(ab, aad(sa)->denied);
164 } 164 }
165 } 165 }
166 if (aad(sa)->signal <= MAXMAPPED_SIG) 166 if (aad(sa)->signal < MAXMAPPED_SIG)
167 audit_log_format(ab, " signal=%s", sig_names[aad(sa)->signal]); 167 audit_log_format(ab, " signal=%s", sig_names[aad(sa)->signal]);
168 else 168 else
169 audit_log_format(ab, " signal=rtmin+%d", 169 audit_log_format(ab, " signal=rtmin+%d",
diff --git a/security/apparmor/label.c b/security/apparmor/label.c
index c5b99b954580..324fe5c60f87 100644
--- a/security/apparmor/label.c
+++ b/security/apparmor/label.c
@@ -80,7 +80,7 @@ void __aa_proxy_redirect(struct aa_label *orig, struct aa_label *new)
80 80
81 AA_BUG(!orig); 81 AA_BUG(!orig);
82 AA_BUG(!new); 82 AA_BUG(!new);
83 AA_BUG(!write_is_locked(&labels_set(orig)->lock)); 83 lockdep_assert_held_exclusive(&labels_set(orig)->lock);
84 84
85 tmp = rcu_dereference_protected(orig->proxy->label, 85 tmp = rcu_dereference_protected(orig->proxy->label,
86 &labels_ns(orig)->lock); 86 &labels_ns(orig)->lock);
@@ -571,7 +571,7 @@ static bool __label_remove(struct aa_label *label, struct aa_label *new)
571 571
572 AA_BUG(!ls); 572 AA_BUG(!ls);
573 AA_BUG(!label); 573 AA_BUG(!label);
574 AA_BUG(!write_is_locked(&ls->lock)); 574 lockdep_assert_held_exclusive(&ls->lock);
575 575
576 if (new) 576 if (new)
577 __aa_proxy_redirect(label, new); 577 __aa_proxy_redirect(label, new);
@@ -608,7 +608,7 @@ static bool __label_replace(struct aa_label *old, struct aa_label *new)
608 AA_BUG(!ls); 608 AA_BUG(!ls);
609 AA_BUG(!old); 609 AA_BUG(!old);
610 AA_BUG(!new); 610 AA_BUG(!new);
611 AA_BUG(!write_is_locked(&ls->lock)); 611 lockdep_assert_held_exclusive(&ls->lock);
612 AA_BUG(new->flags & FLAG_IN_TREE); 612 AA_BUG(new->flags & FLAG_IN_TREE);
613 613
614 if (!label_is_stale(old)) 614 if (!label_is_stale(old))
@@ -645,7 +645,7 @@ static struct aa_label *__label_insert(struct aa_labelset *ls,
645 AA_BUG(!ls); 645 AA_BUG(!ls);
646 AA_BUG(!label); 646 AA_BUG(!label);
647 AA_BUG(labels_set(label) != ls); 647 AA_BUG(labels_set(label) != ls);
648 AA_BUG(!write_is_locked(&ls->lock)); 648 lockdep_assert_held_exclusive(&ls->lock);
649 AA_BUG(label->flags & FLAG_IN_TREE); 649 AA_BUG(label->flags & FLAG_IN_TREE);
650 650
651 /* Figure out where to put new node */ 651 /* Figure out where to put new node */
@@ -2115,7 +2115,7 @@ void __aa_labelset_update_subtree(struct aa_ns *ns)
2115 __labelset_update(ns); 2115 __labelset_update(ns);
2116 2116
2117 list_for_each_entry(child, &ns->sub_ns, base.list) { 2117 list_for_each_entry(child, &ns->sub_ns, base.list) {
2118 mutex_lock(&child->lock); 2118 mutex_lock_nested(&child->lock, child->level);
2119 __aa_labelset_update_subtree(child); 2119 __aa_labelset_update_subtree(child);
2120 mutex_unlock(&child->lock); 2120 mutex_unlock(&child->lock);
2121 } 2121 }
diff --git a/security/apparmor/lib.c b/security/apparmor/lib.c
index 8818621b5d95..4d5e98e49d5e 100644
--- a/security/apparmor/lib.c
+++ b/security/apparmor/lib.c
@@ -211,8 +211,7 @@ void aa_perm_mask_to_str(char *str, const char *chrs, u32 mask)
211 *str = '\0'; 211 *str = '\0';
212} 212}
213 213
214void aa_audit_perm_names(struct audit_buffer *ab, const char * const *names, 214void aa_audit_perm_names(struct audit_buffer *ab, const char **names, u32 mask)
215 u32 mask)
216{ 215{
217 const char *fmt = "%s"; 216 const char *fmt = "%s";
218 unsigned int i, perm = 1; 217 unsigned int i, perm = 1;
@@ -230,7 +229,7 @@ void aa_audit_perm_names(struct audit_buffer *ab, const char * const *names,
230} 229}
231 230
232void aa_audit_perm_mask(struct audit_buffer *ab, u32 mask, const char *chrs, 231void aa_audit_perm_mask(struct audit_buffer *ab, u32 mask, const char *chrs,
233 u32 chrsmask, const char * const *names, u32 namesmask) 232 u32 chrsmask, const char **names, u32 namesmask)
234{ 233{
235 char str[33]; 234 char str[33];
236 235
@@ -318,14 +317,11 @@ static u32 map_other(u32 x)
318void aa_compute_perms(struct aa_dfa *dfa, unsigned int state, 317void aa_compute_perms(struct aa_dfa *dfa, unsigned int state,
319 struct aa_perms *perms) 318 struct aa_perms *perms)
320{ 319{
321 perms->deny = 0; 320 *perms = (struct aa_perms) {
322 perms->kill = perms->stop = 0; 321 .allow = dfa_user_allow(dfa, state),
323 perms->complain = perms->cond = 0; 322 .audit = dfa_user_audit(dfa, state),
324 perms->hide = 0; 323 .quiet = dfa_user_quiet(dfa, state),
325 perms->prompt = 0; 324 };
326 perms->allow = dfa_user_allow(dfa, state);
327 perms->audit = dfa_user_audit(dfa, state);
328 perms->quiet = dfa_user_quiet(dfa, state);
329 325
330 /* for v5 perm mapping in the policydb, the other set is used 326 /* for v5 perm mapping in the policydb, the other set is used
331 * to extend the general perm set 327 * to extend the general perm set
@@ -427,7 +423,6 @@ int aa_check_perms(struct aa_profile *profile, struct aa_perms *perms,
427 void (*cb)(struct audit_buffer *, void *)) 423 void (*cb)(struct audit_buffer *, void *))
428{ 424{
429 int type, error; 425 int type, error;
430 bool stop = false;
431 u32 denied = request & (~perms->allow | perms->deny); 426 u32 denied = request & (~perms->allow | perms->deny);
432 427
433 if (likely(!denied)) { 428 if (likely(!denied)) {
@@ -448,8 +443,6 @@ int aa_check_perms(struct aa_profile *profile, struct aa_perms *perms,
448 else 443 else
449 type = AUDIT_APPARMOR_DENIED; 444 type = AUDIT_APPARMOR_DENIED;
450 445
451 if (denied & perms->stop)
452 stop = true;
453 if (denied == (denied & perms->hide)) 446 if (denied == (denied & perms->hide))
454 error = -ENOENT; 447 error = -ENOENT;
455 448
diff --git a/security/apparmor/lsm.c b/security/apparmor/lsm.c
index 72b915dfcaf7..9a65eeaf7dfa 100644
--- a/security/apparmor/lsm.c
+++ b/security/apparmor/lsm.c
@@ -33,7 +33,6 @@
33#include "include/context.h" 33#include "include/context.h"
34#include "include/file.h" 34#include "include/file.h"
35#include "include/ipc.h" 35#include "include/ipc.h"
36#include "include/net.h"
37#include "include/path.h" 36#include "include/path.h"
38#include "include/label.h" 37#include "include/label.h"
39#include "include/policy.h" 38#include "include/policy.h"
@@ -737,368 +736,6 @@ static int apparmor_task_kill(struct task_struct *target, struct siginfo *info,
737 return error; 736 return error;
738} 737}
739 738
740/**
741 * apparmor_sk_alloc_security - allocate and attach the sk_security field
742 */
743static int apparmor_sk_alloc_security(struct sock *sk, int family, gfp_t flags)
744{
745 struct aa_sk_ctx *ctx;
746
747 ctx = kzalloc(sizeof(*ctx), flags);
748 if (!ctx)
749 return -ENOMEM;
750
751 SK_CTX(sk) = ctx;
752
753 return 0;
754}
755
756/**
757 * apparmor_sk_free_security - free the sk_security field
758 */
759static void apparmor_sk_free_security(struct sock *sk)
760{
761 struct aa_sk_ctx *ctx = SK_CTX(sk);
762
763 SK_CTX(sk) = NULL;
764 aa_put_label(ctx->label);
765 aa_put_label(ctx->peer);
766 path_put(&ctx->path);
767 kfree(ctx);
768}
769
770/**
771 * apparmor_clone_security - clone the sk_security field
772 */
773static void apparmor_sk_clone_security(const struct sock *sk,
774 struct sock *newsk)
775{
776 struct aa_sk_ctx *ctx = SK_CTX(sk);
777 struct aa_sk_ctx *new = SK_CTX(newsk);
778
779 new->label = aa_get_label(ctx->label);
780 new->peer = aa_get_label(ctx->peer);
781 new->path = ctx->path;
782 path_get(&new->path);
783}
784
785static int aa_sock_create_perm(struct aa_label *label, int family, int type,
786 int protocol)
787{
788 AA_BUG(!label);
789 AA_BUG(in_interrupt());
790
791 return aa_af_perm(label, OP_CREATE, AA_MAY_CREATE, family, type,
792 protocol);
793}
794
795
796/**
797 * apparmor_socket_create - check perms before creating a new socket
798 */
799static int apparmor_socket_create(int family, int type, int protocol, int kern)
800{
801 struct aa_label *label;
802 int error = 0;
803
804 label = begin_current_label_crit_section();
805 if (!(kern || unconfined(label)))
806 error = aa_sock_create_perm(label, family, type, protocol);
807 end_current_label_crit_section(label);
808
809 return error;
810}
811
812/**
813 * apparmor_socket_post_create - setup the per-socket security struct
814 *
815 * Note:
816 * - kernel sockets currently labeled unconfined but we may want to
817 * move to a special kernel label
818 * - socket may not have sk here if created with sock_create_lite or
819 * sock_alloc. These should be accept cases which will be handled in
820 * sock_graft.
821 */
822static int apparmor_socket_post_create(struct socket *sock, int family,
823 int type, int protocol, int kern)
824{
825 struct aa_label *label;
826
827 if (kern) {
828 struct aa_ns *ns = aa_get_current_ns();
829
830 label = aa_get_label(ns_unconfined(ns));
831 aa_put_ns(ns);
832 } else
833 label = aa_get_current_label();
834
835 if (sock->sk) {
836 struct aa_sk_ctx *ctx = SK_CTX(sock->sk);
837
838 aa_put_label(ctx->label);
839 ctx->label = aa_get_label(label);
840 }
841 aa_put_label(label);
842
843 return 0;
844}
845
846/**
847 * apparmor_socket_bind - check perms before bind addr to socket
848 */
849static int apparmor_socket_bind(struct socket *sock,
850 struct sockaddr *address, int addrlen)
851{
852 AA_BUG(!sock);
853 AA_BUG(!sock->sk);
854 AA_BUG(!address);
855 AA_BUG(in_interrupt());
856
857 return aa_sk_perm(OP_BIND, AA_MAY_BIND, sock->sk);
858}
859
860/**
861 * apparmor_socket_connect - check perms before connecting @sock to @address
862 */
863static int apparmor_socket_connect(struct socket *sock,
864 struct sockaddr *address, int addrlen)
865{
866 AA_BUG(!sock);
867 AA_BUG(!sock->sk);
868 AA_BUG(!address);
869 AA_BUG(in_interrupt());
870
871 return aa_sk_perm(OP_CONNECT, AA_MAY_CONNECT, sock->sk);
872}
873
874/**
875 * apparmor_socket_list - check perms before allowing listen
876 */
877static int apparmor_socket_listen(struct socket *sock, int backlog)
878{
879 AA_BUG(!sock);
880 AA_BUG(!sock->sk);
881 AA_BUG(in_interrupt());
882
883 return aa_sk_perm(OP_LISTEN, AA_MAY_LISTEN, sock->sk);
884}
885
886/**
887 * apparmor_socket_accept - check perms before accepting a new connection.
888 *
889 * Note: while @newsock is created and has some information, the accept
890 * has not been done.
891 */
892static int apparmor_socket_accept(struct socket *sock, struct socket *newsock)
893{
894 AA_BUG(!sock);
895 AA_BUG(!sock->sk);
896 AA_BUG(!newsock);
897 AA_BUG(in_interrupt());
898
899 return aa_sk_perm(OP_ACCEPT, AA_MAY_ACCEPT, sock->sk);
900}
901
902static int aa_sock_msg_perm(const char *op, u32 request, struct socket *sock,
903 struct msghdr *msg, int size)
904{
905 AA_BUG(!sock);
906 AA_BUG(!sock->sk);
907 AA_BUG(!msg);
908 AA_BUG(in_interrupt());
909
910 return aa_sk_perm(op, request, sock->sk);
911}
912
913/**
914 * apparmor_socket_sendmsg - check perms before sending msg to another socket
915 */
916static int apparmor_socket_sendmsg(struct socket *sock,
917 struct msghdr *msg, int size)
918{
919 return aa_sock_msg_perm(OP_SENDMSG, AA_MAY_SEND, sock, msg, size);
920}
921
922/**
923 * apparmor_socket_recvmsg - check perms before receiving a message
924 */
925static int apparmor_socket_recvmsg(struct socket *sock,
926 struct msghdr *msg, int size, int flags)
927{
928 return aa_sock_msg_perm(OP_RECVMSG, AA_MAY_RECEIVE, sock, msg, size);
929}
930
931/* revaliation, get/set attr, shutdown */
932static int aa_sock_perm(const char *op, u32 request, struct socket *sock)
933{
934 AA_BUG(!sock);
935 AA_BUG(!sock->sk);
936 AA_BUG(in_interrupt());
937
938 return aa_sk_perm(op, request, sock->sk);
939}
940
941/**
942 * apparmor_socket_getsockname - check perms before getting the local address
943 */
944static int apparmor_socket_getsockname(struct socket *sock)
945{
946 return aa_sock_perm(OP_GETSOCKNAME, AA_MAY_GETATTR, sock);
947}
948
949/**
950 * apparmor_socket_getpeername - check perms before getting remote address
951 */
952static int apparmor_socket_getpeername(struct socket *sock)
953{
954 return aa_sock_perm(OP_GETPEERNAME, AA_MAY_GETATTR, sock);
955}
956
957/* revaliation, get/set attr, opt */
958static int aa_sock_opt_perm(const char *op, u32 request, struct socket *sock,
959 int level, int optname)
960{
961 AA_BUG(!sock);
962 AA_BUG(!sock->sk);
963 AA_BUG(in_interrupt());
964
965 return aa_sk_perm(op, request, sock->sk);
966}
967
968/**
969 * apparmor_getsockopt - check perms before getting socket options
970 */
971static int apparmor_socket_getsockopt(struct socket *sock, int level,
972 int optname)
973{
974 return aa_sock_opt_perm(OP_GETSOCKOPT, AA_MAY_GETOPT, sock,
975 level, optname);
976}
977
978/**
979 * apparmor_setsockopt - check perms before setting socket options
980 */
981static int apparmor_socket_setsockopt(struct socket *sock, int level,
982 int optname)
983{
984 return aa_sock_opt_perm(OP_SETSOCKOPT, AA_MAY_SETOPT, sock,
985 level, optname);
986}
987
988/**
989 * apparmor_socket_shutdown - check perms before shutting down @sock conn
990 */
991static int apparmor_socket_shutdown(struct socket *sock, int how)
992{
993 return aa_sock_perm(OP_SHUTDOWN, AA_MAY_SHUTDOWN, sock);
994}
995
996/**
997 * apparmor_socket_sock_recv_skb - check perms before associating skb to sk
998 *
999 * Note: can not sleep may be called with locks held
1000 *
1001 * dont want protocol specific in __skb_recv_datagram()
1002 * to deny an incoming connection socket_sock_rcv_skb()
1003 */
1004static int apparmor_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
1005{
1006 return 0;
1007}
1008
1009
1010static struct aa_label *sk_peer_label(struct sock *sk)
1011{
1012 struct aa_sk_ctx *ctx = SK_CTX(sk);
1013
1014 if (ctx->peer)
1015 return ctx->peer;
1016
1017 return ERR_PTR(-ENOPROTOOPT);
1018}
1019
1020/**
1021 * apparmor_socket_getpeersec_stream - get security context of peer
1022 *
1023 * Note: for tcp only valid if using ipsec or cipso on lan
1024 */
1025static int apparmor_socket_getpeersec_stream(struct socket *sock,
1026 char __user *optval,
1027 int __user *optlen,
1028 unsigned int len)
1029{
1030 char *name;
1031 int slen, error = 0;
1032 struct aa_label *label;
1033 struct aa_label *peer;
1034
1035 label = begin_current_label_crit_section();
1036 peer = sk_peer_label(sock->sk);
1037 if (IS_ERR(peer)) {
1038 error = PTR_ERR(peer);
1039 goto done;
1040 }
1041 slen = aa_label_asxprint(&name, labels_ns(label), peer,
1042 FLAG_SHOW_MODE | FLAG_VIEW_SUBNS |
1043 FLAG_HIDDEN_UNCONFINED, GFP_KERNEL);
1044 /* don't include terminating \0 in slen, it breaks some apps */
1045 if (slen < 0) {
1046 error = -ENOMEM;
1047 } else {
1048 if (slen > len) {
1049 error = -ERANGE;
1050 } else if (copy_to_user(optval, name, slen)) {
1051 error = -EFAULT;
1052 goto out;
1053 }
1054 if (put_user(slen, optlen))
1055 error = -EFAULT;
1056out:
1057 kfree(name);
1058
1059 }
1060
1061done:
1062 end_current_label_crit_section(label);
1063
1064 return error;
1065}
1066
1067/**
1068 * apparmor_socket_getpeersec_dgram - get security label of packet
1069 * @sock: the peer socket
1070 * @skb: packet data
1071 * @secid: pointer to where to put the secid of the packet
1072 *
1073 * Sets the netlabel socket state on sk from parent
1074 */
1075static int apparmor_socket_getpeersec_dgram(struct socket *sock,
1076 struct sk_buff *skb, u32 *secid)
1077
1078{
1079 /* TODO: requires secid support */
1080 return -ENOPROTOOPT;
1081}
1082
1083/**
1084 * apparmor_sock_graft - Initialize newly created socket
1085 * @sk: child sock
1086 * @parent: parent socket
1087 *
1088 * Note: could set off of SOCK_CTX(parent) but need to track inode and we can
1089 * just set sk security information off of current creating process label
1090 * Labeling of sk for accept case - probably should be sock based
1091 * instead of task, because of the case where an implicitly labeled
1092 * socket is shared by different tasks.
1093 */
1094static void apparmor_sock_graft(struct sock *sk, struct socket *parent)
1095{
1096 struct aa_sk_ctx *ctx = SK_CTX(sk);
1097
1098 if (!ctx->label)
1099 ctx->label = aa_get_current_label();
1100}
1101
1102static struct security_hook_list apparmor_hooks[] __lsm_ro_after_init = { 739static struct security_hook_list apparmor_hooks[] __lsm_ro_after_init = {
1103 LSM_HOOK_INIT(ptrace_access_check, apparmor_ptrace_access_check), 740 LSM_HOOK_INIT(ptrace_access_check, apparmor_ptrace_access_check),
1104 LSM_HOOK_INIT(ptrace_traceme, apparmor_ptrace_traceme), 741 LSM_HOOK_INIT(ptrace_traceme, apparmor_ptrace_traceme),
@@ -1133,30 +770,6 @@ static struct security_hook_list apparmor_hooks[] __lsm_ro_after_init = {
1133 LSM_HOOK_INIT(getprocattr, apparmor_getprocattr), 770 LSM_HOOK_INIT(getprocattr, apparmor_getprocattr),
1134 LSM_HOOK_INIT(setprocattr, apparmor_setprocattr), 771 LSM_HOOK_INIT(setprocattr, apparmor_setprocattr),
1135 772
1136 LSM_HOOK_INIT(sk_alloc_security, apparmor_sk_alloc_security),
1137 LSM_HOOK_INIT(sk_free_security, apparmor_sk_free_security),
1138 LSM_HOOK_INIT(sk_clone_security, apparmor_sk_clone_security),
1139
1140 LSM_HOOK_INIT(socket_create, apparmor_socket_create),
1141 LSM_HOOK_INIT(socket_post_create, apparmor_socket_post_create),
1142 LSM_HOOK_INIT(socket_bind, apparmor_socket_bind),
1143 LSM_HOOK_INIT(socket_connect, apparmor_socket_connect),
1144 LSM_HOOK_INIT(socket_listen, apparmor_socket_listen),
1145 LSM_HOOK_INIT(socket_accept, apparmor_socket_accept),
1146 LSM_HOOK_INIT(socket_sendmsg, apparmor_socket_sendmsg),
1147 LSM_HOOK_INIT(socket_recvmsg, apparmor_socket_recvmsg),
1148 LSM_HOOK_INIT(socket_getsockname, apparmor_socket_getsockname),
1149 LSM_HOOK_INIT(socket_getpeername, apparmor_socket_getpeername),
1150 LSM_HOOK_INIT(socket_getsockopt, apparmor_socket_getsockopt),
1151 LSM_HOOK_INIT(socket_setsockopt, apparmor_socket_setsockopt),
1152 LSM_HOOK_INIT(socket_shutdown, apparmor_socket_shutdown),
1153 LSM_HOOK_INIT(socket_sock_rcv_skb, apparmor_socket_sock_rcv_skb),
1154 LSM_HOOK_INIT(socket_getpeersec_stream,
1155 apparmor_socket_getpeersec_stream),
1156 LSM_HOOK_INIT(socket_getpeersec_dgram,
1157 apparmor_socket_getpeersec_dgram),
1158 LSM_HOOK_INIT(sock_graft, apparmor_sock_graft),
1159
1160 LSM_HOOK_INIT(cred_alloc_blank, apparmor_cred_alloc_blank), 773 LSM_HOOK_INIT(cred_alloc_blank, apparmor_cred_alloc_blank),
1161 LSM_HOOK_INIT(cred_free, apparmor_cred_free), 774 LSM_HOOK_INIT(cred_free, apparmor_cred_free),
1162 LSM_HOOK_INIT(cred_prepare, apparmor_cred_prepare), 775 LSM_HOOK_INIT(cred_prepare, apparmor_cred_prepare),
@@ -1200,11 +813,11 @@ static const struct kernel_param_ops param_ops_aalockpolicy = {
1200 .get = param_get_aalockpolicy 813 .get = param_get_aalockpolicy
1201}; 814};
1202 815
1203static int param_set_audit(const char *val, struct kernel_param *kp); 816static int param_set_audit(const char *val, const struct kernel_param *kp);
1204static int param_get_audit(char *buffer, struct kernel_param *kp); 817static int param_get_audit(char *buffer, const struct kernel_param *kp);
1205 818
1206static int param_set_mode(const char *val, struct kernel_param *kp); 819static int param_set_mode(const char *val, const struct kernel_param *kp);
1207static int param_get_mode(char *buffer, struct kernel_param *kp); 820static int param_get_mode(char *buffer, const struct kernel_param *kp);
1208 821
1209/* Flag values, also controllable via /sys/module/apparmor/parameters 822/* Flag values, also controllable via /sys/module/apparmor/parameters
1210 * We define special types as we want to do additional mediation. 823 * We define special types as we want to do additional mediation.
@@ -1233,7 +846,7 @@ module_param_call(audit, param_set_audit, param_get_audit,
1233/* Determines if audit header is included in audited messages. This 846/* Determines if audit header is included in audited messages. This
1234 * provides more context if the audit daemon is not running 847 * provides more context if the audit daemon is not running
1235 */ 848 */
1236bool aa_g_audit_header = 1; 849bool aa_g_audit_header = true;
1237module_param_named(audit_header, aa_g_audit_header, aabool, 850module_param_named(audit_header, aa_g_audit_header, aabool,
1238 S_IRUSR | S_IWUSR); 851 S_IRUSR | S_IWUSR);
1239 852
@@ -1258,7 +871,7 @@ module_param_named(path_max, aa_g_path_max, aauint, S_IRUSR);
1258 * DEPRECATED: read only as strict checking of load is always done now 871 * DEPRECATED: read only as strict checking of load is always done now
1259 * that none root users (user namespaces) can load policy. 872 * that none root users (user namespaces) can load policy.
1260 */ 873 */
1261bool aa_g_paranoid_load = 1; 874bool aa_g_paranoid_load = true;
1262module_param_named(paranoid_load, aa_g_paranoid_load, aabool, S_IRUGO); 875module_param_named(paranoid_load, aa_g_paranoid_load, aabool, S_IRUGO);
1263 876
1264/* Boot time disable flag */ 877/* Boot time disable flag */
@@ -1338,7 +951,7 @@ static int param_get_aauint(char *buffer, const struct kernel_param *kp)
1338 return param_get_uint(buffer, kp); 951 return param_get_uint(buffer, kp);
1339} 952}
1340 953
1341static int param_get_audit(char *buffer, struct kernel_param *kp) 954static int param_get_audit(char *buffer, const struct kernel_param *kp)
1342{ 955{
1343 if (!apparmor_enabled) 956 if (!apparmor_enabled)
1344 return -EINVAL; 957 return -EINVAL;
@@ -1347,7 +960,7 @@ static int param_get_audit(char *buffer, struct kernel_param *kp)
1347 return sprintf(buffer, "%s", audit_mode_names[aa_g_audit]); 960 return sprintf(buffer, "%s", audit_mode_names[aa_g_audit]);
1348} 961}
1349 962
1350static int param_set_audit(const char *val, struct kernel_param *kp) 963static int param_set_audit(const char *val, const struct kernel_param *kp)
1351{ 964{
1352 int i; 965 int i;
1353 966
@@ -1368,7 +981,7 @@ static int param_set_audit(const char *val, struct kernel_param *kp)
1368 return -EINVAL; 981 return -EINVAL;
1369} 982}
1370 983
1371static int param_get_mode(char *buffer, struct kernel_param *kp) 984static int param_get_mode(char *buffer, const struct kernel_param *kp)
1372{ 985{
1373 if (!apparmor_enabled) 986 if (!apparmor_enabled)
1374 return -EINVAL; 987 return -EINVAL;
@@ -1378,7 +991,7 @@ static int param_get_mode(char *buffer, struct kernel_param *kp)
1378 return sprintf(buffer, "%s", aa_profile_mode_names[aa_g_profile_mode]); 991 return sprintf(buffer, "%s", aa_profile_mode_names[aa_g_profile_mode]);
1379} 992}
1380 993
1381static int param_set_mode(const char *val, struct kernel_param *kp) 994static int param_set_mode(const char *val, const struct kernel_param *kp)
1382{ 995{
1383 int i; 996 int i;
1384 997
@@ -1506,7 +1119,7 @@ static int __init apparmor_init(void)
1506 1119
1507 if (!apparmor_enabled || !security_module_enable("apparmor")) { 1120 if (!apparmor_enabled || !security_module_enable("apparmor")) {
1508 aa_info_message("AppArmor disabled by boot time parameter"); 1121 aa_info_message("AppArmor disabled by boot time parameter");
1509 apparmor_enabled = 0; 1122 apparmor_enabled = false;
1510 return 0; 1123 return 0;
1511 } 1124 }
1512 1125
@@ -1562,7 +1175,7 @@ alloc_out:
1562 aa_destroy_aafs(); 1175 aa_destroy_aafs();
1563 aa_teardown_dfa_engine(); 1176 aa_teardown_dfa_engine();
1564 1177
1565 apparmor_enabled = 0; 1178 apparmor_enabled = false;
1566 return error; 1179 return error;
1567} 1180}
1568 1181
diff --git a/security/apparmor/mount.c b/security/apparmor/mount.c
index 82a64b58041d..ed9b4d0f9f7e 100644
--- a/security/apparmor/mount.c
+++ b/security/apparmor/mount.c
@@ -216,13 +216,12 @@ static unsigned int match_mnt_flags(struct aa_dfa *dfa, unsigned int state,
216static struct aa_perms compute_mnt_perms(struct aa_dfa *dfa, 216static struct aa_perms compute_mnt_perms(struct aa_dfa *dfa,
217 unsigned int state) 217 unsigned int state)
218{ 218{
219 struct aa_perms perms; 219 struct aa_perms perms = {
220 220 .allow = dfa_user_allow(dfa, state),
221 perms.kill = 0; 221 .audit = dfa_user_audit(dfa, state),
222 perms.allow = dfa_user_allow(dfa, state); 222 .quiet = dfa_user_quiet(dfa, state),
223 perms.audit = dfa_user_audit(dfa, state); 223 .xindex = dfa_user_xindex(dfa, state),
224 perms.quiet = dfa_user_quiet(dfa, state); 224 };
225 perms.xindex = dfa_user_xindex(dfa, state);
226 225
227 return perms; 226 return perms;
228} 227}
diff --git a/security/apparmor/net.c b/security/apparmor/net.c
deleted file mode 100644
index 33d54435f8d6..000000000000
--- a/security/apparmor/net.c
+++ /dev/null
@@ -1,184 +0,0 @@
1/*
2 * AppArmor security module
3 *
4 * This file contains AppArmor network mediation
5 *
6 * Copyright (C) 1998-2008 Novell/SUSE
7 * Copyright 2009-2017 Canonical Ltd.
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as
11 * published by the Free Software Foundation, version 2 of the
12 * License.
13 */
14
15#include "include/apparmor.h"
16#include "include/audit.h"
17#include "include/context.h"
18#include "include/label.h"
19#include "include/net.h"
20#include "include/policy.h"
21
22#include "net_names.h"
23
24
25struct aa_sfs_entry aa_sfs_entry_network[] = {
26 AA_SFS_FILE_STRING("af_mask", AA_SFS_AF_MASK),
27 { }
28};
29
30static const char * const net_mask_names[] = {
31 "unknown",
32 "send",
33 "receive",
34 "unknown",
35
36 "create",
37 "shutdown",
38 "connect",
39 "unknown",
40
41 "setattr",
42 "getattr",
43 "setcred",
44 "getcred",
45
46 "chmod",
47 "chown",
48 "chgrp",
49 "lock",
50
51 "mmap",
52 "mprot",
53 "unknown",
54 "unknown",
55
56 "accept",
57 "bind",
58 "listen",
59 "unknown",
60
61 "setopt",
62 "getopt",
63 "unknown",
64 "unknown",
65
66 "unknown",
67 "unknown",
68 "unknown",
69 "unknown",
70};
71
72
73/* audit callback for net specific fields */
74void audit_net_cb(struct audit_buffer *ab, void *va)
75{
76 struct common_audit_data *sa = va;
77
78 audit_log_format(ab, " family=");
79 if (address_family_names[sa->u.net->family])
80 audit_log_string(ab, address_family_names[sa->u.net->family]);
81 else
82 audit_log_format(ab, "\"unknown(%d)\"", sa->u.net->family);
83 audit_log_format(ab, " sock_type=");
84 if (sock_type_names[aad(sa)->net.type])
85 audit_log_string(ab, sock_type_names[aad(sa)->net.type]);
86 else
87 audit_log_format(ab, "\"unknown(%d)\"", aad(sa)->net.type);
88 audit_log_format(ab, " protocol=%d", aad(sa)->net.protocol);
89
90 if (aad(sa)->request & NET_PERMS_MASK) {
91 audit_log_format(ab, " requested_mask=");
92 aa_audit_perm_mask(ab, aad(sa)->request, NULL, 0,
93 net_mask_names, NET_PERMS_MASK);
94
95 if (aad(sa)->denied & NET_PERMS_MASK) {
96 audit_log_format(ab, " denied_mask=");
97 aa_audit_perm_mask(ab, aad(sa)->denied, NULL, 0,
98 net_mask_names, NET_PERMS_MASK);
99 }
100 }
101 if (aad(sa)->peer) {
102 audit_log_format(ab, " peer=");
103 aa_label_xaudit(ab, labels_ns(aad(sa)->label), aad(sa)->peer,
104 FLAGS_NONE, GFP_ATOMIC);
105 }
106}
107
108
109/* Generic af perm */
110int aa_profile_af_perm(struct aa_profile *profile, struct common_audit_data *sa,
111 u32 request, u16 family, int type)
112{
113 struct aa_perms perms = { };
114
115 AA_BUG(family >= AF_MAX);
116 AA_BUG(type < 0 || type >= SOCK_MAX);
117
118 if (profile_unconfined(profile))
119 return 0;
120
121 perms.allow = (profile->net.allow[family] & (1 << type)) ?
122 ALL_PERMS_MASK : 0;
123 perms.audit = (profile->net.audit[family] & (1 << type)) ?
124 ALL_PERMS_MASK : 0;
125 perms.quiet = (profile->net.quiet[family] & (1 << type)) ?
126 ALL_PERMS_MASK : 0;
127 aa_apply_modes_to_perms(profile, &perms);
128
129 return aa_check_perms(profile, &perms, request, sa, audit_net_cb);
130}
131
132int aa_af_perm(struct aa_label *label, const char *op, u32 request, u16 family,
133 int type, int protocol)
134{
135 struct aa_profile *profile;
136 DEFINE_AUDIT_NET(sa, op, NULL, family, type, protocol);
137
138 return fn_for_each_confined(label, profile,
139 aa_profile_af_perm(profile, &sa, request, family,
140 type));
141}
142
143static int aa_label_sk_perm(struct aa_label *label, const char *op, u32 request,
144 struct sock *sk)
145{
146 struct aa_profile *profile;
147 DEFINE_AUDIT_SK(sa, op, sk);
148
149 AA_BUG(!label);
150 AA_BUG(!sk);
151
152 if (unconfined(label))
153 return 0;
154
155 return fn_for_each_confined(label, profile,
156 aa_profile_af_sk_perm(profile, &sa, request, sk));
157}
158
159int aa_sk_perm(const char *op, u32 request, struct sock *sk)
160{
161 struct aa_label *label;
162 int error;
163
164 AA_BUG(!sk);
165 AA_BUG(in_interrupt());
166
167 /* TODO: switch to begin_current_label ???? */
168 label = begin_current_label_crit_section();
169 error = aa_label_sk_perm(label, op, request, sk);
170 end_current_label_crit_section(label);
171
172 return error;
173}
174
175
176int aa_sock_file_perm(struct aa_label *label, const char *op, u32 request,
177 struct socket *sock)
178{
179 AA_BUG(!label);
180 AA_BUG(!sock);
181 AA_BUG(!sock->sk);
182
183 return aa_label_sk_perm(label, op, request, sock->sk);
184}
diff --git a/security/apparmor/policy.c b/security/apparmor/policy.c
index 4243b0c3f0e4..b0b58848c248 100644
--- a/security/apparmor/policy.c
+++ b/security/apparmor/policy.c
@@ -502,7 +502,7 @@ struct aa_profile *aa_new_null_profile(struct aa_profile *parent, bool hat,
502{ 502{
503 struct aa_profile *p, *profile; 503 struct aa_profile *p, *profile;
504 const char *bname; 504 const char *bname;
505 char *name; 505 char *name = NULL;
506 506
507 AA_BUG(!parent); 507 AA_BUG(!parent);
508 508
@@ -545,7 +545,7 @@ name:
545 profile->file.dfa = aa_get_dfa(nulldfa); 545 profile->file.dfa = aa_get_dfa(nulldfa);
546 profile->policy.dfa = aa_get_dfa(nulldfa); 546 profile->policy.dfa = aa_get_dfa(nulldfa);
547 547
548 mutex_lock(&profile->ns->lock); 548 mutex_lock_nested(&profile->ns->lock, profile->ns->level);
549 p = __find_child(&parent->base.profiles, bname); 549 p = __find_child(&parent->base.profiles, bname);
550 if (p) { 550 if (p) {
551 aa_free_profile(profile); 551 aa_free_profile(profile);
@@ -562,6 +562,7 @@ out:
562 return profile; 562 return profile;
563 563
564fail: 564fail:
565 kfree(name);
565 aa_free_profile(profile); 566 aa_free_profile(profile);
566 return NULL; 567 return NULL;
567} 568}
@@ -905,7 +906,7 @@ ssize_t aa_replace_profiles(struct aa_ns *policy_ns, struct aa_label *label,
905 } else 906 } else
906 ns = aa_get_ns(policy_ns ? policy_ns : labels_ns(label)); 907 ns = aa_get_ns(policy_ns ? policy_ns : labels_ns(label));
907 908
908 mutex_lock(&ns->lock); 909 mutex_lock_nested(&ns->lock, ns->level);
909 /* check for duplicate rawdata blobs: space and file dedup */ 910 /* check for duplicate rawdata blobs: space and file dedup */
910 list_for_each_entry(rawdata_ent, &ns->rawdata_list, list) { 911 list_for_each_entry(rawdata_ent, &ns->rawdata_list, list) {
911 if (aa_rawdata_eq(rawdata_ent, udata)) { 912 if (aa_rawdata_eq(rawdata_ent, udata)) {
@@ -1116,13 +1117,13 @@ ssize_t aa_remove_profiles(struct aa_ns *policy_ns, struct aa_label *subj,
1116 1117
1117 if (!name) { 1118 if (!name) {
1118 /* remove namespace - can only happen if fqname[0] == ':' */ 1119 /* remove namespace - can only happen if fqname[0] == ':' */
1119 mutex_lock(&ns->parent->lock); 1120 mutex_lock_nested(&ns->parent->lock, ns->level);
1120 __aa_remove_ns(ns); 1121 __aa_remove_ns(ns);
1121 __aa_bump_ns_revision(ns); 1122 __aa_bump_ns_revision(ns);
1122 mutex_unlock(&ns->parent->lock); 1123 mutex_unlock(&ns->parent->lock);
1123 } else { 1124 } else {
1124 /* remove profile */ 1125 /* remove profile */
1125 mutex_lock(&ns->lock); 1126 mutex_lock_nested(&ns->lock, ns->level);
1126 profile = aa_get_profile(__lookup_profile(&ns->base, name)); 1127 profile = aa_get_profile(__lookup_profile(&ns->base, name));
1127 if (!profile) { 1128 if (!profile) {
1128 error = -ENOENT; 1129 error = -ENOENT;
diff --git a/security/apparmor/policy_ns.c b/security/apparmor/policy_ns.c
index 62a3589c62ab..b1e629cba70b 100644
--- a/security/apparmor/policy_ns.c
+++ b/security/apparmor/policy_ns.c
@@ -256,7 +256,8 @@ static struct aa_ns *__aa_create_ns(struct aa_ns *parent, const char *name,
256 ns = alloc_ns(parent->base.hname, name); 256 ns = alloc_ns(parent->base.hname, name);
257 if (!ns) 257 if (!ns)
258 return NULL; 258 return NULL;
259 mutex_lock(&ns->lock); 259 ns->level = parent->level + 1;
260 mutex_lock_nested(&ns->lock, ns->level);
260 error = __aafs_ns_mkdir(ns, ns_subns_dir(parent), name, dir); 261 error = __aafs_ns_mkdir(ns, ns_subns_dir(parent), name, dir);
261 if (error) { 262 if (error) {
262 AA_ERROR("Failed to create interface for ns %s\n", 263 AA_ERROR("Failed to create interface for ns %s\n",
@@ -266,7 +267,6 @@ static struct aa_ns *__aa_create_ns(struct aa_ns *parent, const char *name,
266 return ERR_PTR(error); 267 return ERR_PTR(error);
267 } 268 }
268 ns->parent = aa_get_ns(parent); 269 ns->parent = aa_get_ns(parent);
269 ns->level = parent->level + 1;
270 list_add_rcu(&ns->base.list, &parent->sub_ns); 270 list_add_rcu(&ns->base.list, &parent->sub_ns);
271 /* add list ref */ 271 /* add list ref */
272 aa_get_ns(ns); 272 aa_get_ns(ns);
@@ -313,7 +313,7 @@ struct aa_ns *aa_prepare_ns(struct aa_ns *parent, const char *name)
313{ 313{
314 struct aa_ns *ns; 314 struct aa_ns *ns;
315 315
316 mutex_lock(&parent->lock); 316 mutex_lock_nested(&parent->lock, parent->level);
317 /* try and find the specified ns and if it doesn't exist create it */ 317 /* try and find the specified ns and if it doesn't exist create it */
318 /* released by caller */ 318 /* released by caller */
319 ns = aa_get_ns(__aa_find_ns(&parent->sub_ns, name)); 319 ns = aa_get_ns(__aa_find_ns(&parent->sub_ns, name));
@@ -336,7 +336,7 @@ static void destroy_ns(struct aa_ns *ns)
336 if (!ns) 336 if (!ns)
337 return; 337 return;
338 338
339 mutex_lock(&ns->lock); 339 mutex_lock_nested(&ns->lock, ns->level);
340 /* release all profiles in this namespace */ 340 /* release all profiles in this namespace */
341 __aa_profile_list_release(&ns->base.profiles); 341 __aa_profile_list_release(&ns->base.profiles);
342 342
diff --git a/security/apparmor/policy_unpack.c b/security/apparmor/policy_unpack.c
index 5a2aec358322..59a1a25b7d43 100644
--- a/security/apparmor/policy_unpack.c
+++ b/security/apparmor/policy_unpack.c
@@ -157,7 +157,7 @@ static void do_loaddata_free(struct work_struct *work)
157 struct aa_ns *ns = aa_get_ns(d->ns); 157 struct aa_ns *ns = aa_get_ns(d->ns);
158 158
159 if (ns) { 159 if (ns) {
160 mutex_lock(&ns->lock); 160 mutex_lock_nested(&ns->lock, ns->level);
161 __aa_fs_remove_rawdata(d); 161 __aa_fs_remove_rawdata(d);
162 mutex_unlock(&ns->lock); 162 mutex_unlock(&ns->lock);
163 aa_put_ns(ns); 163 aa_put_ns(ns);
@@ -275,19 +275,6 @@ fail:
275 return 0; 275 return 0;
276} 276}
277 277
278static bool unpack_u16(struct aa_ext *e, u16 *data, const char *name)
279{
280 if (unpack_nameX(e, AA_U16, name)) {
281 if (!inbounds(e, sizeof(u16)))
282 return 0;
283 if (data)
284 *data = le16_to_cpu(get_unaligned((__le16 *) e->pos));
285 e->pos += sizeof(u16);
286 return 1;
287 }
288 return 0;
289}
290
291static bool unpack_u32(struct aa_ext *e, u32 *data, const char *name) 278static bool unpack_u32(struct aa_ext *e, u32 *data, const char *name)
292{ 279{
293 if (unpack_nameX(e, AA_U32, name)) { 280 if (unpack_nameX(e, AA_U32, name)) {
@@ -597,7 +584,7 @@ static struct aa_profile *unpack_profile(struct aa_ext *e, char **ns_name)
597 struct aa_profile *profile = NULL; 584 struct aa_profile *profile = NULL;
598 const char *tmpname, *tmpns = NULL, *name = NULL; 585 const char *tmpname, *tmpns = NULL, *name = NULL;
599 const char *info = "failed to unpack profile"; 586 const char *info = "failed to unpack profile";
600 size_t size = 0, ns_len; 587 size_t ns_len;
601 struct rhashtable_params params = { 0 }; 588 struct rhashtable_params params = { 0 };
602 char *key = NULL; 589 char *key = NULL;
603 struct aa_data *data; 590 struct aa_data *data;
@@ -730,38 +717,6 @@ static struct aa_profile *unpack_profile(struct aa_ext *e, char **ns_name)
730 goto fail; 717 goto fail;
731 } 718 }
732 719
733 size = unpack_array(e, "net_allowed_af");
734 if (size) {
735
736 for (i = 0; i < size; i++) {
737 /* discard extraneous rules that this kernel will
738 * never request
739 */
740 if (i >= AF_MAX) {
741 u16 tmp;
742
743 if (!unpack_u16(e, &tmp, NULL) ||
744 !unpack_u16(e, &tmp, NULL) ||
745 !unpack_u16(e, &tmp, NULL))
746 goto fail;
747 continue;
748 }
749 if (!unpack_u16(e, &profile->net.allow[i], NULL))
750 goto fail;
751 if (!unpack_u16(e, &profile->net.audit[i], NULL))
752 goto fail;
753 if (!unpack_u16(e, &profile->net.quiet[i], NULL))
754 goto fail;
755 }
756 if (!unpack_nameX(e, AA_ARRAYEND, NULL))
757 goto fail;
758 }
759 if (VERSION_LT(e->version, v7)) {
760 /* pre v7 policy always allowed these */
761 profile->net.allow[AF_UNIX] = 0xffff;
762 profile->net.allow[AF_NETLINK] = 0xffff;
763 }
764
765 if (unpack_nameX(e, AA_STRUCT, "policydb")) { 720 if (unpack_nameX(e, AA_STRUCT, "policydb")) {
766 /* generic policy dfa - optional and may be NULL */ 721 /* generic policy dfa - optional and may be NULL */
767 info = "failed to unpack policydb"; 722 info = "failed to unpack policydb";
diff --git a/security/apparmor/resource.c b/security/apparmor/resource.c
index d8bc842594ed..cf4d234febe9 100644
--- a/security/apparmor/resource.c
+++ b/security/apparmor/resource.c
@@ -47,7 +47,7 @@ static void audit_cb(struct audit_buffer *ab, void *va)
47/** 47/**
48 * audit_resource - audit setting resource limit 48 * audit_resource - audit setting resource limit
49 * @profile: profile being enforced (NOT NULL) 49 * @profile: profile being enforced (NOT NULL)
50 * @resoure: rlimit being auditing 50 * @resource: rlimit being auditing
51 * @value: value being set 51 * @value: value being set
52 * @error: error value 52 * @error: error value
53 * 53 *
@@ -128,7 +128,7 @@ int aa_task_setrlimit(struct aa_label *label, struct task_struct *task,
128 error = fn_for_each(label, profile, 128 error = fn_for_each(label, profile,
129 audit_resource(profile, resource, 129 audit_resource(profile, resource,
130 new_rlim->rlim_max, peer, 130 new_rlim->rlim_max, peer,
131 "cap_sys_resoure", -EACCES)); 131 "cap_sys_resource", -EACCES));
132 else 132 else
133 error = fn_for_each_confined(label, profile, 133 error = fn_for_each_confined(label, profile,
134 profile_setrlimit(profile, resource, new_rlim)); 134 profile_setrlimit(profile, resource, new_rlim));
diff --git a/security/commoncap.c b/security/commoncap.c
index 5fa839c7fb3f..4f8e09340956 100644
--- a/security/commoncap.c
+++ b/security/commoncap.c
@@ -585,13 +585,14 @@ int get_vfs_caps_from_disk(const struct dentry *dentry, struct cpu_vfs_cap_data
585 struct vfs_ns_cap_data data, *nscaps = &data; 585 struct vfs_ns_cap_data data, *nscaps = &data;
586 struct vfs_cap_data *caps = (struct vfs_cap_data *) &data; 586 struct vfs_cap_data *caps = (struct vfs_cap_data *) &data;
587 kuid_t rootkuid; 587 kuid_t rootkuid;
588 struct user_namespace *fs_ns = inode->i_sb->s_user_ns; 588 struct user_namespace *fs_ns;
589 589
590 memset(cpu_caps, 0, sizeof(struct cpu_vfs_cap_data)); 590 memset(cpu_caps, 0, sizeof(struct cpu_vfs_cap_data));
591 591
592 if (!inode) 592 if (!inode)
593 return -ENODATA; 593 return -ENODATA;
594 594
595 fs_ns = inode->i_sb->s_user_ns;
595 size = __vfs_getxattr((struct dentry *)dentry, inode, 596 size = __vfs_getxattr((struct dentry *)dentry, inode,
596 XATTR_NAME_CAPS, &data, XATTR_CAPS_SZ); 597 XATTR_NAME_CAPS, &data, XATTR_CAPS_SZ);
597 if (size == -ENODATA || size == -EOPNOTSUPP) 598 if (size == -ENODATA || size == -EOPNOTSUPP)
diff --git a/security/device_cgroup.c b/security/device_cgroup.c
index 03c1652c9a1f..c65b39bafdfe 100644
--- a/security/device_cgroup.c
+++ b/security/device_cgroup.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * device_cgroup.c - device cgroup subsystem 3 * device_cgroup.c - device cgroup subsystem
3 * 4 *
@@ -14,15 +15,6 @@
14#include <linux/rcupdate.h> 15#include <linux/rcupdate.h>
15#include <linux/mutex.h> 16#include <linux/mutex.h>
16 17
17#define ACC_MKNOD 1
18#define ACC_READ 2
19#define ACC_WRITE 4
20#define ACC_MASK (ACC_MKNOD | ACC_READ | ACC_WRITE)
21
22#define DEV_BLOCK 1
23#define DEV_CHAR 2
24#define DEV_ALL 4 /* this represents all devices */
25
26static DEFINE_MUTEX(devcgroup_mutex); 18static DEFINE_MUTEX(devcgroup_mutex);
27 19
28enum devcg_behavior { 20enum devcg_behavior {
@@ -245,21 +237,21 @@ static void set_access(char *acc, short access)
245{ 237{
246 int idx = 0; 238 int idx = 0;
247 memset(acc, 0, ACCLEN); 239 memset(acc, 0, ACCLEN);
248 if (access & ACC_READ) 240 if (access & DEVCG_ACC_READ)
249 acc[idx++] = 'r'; 241 acc[idx++] = 'r';
250 if (access & ACC_WRITE) 242 if (access & DEVCG_ACC_WRITE)
251 acc[idx++] = 'w'; 243 acc[idx++] = 'w';
252 if (access & ACC_MKNOD) 244 if (access & DEVCG_ACC_MKNOD)
253 acc[idx++] = 'm'; 245 acc[idx++] = 'm';
254} 246}
255 247
256static char type_to_char(short type) 248static char type_to_char(short type)
257{ 249{
258 if (type == DEV_ALL) 250 if (type == DEVCG_DEV_ALL)
259 return 'a'; 251 return 'a';
260 if (type == DEV_CHAR) 252 if (type == DEVCG_DEV_CHAR)
261 return 'c'; 253 return 'c';
262 if (type == DEV_BLOCK) 254 if (type == DEVCG_DEV_BLOCK)
263 return 'b'; 255 return 'b';
264 return 'X'; 256 return 'X';
265} 257}
@@ -286,10 +278,10 @@ static int devcgroup_seq_show(struct seq_file *m, void *v)
286 * This way, the file remains as a "whitelist of devices" 278 * This way, the file remains as a "whitelist of devices"
287 */ 279 */
288 if (devcgroup->behavior == DEVCG_DEFAULT_ALLOW) { 280 if (devcgroup->behavior == DEVCG_DEFAULT_ALLOW) {
289 set_access(acc, ACC_MASK); 281 set_access(acc, DEVCG_ACC_MASK);
290 set_majmin(maj, ~0); 282 set_majmin(maj, ~0);
291 set_majmin(min, ~0); 283 set_majmin(min, ~0);
292 seq_printf(m, "%c %s:%s %s\n", type_to_char(DEV_ALL), 284 seq_printf(m, "%c %s:%s %s\n", type_to_char(DEVCG_DEV_ALL),
293 maj, min, acc); 285 maj, min, acc);
294 } else { 286 } else {
295 list_for_each_entry_rcu(ex, &devcgroup->exceptions, list) { 287 list_for_each_entry_rcu(ex, &devcgroup->exceptions, list) {
@@ -308,10 +300,10 @@ static int devcgroup_seq_show(struct seq_file *m, void *v)
308/** 300/**
309 * match_exception - iterates the exception list trying to find a complete match 301 * match_exception - iterates the exception list trying to find a complete match
310 * @exceptions: list of exceptions 302 * @exceptions: list of exceptions
311 * @type: device type (DEV_BLOCK or DEV_CHAR) 303 * @type: device type (DEVCG_DEV_BLOCK or DEVCG_DEV_CHAR)
312 * @major: device file major number, ~0 to match all 304 * @major: device file major number, ~0 to match all
313 * @minor: device file minor number, ~0 to match all 305 * @minor: device file minor number, ~0 to match all
314 * @access: permission mask (ACC_READ, ACC_WRITE, ACC_MKNOD) 306 * @access: permission mask (DEVCG_ACC_READ, DEVCG_ACC_WRITE, DEVCG_ACC_MKNOD)
315 * 307 *
316 * It is considered a complete match if an exception is found that will 308 * It is considered a complete match if an exception is found that will
317 * contain the entire range of provided parameters. 309 * contain the entire range of provided parameters.
@@ -324,9 +316,9 @@ static bool match_exception(struct list_head *exceptions, short type,
324 struct dev_exception_item *ex; 316 struct dev_exception_item *ex;
325 317
326 list_for_each_entry_rcu(ex, exceptions, list) { 318 list_for_each_entry_rcu(ex, exceptions, list) {
327 if ((type & DEV_BLOCK) && !(ex->type & DEV_BLOCK)) 319 if ((type & DEVCG_DEV_BLOCK) && !(ex->type & DEVCG_DEV_BLOCK))
328 continue; 320 continue;
329 if ((type & DEV_CHAR) && !(ex->type & DEV_CHAR)) 321 if ((type & DEVCG_DEV_CHAR) && !(ex->type & DEVCG_DEV_CHAR))
330 continue; 322 continue;
331 if (ex->major != ~0 && ex->major != major) 323 if (ex->major != ~0 && ex->major != major)
332 continue; 324 continue;
@@ -343,10 +335,10 @@ static bool match_exception(struct list_head *exceptions, short type,
343/** 335/**
344 * match_exception_partial - iterates the exception list trying to find a partial match 336 * match_exception_partial - iterates the exception list trying to find a partial match
345 * @exceptions: list of exceptions 337 * @exceptions: list of exceptions
346 * @type: device type (DEV_BLOCK or DEV_CHAR) 338 * @type: device type (DEVCG_DEV_BLOCK or DEVCG_DEV_CHAR)
347 * @major: device file major number, ~0 to match all 339 * @major: device file major number, ~0 to match all
348 * @minor: device file minor number, ~0 to match all 340 * @minor: device file minor number, ~0 to match all
349 * @access: permission mask (ACC_READ, ACC_WRITE, ACC_MKNOD) 341 * @access: permission mask (DEVCG_ACC_READ, DEVCG_ACC_WRITE, DEVCG_ACC_MKNOD)
350 * 342 *
351 * It is considered a partial match if an exception's range is found to 343 * It is considered a partial match if an exception's range is found to
352 * contain *any* of the devices specified by provided parameters. This is 344 * contain *any* of the devices specified by provided parameters. This is
@@ -361,9 +353,9 @@ static bool match_exception_partial(struct list_head *exceptions, short type,
361 struct dev_exception_item *ex; 353 struct dev_exception_item *ex;
362 354
363 list_for_each_entry_rcu(ex, exceptions, list) { 355 list_for_each_entry_rcu(ex, exceptions, list) {
364 if ((type & DEV_BLOCK) && !(ex->type & DEV_BLOCK)) 356 if ((type & DEVCG_DEV_BLOCK) && !(ex->type & DEVCG_DEV_BLOCK))
365 continue; 357 continue;
366 if ((type & DEV_CHAR) && !(ex->type & DEV_CHAR)) 358 if ((type & DEVCG_DEV_CHAR) && !(ex->type & DEVCG_DEV_CHAR))
367 continue; 359 continue;
368 /* 360 /*
369 * We must be sure that both the exception and the provided 361 * We must be sure that both the exception and the provided
@@ -646,10 +638,10 @@ static int devcgroup_update_access(struct dev_cgroup *devcgroup,
646 } 638 }
647 return 0; 639 return 0;
648 case 'b': 640 case 'b':
649 ex.type = DEV_BLOCK; 641 ex.type = DEVCG_DEV_BLOCK;
650 break; 642 break;
651 case 'c': 643 case 'c':
652 ex.type = DEV_CHAR; 644 ex.type = DEVCG_DEV_CHAR;
653 break; 645 break;
654 default: 646 default:
655 return -EINVAL; 647 return -EINVAL;
@@ -702,13 +694,13 @@ static int devcgroup_update_access(struct dev_cgroup *devcgroup,
702 for (b++, count = 0; count < 3; count++, b++) { 694 for (b++, count = 0; count < 3; count++, b++) {
703 switch (*b) { 695 switch (*b) {
704 case 'r': 696 case 'r':
705 ex.access |= ACC_READ; 697 ex.access |= DEVCG_ACC_READ;
706 break; 698 break;
707 case 'w': 699 case 'w':
708 ex.access |= ACC_WRITE; 700 ex.access |= DEVCG_ACC_WRITE;
709 break; 701 break;
710 case 'm': 702 case 'm':
711 ex.access |= ACC_MKNOD; 703 ex.access |= DEVCG_ACC_MKNOD;
712 break; 704 break;
713 case '\n': 705 case '\n':
714 case '\0': 706 case '\0':
@@ -805,12 +797,12 @@ struct cgroup_subsys devices_cgrp_subsys = {
805 * @type: device type 797 * @type: device type
806 * @major: device major number 798 * @major: device major number
807 * @minor: device minor number 799 * @minor: device minor number
808 * @access: combination of ACC_WRITE, ACC_READ and ACC_MKNOD 800 * @access: combination of DEVCG_ACC_WRITE, DEVCG_ACC_READ and DEVCG_ACC_MKNOD
809 * 801 *
810 * returns 0 on success, -EPERM case the operation is not permitted 802 * returns 0 on success, -EPERM case the operation is not permitted
811 */ 803 */
812static int __devcgroup_check_permission(short type, u32 major, u32 minor, 804int __devcgroup_check_permission(short type, u32 major, u32 minor,
813 short access) 805 short access)
814{ 806{
815 struct dev_cgroup *dev_cgroup; 807 struct dev_cgroup *dev_cgroup;
816 bool rc; 808 bool rc;
@@ -832,37 +824,3 @@ static int __devcgroup_check_permission(short type, u32 major, u32 minor,
832 824
833 return 0; 825 return 0;
834} 826}
835
836int __devcgroup_inode_permission(struct inode *inode, int mask)
837{
838 short type, access = 0;
839
840 if (S_ISBLK(inode->i_mode))
841 type = DEV_BLOCK;
842 if (S_ISCHR(inode->i_mode))
843 type = DEV_CHAR;
844 if (mask & MAY_WRITE)
845 access |= ACC_WRITE;
846 if (mask & MAY_READ)
847 access |= ACC_READ;
848
849 return __devcgroup_check_permission(type, imajor(inode), iminor(inode),
850 access);
851}
852
853int devcgroup_inode_mknod(int mode, dev_t dev)
854{
855 short type;
856
857 if (!S_ISBLK(mode) && !S_ISCHR(mode))
858 return 0;
859
860 if (S_ISBLK(mode))
861 type = DEV_BLOCK;
862 else
863 type = DEV_CHAR;
864
865 return __devcgroup_check_permission(type, MAJOR(dev), MINOR(dev),
866 ACC_MKNOD);
867
868}
diff --git a/security/integrity/Makefile b/security/integrity/Makefile
index 8d1f4bf51087..04d6e462b079 100644
--- a/security/integrity/Makefile
+++ b/security/integrity/Makefile
@@ -1,3 +1,4 @@
1# SPDX-License-Identifier: GPL-2.0
1# 2#
2# Makefile for caching inode integrity data (iint) 3# Makefile for caching inode integrity data (iint)
3# 4#
diff --git a/security/integrity/digsig.c b/security/integrity/digsig.c
index 06554c448dce..6f9e4ce568cd 100644
--- a/security/integrity/digsig.c
+++ b/security/integrity/digsig.c
@@ -112,21 +112,25 @@ int __init integrity_init_keyring(const unsigned int id)
112int __init integrity_load_x509(const unsigned int id, const char *path) 112int __init integrity_load_x509(const unsigned int id, const char *path)
113{ 113{
114 key_ref_t key; 114 key_ref_t key;
115 char *data; 115 void *data;
116 loff_t size;
116 int rc; 117 int rc;
117 118
118 if (!keyring[id]) 119 if (!keyring[id])
119 return -EINVAL; 120 return -EINVAL;
120 121
121 rc = integrity_read_file(path, &data); 122 rc = kernel_read_file_from_path(path, &data, &size, 0,
122 if (rc < 0) 123 READING_X509_CERTIFICATE);
124 if (rc < 0) {
125 pr_err("Unable to open file: %s (%d)", path, rc);
123 return rc; 126 return rc;
127 }
124 128
125 key = key_create_or_update(make_key_ref(keyring[id], 1), 129 key = key_create_or_update(make_key_ref(keyring[id], 1),
126 "asymmetric", 130 "asymmetric",
127 NULL, 131 NULL,
128 data, 132 data,
129 rc, 133 size,
130 ((KEY_POS_ALL & ~KEY_POS_SETATTR) | 134 ((KEY_POS_ALL & ~KEY_POS_SETATTR) |
131 KEY_USR_VIEW | KEY_USR_READ), 135 KEY_USR_VIEW | KEY_USR_READ),
132 KEY_ALLOC_NOT_IN_QUOTA); 136 KEY_ALLOC_NOT_IN_QUOTA);
@@ -139,6 +143,6 @@ int __init integrity_load_x509(const unsigned int id, const char *path)
139 key_ref_to_ptr(key)->description, path); 143 key_ref_to_ptr(key)->description, path);
140 key_ref_put(key); 144 key_ref_put(key);
141 } 145 }
142 kfree(data); 146 vfree(data);
143 return 0; 147 return 0;
144} 148}
diff --git a/security/integrity/evm/evm.h b/security/integrity/evm/evm.h
index f5f12727771a..241aca315b0c 100644
--- a/security/integrity/evm/evm.h
+++ b/security/integrity/evm/evm.h
@@ -23,6 +23,9 @@
23 23
24#define EVM_INIT_HMAC 0x0001 24#define EVM_INIT_HMAC 0x0001
25#define EVM_INIT_X509 0x0002 25#define EVM_INIT_X509 0x0002
26#define EVM_SETUP 0x80000000 /* userland has signaled key load */
27
28#define EVM_INIT_MASK (EVM_INIT_HMAC | EVM_INIT_X509 | EVM_SETUP)
26 29
27extern int evm_initialized; 30extern int evm_initialized;
28extern char *evm_hmac; 31extern char *evm_hmac;
diff --git a/security/integrity/evm/evm_crypto.c b/security/integrity/evm/evm_crypto.c
index 1d32cd20009a..bcd64baf8788 100644
--- a/security/integrity/evm/evm_crypto.c
+++ b/security/integrity/evm/evm_crypto.c
@@ -80,7 +80,7 @@ static struct shash_desc *init_desc(char type)
80 80
81 if (type == EVM_XATTR_HMAC) { 81 if (type == EVM_XATTR_HMAC) {
82 if (!(evm_initialized & EVM_INIT_HMAC)) { 82 if (!(evm_initialized & EVM_INIT_HMAC)) {
83 pr_err("HMAC key is not set\n"); 83 pr_err_once("HMAC key is not set\n");
84 return ERR_PTR(-ENOKEY); 84 return ERR_PTR(-ENOKEY);
85 } 85 }
86 tfm = &hmac_tfm; 86 tfm = &hmac_tfm;
diff --git a/security/integrity/evm/evm_main.c b/security/integrity/evm/evm_main.c
index 063d38aef64e..9826c02e2db8 100644
--- a/security/integrity/evm/evm_main.c
+++ b/security/integrity/evm/evm_main.c
@@ -49,6 +49,9 @@ char *evm_config_xattrnames[] = {
49 XATTR_NAME_SMACKMMAP, 49 XATTR_NAME_SMACKMMAP,
50#endif 50#endif
51#endif 51#endif
52#ifdef CONFIG_SECURITY_APPARMOR
53 XATTR_NAME_APPARMOR,
54#endif
52#ifdef CONFIG_IMA_APPRAISE 55#ifdef CONFIG_IMA_APPRAISE
53 XATTR_NAME_IMA, 56 XATTR_NAME_IMA,
54#endif 57#endif
diff --git a/security/integrity/evm/evm_secfs.c b/security/integrity/evm/evm_secfs.c
index c8dccd54d501..319cf16d6603 100644
--- a/security/integrity/evm/evm_secfs.c
+++ b/security/integrity/evm/evm_secfs.c
@@ -40,7 +40,7 @@ static ssize_t evm_read_key(struct file *filp, char __user *buf,
40 if (*ppos != 0) 40 if (*ppos != 0)
41 return 0; 41 return 0;
42 42
43 sprintf(temp, "%d", evm_initialized); 43 sprintf(temp, "%d", (evm_initialized & ~EVM_SETUP));
44 rc = simple_read_from_buffer(buf, count, ppos, temp, strlen(temp)); 44 rc = simple_read_from_buffer(buf, count, ppos, temp, strlen(temp));
45 45
46 return rc; 46 return rc;
@@ -61,24 +61,29 @@ static ssize_t evm_read_key(struct file *filp, char __user *buf,
61static ssize_t evm_write_key(struct file *file, const char __user *buf, 61static ssize_t evm_write_key(struct file *file, const char __user *buf,
62 size_t count, loff_t *ppos) 62 size_t count, loff_t *ppos)
63{ 63{
64 char temp[80]; 64 int i, ret;
65 int i;
66 65
67 if (!capable(CAP_SYS_ADMIN) || (evm_initialized & EVM_INIT_HMAC)) 66 if (!capable(CAP_SYS_ADMIN) || (evm_initialized & EVM_SETUP))
68 return -EPERM; 67 return -EPERM;
69 68
70 if (count >= sizeof(temp) || count == 0) 69 ret = kstrtoint_from_user(buf, count, 0, &i);
71 return -EINVAL;
72
73 if (copy_from_user(temp, buf, count) != 0)
74 return -EFAULT;
75 70
76 temp[count] = '\0'; 71 if (ret)
72 return ret;
77 73
78 if ((sscanf(temp, "%d", &i) != 1) || (i != 1)) 74 /* Reject invalid values */
75 if (!i || (i & ~EVM_INIT_MASK) != 0)
79 return -EINVAL; 76 return -EINVAL;
80 77
81 evm_init_key(); 78 if (i & EVM_INIT_HMAC) {
79 ret = evm_init_key();
80 if (ret != 0)
81 return ret;
82 /* Forbid further writes after the symmetric key is loaded */
83 i |= EVM_SETUP;
84 }
85
86 evm_initialized |= i;
82 87
83 return count; 88 return count;
84} 89}
diff --git a/security/integrity/iint.c b/security/integrity/iint.c
index 6fc888ca468e..c84e05866052 100644
--- a/security/integrity/iint.c
+++ b/security/integrity/iint.c
@@ -200,55 +200,6 @@ int integrity_kernel_read(struct file *file, loff_t offset,
200} 200}
201 201
202/* 202/*
203 * integrity_read_file - read entire file content into the buffer
204 *
205 * This is function opens a file, allocates the buffer of required
206 * size, read entire file content to the buffer and closes the file
207 *
208 * It is used only by init code.
209 *
210 */
211int __init integrity_read_file(const char *path, char **data)
212{
213 struct file *file;
214 loff_t size;
215 char *buf;
216 int rc = -EINVAL;
217
218 if (!path || !*path)
219 return -EINVAL;
220
221 file = filp_open(path, O_RDONLY, 0);
222 if (IS_ERR(file)) {
223 rc = PTR_ERR(file);
224 pr_err("Unable to open file: %s (%d)", path, rc);
225 return rc;
226 }
227
228 size = i_size_read(file_inode(file));
229 if (size <= 0)
230 goto out;
231
232 buf = kmalloc(size, GFP_KERNEL);
233 if (!buf) {
234 rc = -ENOMEM;
235 goto out;
236 }
237
238 rc = integrity_kernel_read(file, 0, buf, size);
239 if (rc == size) {
240 *data = buf;
241 } else {
242 kfree(buf);
243 if (rc >= 0)
244 rc = -EIO;
245 }
246out:
247 fput(file);
248 return rc;
249}
250
251/*
252 * integrity_load_keys - load integrity keys hook 203 * integrity_load_keys - load integrity keys hook
253 * 204 *
254 * Hooks is called from init/main.c:kernel_init_freeable() 205 * Hooks is called from init/main.c:kernel_init_freeable()
diff --git a/security/integrity/ima/Makefile b/security/integrity/ima/Makefile
index 29f198bde02b..d921dc4f9eb0 100644
--- a/security/integrity/ima/Makefile
+++ b/security/integrity/ima/Makefile
@@ -1,3 +1,4 @@
1# SPDX-License-Identifier: GPL-2.0
1# 2#
2# Makefile for building Trusted Computing Group's(TCG) runtime Integrity 3# Makefile for building Trusted Computing Group's(TCG) runtime Integrity
3# Measurement Architecture(IMA). 4# Measurement Architecture(IMA).
diff --git a/security/integrity/ima/ima_api.c b/security/integrity/ima/ima_api.c
index c2edba8de35e..c7e8db0ea4c0 100644
--- a/security/integrity/ima/ima_api.c
+++ b/security/integrity/ima/ima_api.c
@@ -199,42 +199,59 @@ int ima_collect_measurement(struct integrity_iint_cache *iint,
199 struct inode *inode = file_inode(file); 199 struct inode *inode = file_inode(file);
200 const char *filename = file->f_path.dentry->d_name.name; 200 const char *filename = file->f_path.dentry->d_name.name;
201 int result = 0; 201 int result = 0;
202 int length;
203 void *tmpbuf;
204 u64 i_version;
202 struct { 205 struct {
203 struct ima_digest_data hdr; 206 struct ima_digest_data hdr;
204 char digest[IMA_MAX_DIGEST_SIZE]; 207 char digest[IMA_MAX_DIGEST_SIZE];
205 } hash; 208 } hash;
206 209
207 if (!(iint->flags & IMA_COLLECTED)) { 210 if (iint->flags & IMA_COLLECTED)
208 u64 i_version = file_inode(file)->i_version; 211 goto out;
209 212
210 if (file->f_flags & O_DIRECT) { 213 /*
211 audit_cause = "failed(directio)"; 214 * Dectecting file change is based on i_version. On filesystems
212 result = -EACCES; 215 * which do not support i_version, support is limited to an initial
213 goto out; 216 * measurement/appraisal/audit.
214 } 217 */
218 i_version = file_inode(file)->i_version;
219 hash.hdr.algo = algo;
215 220
216 hash.hdr.algo = algo; 221 /* Initialize hash digest to 0's in case of failure */
217 222 memset(&hash.digest, 0, sizeof(hash.digest));
218 result = (!buf) ? ima_calc_file_hash(file, &hash.hdr) : 223
219 ima_calc_buffer_hash(buf, size, &hash.hdr); 224 if (buf)
220 if (!result) { 225 result = ima_calc_buffer_hash(buf, size, &hash.hdr);
221 int length = sizeof(hash.hdr) + hash.hdr.length; 226 else
222 void *tmpbuf = krealloc(iint->ima_hash, length, 227 result = ima_calc_file_hash(file, &hash.hdr);
223 GFP_NOFS); 228
224 if (tmpbuf) { 229 if (result && result != -EBADF && result != -EINVAL)
225 iint->ima_hash = tmpbuf; 230 goto out;
226 memcpy(iint->ima_hash, &hash, length); 231
227 iint->version = i_version; 232 length = sizeof(hash.hdr) + hash.hdr.length;
228 iint->flags |= IMA_COLLECTED; 233 tmpbuf = krealloc(iint->ima_hash, length, GFP_NOFS);
229 } else 234 if (!tmpbuf) {
230 result = -ENOMEM; 235 result = -ENOMEM;
231 } 236 goto out;
232 } 237 }
238
239 iint->ima_hash = tmpbuf;
240 memcpy(iint->ima_hash, &hash, length);
241 iint->version = i_version;
242
243 /* Possibly temporary failure due to type of read (eg. O_DIRECT) */
244 if (!result)
245 iint->flags |= IMA_COLLECTED;
233out: 246out:
234 if (result) 247 if (result) {
248 if (file->f_flags & O_DIRECT)
249 audit_cause = "failed(directio)";
250
235 integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, 251 integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode,
236 filename, "collect_data", audit_cause, 252 filename, "collect_data", audit_cause,
237 result, 0); 253 result, 0);
254 }
238 return result; 255 return result;
239} 256}
240 257
@@ -278,7 +295,7 @@ void ima_store_measurement(struct integrity_iint_cache *iint,
278 } 295 }
279 296
280 result = ima_store_template(entry, violation, inode, filename, pcr); 297 result = ima_store_template(entry, violation, inode, filename, pcr);
281 if (!result || result == -EEXIST) { 298 if ((!result || result == -EEXIST) && !(file->f_flags & O_DIRECT)) {
282 iint->flags |= IMA_MEASURED; 299 iint->flags |= IMA_MEASURED;
283 iint->measured_pcrs |= (0x1 << pcr); 300 iint->measured_pcrs |= (0x1 << pcr);
284 } 301 }
diff --git a/security/integrity/ima/ima_appraise.c b/security/integrity/ima/ima_appraise.c
index 809ba70fbbbf..65fbcf3c32c7 100644
--- a/security/integrity/ima/ima_appraise.c
+++ b/security/integrity/ima/ima_appraise.c
@@ -40,7 +40,7 @@ __setup("ima_appraise=", default_appraise_setup);
40 */ 40 */
41bool is_ima_appraise_enabled(void) 41bool is_ima_appraise_enabled(void)
42{ 42{
43 return (ima_appraise & IMA_APPRAISE_ENFORCE) ? 1 : 0; 43 return ima_appraise & IMA_APPRAISE_ENFORCE;
44} 44}
45 45
46/* 46/*
@@ -320,6 +320,9 @@ void ima_update_xattr(struct integrity_iint_cache *iint, struct file *file)
320 if (iint->flags & IMA_DIGSIG) 320 if (iint->flags & IMA_DIGSIG)
321 return; 321 return;
322 322
323 if (iint->ima_file_status != INTEGRITY_PASS)
324 return;
325
323 rc = ima_collect_measurement(iint, file, NULL, 0, ima_hash_algo); 326 rc = ima_collect_measurement(iint, file, NULL, 0, ima_hash_algo);
324 if (rc < 0) 327 if (rc < 0)
325 return; 328 return;
@@ -405,7 +408,7 @@ int ima_inode_setxattr(struct dentry *dentry, const char *xattr_name,
405 if (!xattr_value_len || (xvalue->type >= IMA_XATTR_LAST)) 408 if (!xattr_value_len || (xvalue->type >= IMA_XATTR_LAST))
406 return -EINVAL; 409 return -EINVAL;
407 ima_reset_appraise_flags(d_backing_inode(dentry), 410 ima_reset_appraise_flags(d_backing_inode(dentry),
408 (xvalue->type == EVM_IMA_XATTR_DIGSIG) ? 1 : 0); 411 xvalue->type == EVM_IMA_XATTR_DIGSIG);
409 result = 0; 412 result = 0;
410 } 413 }
411 return result; 414 return result;
diff --git a/security/integrity/ima/ima_crypto.c b/security/integrity/ima/ima_crypto.c
index 802d5d20f36f..9057b163c378 100644
--- a/security/integrity/ima/ima_crypto.c
+++ b/security/integrity/ima/ima_crypto.c
@@ -27,11 +27,6 @@
27 27
28#include "ima.h" 28#include "ima.h"
29 29
30struct ahash_completion {
31 struct completion completion;
32 int err;
33};
34
35/* minimum file size for ahash use */ 30/* minimum file size for ahash use */
36static unsigned long ima_ahash_minsize; 31static unsigned long ima_ahash_minsize;
37module_param_named(ahash_minsize, ima_ahash_minsize, ulong, 0644); 32module_param_named(ahash_minsize, ima_ahash_minsize, ulong, 0644);
@@ -196,30 +191,13 @@ static void ima_free_atfm(struct crypto_ahash *tfm)
196 crypto_free_ahash(tfm); 191 crypto_free_ahash(tfm);
197} 192}
198 193
199static void ahash_complete(struct crypto_async_request *req, int err) 194static inline int ahash_wait(int err, struct crypto_wait *wait)
200{ 195{
201 struct ahash_completion *res = req->data;
202 196
203 if (err == -EINPROGRESS) 197 err = crypto_wait_req(err, wait);
204 return;
205 res->err = err;
206 complete(&res->completion);
207}
208 198
209static int ahash_wait(int err, struct ahash_completion *res) 199 if (err)
210{
211 switch (err) {
212 case 0:
213 break;
214 case -EINPROGRESS:
215 case -EBUSY:
216 wait_for_completion(&res->completion);
217 reinit_completion(&res->completion);
218 err = res->err;
219 /* fall through */
220 default:
221 pr_crit_ratelimited("ahash calculation failed: err: %d\n", err); 200 pr_crit_ratelimited("ahash calculation failed: err: %d\n", err);
222 }
223 201
224 return err; 202 return err;
225} 203}
@@ -233,7 +211,7 @@ static int ima_calc_file_hash_atfm(struct file *file,
233 int rc, read = 0, rbuf_len, active = 0, ahash_rc = 0; 211 int rc, read = 0, rbuf_len, active = 0, ahash_rc = 0;
234 struct ahash_request *req; 212 struct ahash_request *req;
235 struct scatterlist sg[1]; 213 struct scatterlist sg[1];
236 struct ahash_completion res; 214 struct crypto_wait wait;
237 size_t rbuf_size[2]; 215 size_t rbuf_size[2];
238 216
239 hash->length = crypto_ahash_digestsize(tfm); 217 hash->length = crypto_ahash_digestsize(tfm);
@@ -242,12 +220,12 @@ static int ima_calc_file_hash_atfm(struct file *file,
242 if (!req) 220 if (!req)
243 return -ENOMEM; 221 return -ENOMEM;
244 222
245 init_completion(&res.completion); 223 crypto_init_wait(&wait);
246 ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG | 224 ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
247 CRYPTO_TFM_REQ_MAY_SLEEP, 225 CRYPTO_TFM_REQ_MAY_SLEEP,
248 ahash_complete, &res); 226 crypto_req_done, &wait);
249 227
250 rc = ahash_wait(crypto_ahash_init(req), &res); 228 rc = ahash_wait(crypto_ahash_init(req), &wait);
251 if (rc) 229 if (rc)
252 goto out1; 230 goto out1;
253 231
@@ -288,7 +266,7 @@ static int ima_calc_file_hash_atfm(struct file *file,
288 * read/request, wait for the completion of the 266 * read/request, wait for the completion of the
289 * previous ahash_update() request. 267 * previous ahash_update() request.
290 */ 268 */
291 rc = ahash_wait(ahash_rc, &res); 269 rc = ahash_wait(ahash_rc, &wait);
292 if (rc) 270 if (rc)
293 goto out3; 271 goto out3;
294 } 272 }
@@ -304,7 +282,7 @@ static int ima_calc_file_hash_atfm(struct file *file,
304 * read/request, wait for the completion of the 282 * read/request, wait for the completion of the
305 * previous ahash_update() request. 283 * previous ahash_update() request.
306 */ 284 */
307 rc = ahash_wait(ahash_rc, &res); 285 rc = ahash_wait(ahash_rc, &wait);
308 if (rc) 286 if (rc)
309 goto out3; 287 goto out3;
310 } 288 }
@@ -318,7 +296,7 @@ static int ima_calc_file_hash_atfm(struct file *file,
318 active = !active; /* swap buffers, if we use two */ 296 active = !active; /* swap buffers, if we use two */
319 } 297 }
320 /* wait for the last update request to complete */ 298 /* wait for the last update request to complete */
321 rc = ahash_wait(ahash_rc, &res); 299 rc = ahash_wait(ahash_rc, &wait);
322out3: 300out3:
323 if (read) 301 if (read)
324 file->f_mode &= ~FMODE_READ; 302 file->f_mode &= ~FMODE_READ;
@@ -327,7 +305,7 @@ out3:
327out2: 305out2:
328 if (!rc) { 306 if (!rc) {
329 ahash_request_set_crypt(req, NULL, hash->digest, 0); 307 ahash_request_set_crypt(req, NULL, hash->digest, 0);
330 rc = ahash_wait(crypto_ahash_final(req), &res); 308 rc = ahash_wait(crypto_ahash_final(req), &wait);
331 } 309 }
332out1: 310out1:
333 ahash_request_free(req); 311 ahash_request_free(req);
@@ -441,6 +419,16 @@ int ima_calc_file_hash(struct file *file, struct ima_digest_data *hash)
441 loff_t i_size; 419 loff_t i_size;
442 int rc; 420 int rc;
443 421
422 /*
423 * For consistency, fail file's opened with the O_DIRECT flag on
424 * filesystems mounted with/without DAX option.
425 */
426 if (file->f_flags & O_DIRECT) {
427 hash->length = hash_digest_size[ima_hash_algo];
428 hash->algo = ima_hash_algo;
429 return -EINVAL;
430 }
431
444 i_size = i_size_read(file_inode(file)); 432 i_size = i_size_read(file_inode(file));
445 433
446 if (ima_ahash_minsize && i_size >= ima_ahash_minsize) { 434 if (ima_ahash_minsize && i_size >= ima_ahash_minsize) {
@@ -527,7 +515,7 @@ static int calc_buffer_ahash_atfm(const void *buf, loff_t len,
527{ 515{
528 struct ahash_request *req; 516 struct ahash_request *req;
529 struct scatterlist sg; 517 struct scatterlist sg;
530 struct ahash_completion res; 518 struct crypto_wait wait;
531 int rc, ahash_rc = 0; 519 int rc, ahash_rc = 0;
532 520
533 hash->length = crypto_ahash_digestsize(tfm); 521 hash->length = crypto_ahash_digestsize(tfm);
@@ -536,12 +524,12 @@ static int calc_buffer_ahash_atfm(const void *buf, loff_t len,
536 if (!req) 524 if (!req)
537 return -ENOMEM; 525 return -ENOMEM;
538 526
539 init_completion(&res.completion); 527 crypto_init_wait(&wait);
540 ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG | 528 ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
541 CRYPTO_TFM_REQ_MAY_SLEEP, 529 CRYPTO_TFM_REQ_MAY_SLEEP,
542 ahash_complete, &res); 530 crypto_req_done, &wait);
543 531
544 rc = ahash_wait(crypto_ahash_init(req), &res); 532 rc = ahash_wait(crypto_ahash_init(req), &wait);
545 if (rc) 533 if (rc)
546 goto out; 534 goto out;
547 535
@@ -551,10 +539,10 @@ static int calc_buffer_ahash_atfm(const void *buf, loff_t len,
551 ahash_rc = crypto_ahash_update(req); 539 ahash_rc = crypto_ahash_update(req);
552 540
553 /* wait for the update request to complete */ 541 /* wait for the update request to complete */
554 rc = ahash_wait(ahash_rc, &res); 542 rc = ahash_wait(ahash_rc, &wait);
555 if (!rc) { 543 if (!rc) {
556 ahash_request_set_crypt(req, NULL, hash->digest, 0); 544 ahash_request_set_crypt(req, NULL, hash->digest, 0);
557 rc = ahash_wait(crypto_ahash_final(req), &res); 545 rc = ahash_wait(crypto_ahash_final(req), &wait);
558 } 546 }
559out: 547out:
560 ahash_request_free(req); 548 ahash_request_free(req);
diff --git a/security/integrity/ima/ima_fs.c b/security/integrity/ima/ima_fs.c
index ad491c51e833..fa540c0469da 100644
--- a/security/integrity/ima/ima_fs.c
+++ b/security/integrity/ima/ima_fs.c
@@ -32,7 +32,7 @@ bool ima_canonical_fmt;
32static int __init default_canonical_fmt_setup(char *str) 32static int __init default_canonical_fmt_setup(char *str)
33{ 33{
34#ifdef __BIG_ENDIAN 34#ifdef __BIG_ENDIAN
35 ima_canonical_fmt = 1; 35 ima_canonical_fmt = true;
36#endif 36#endif
37 return 1; 37 return 1;
38} 38}
@@ -429,10 +429,10 @@ static int ima_release_policy(struct inode *inode, struct file *file)
429 } 429 }
430 430
431 ima_update_policy(); 431 ima_update_policy();
432#ifndef CONFIG_IMA_WRITE_POLICY 432#if !defined(CONFIG_IMA_WRITE_POLICY) && !defined(CONFIG_IMA_READ_POLICY)
433 securityfs_remove(ima_policy); 433 securityfs_remove(ima_policy);
434 ima_policy = NULL; 434 ima_policy = NULL;
435#else 435#elif defined(CONFIG_IMA_WRITE_POLICY)
436 clear_bit(IMA_FS_BUSY, &ima_fs_flags); 436 clear_bit(IMA_FS_BUSY, &ima_fs_flags);
437#endif 437#endif
438 return 0; 438 return 0;
diff --git a/security/integrity/ima/ima_main.c b/security/integrity/ima/ima_main.c
index 2aebb7984437..770654694efc 100644
--- a/security/integrity/ima/ima_main.c
+++ b/security/integrity/ima/ima_main.c
@@ -51,6 +51,8 @@ static int __init hash_setup(char *str)
51 ima_hash_algo = HASH_ALGO_SHA1; 51 ima_hash_algo = HASH_ALGO_SHA1;
52 else if (strncmp(str, "md5", 3) == 0) 52 else if (strncmp(str, "md5", 3) == 0)
53 ima_hash_algo = HASH_ALGO_MD5; 53 ima_hash_algo = HASH_ALGO_MD5;
54 else
55 return 1;
54 goto out; 56 goto out;
55 } 57 }
56 58
@@ -60,6 +62,8 @@ static int __init hash_setup(char *str)
60 break; 62 break;
61 } 63 }
62 } 64 }
65 if (i == HASH_ALGO__LAST)
66 return 1;
63out: 67out:
64 hash_setup_done = 1; 68 hash_setup_done = 1;
65 return 1; 69 return 1;
@@ -235,11 +239,8 @@ static int process_measurement(struct file *file, char *buf, loff_t size,
235 hash_algo = ima_get_hash_algo(xattr_value, xattr_len); 239 hash_algo = ima_get_hash_algo(xattr_value, xattr_len);
236 240
237 rc = ima_collect_measurement(iint, file, buf, size, hash_algo); 241 rc = ima_collect_measurement(iint, file, buf, size, hash_algo);
238 if (rc != 0) { 242 if (rc != 0 && rc != -EBADF && rc != -EINVAL)
239 if (file->f_flags & O_DIRECT)
240 rc = (iint->flags & IMA_PERMIT_DIRECTIO) ? 0 : -EACCES;
241 goto out_digsig; 243 goto out_digsig;
242 }
243 244
244 if (!pathbuf) /* ima_rdwr_violation possibly pre-fetched */ 245 if (!pathbuf) /* ima_rdwr_violation possibly pre-fetched */
245 pathname = ima_d_path(&file->f_path, &pathbuf, filename); 246 pathname = ima_d_path(&file->f_path, &pathbuf, filename);
@@ -247,12 +248,14 @@ static int process_measurement(struct file *file, char *buf, loff_t size,
247 if (action & IMA_MEASURE) 248 if (action & IMA_MEASURE)
248 ima_store_measurement(iint, file, pathname, 249 ima_store_measurement(iint, file, pathname,
249 xattr_value, xattr_len, pcr); 250 xattr_value, xattr_len, pcr);
250 if (action & IMA_APPRAISE_SUBMASK) 251 if (rc == 0 && (action & IMA_APPRAISE_SUBMASK))
251 rc = ima_appraise_measurement(func, iint, file, pathname, 252 rc = ima_appraise_measurement(func, iint, file, pathname,
252 xattr_value, xattr_len, opened); 253 xattr_value, xattr_len, opened);
253 if (action & IMA_AUDIT) 254 if (action & IMA_AUDIT)
254 ima_audit_measurement(iint, pathname); 255 ima_audit_measurement(iint, pathname);
255 256
257 if ((file->f_flags & O_DIRECT) && (iint->flags & IMA_PERMIT_DIRECTIO))
258 rc = 0;
256out_digsig: 259out_digsig:
257 if ((mask & MAY_WRITE) && (iint->flags & IMA_DIGSIG) && 260 if ((mask & MAY_WRITE) && (iint->flags & IMA_DIGSIG) &&
258 !(iint->flags & IMA_NEW_FILE)) 261 !(iint->flags & IMA_NEW_FILE))
@@ -359,12 +362,12 @@ void ima_post_path_mknod(struct dentry *dentry)
359 */ 362 */
360int ima_read_file(struct file *file, enum kernel_read_file_id read_id) 363int ima_read_file(struct file *file, enum kernel_read_file_id read_id)
361{ 364{
365 bool sig_enforce = is_module_sig_enforced();
366
362 if (!file && read_id == READING_MODULE) { 367 if (!file && read_id == READING_MODULE) {
363#ifndef CONFIG_MODULE_SIG_FORCE 368 if (!sig_enforce && (ima_appraise & IMA_APPRAISE_MODULES) &&
364 if ((ima_appraise & IMA_APPRAISE_MODULES) &&
365 (ima_appraise & IMA_APPRAISE_ENFORCE)) 369 (ima_appraise & IMA_APPRAISE_ENFORCE))
366 return -EACCES; /* INTEGRITY_UNKNOWN */ 370 return -EACCES; /* INTEGRITY_UNKNOWN */
367#endif
368 return 0; /* We rely on module signature checking */ 371 return 0; /* We rely on module signature checking */
369 } 372 }
370 return 0; 373 return 0;
@@ -406,6 +409,10 @@ int ima_post_read_file(struct file *file, void *buf, loff_t size,
406 if (!file && read_id == READING_MODULE) /* MODULE_SIG_FORCE enabled */ 409 if (!file && read_id == READING_MODULE) /* MODULE_SIG_FORCE enabled */
407 return 0; 410 return 0;
408 411
412 /* permit signed certs */
413 if (!file && read_id == READING_X509_CERTIFICATE)
414 return 0;
415
409 if (!file || !buf || size == 0) { /* should never happen */ 416 if (!file || !buf || size == 0) { /* should never happen */
410 if (ima_appraise & IMA_APPRAISE_ENFORCE) 417 if (ima_appraise & IMA_APPRAISE_ENFORCE)
411 return -EACCES; 418 return -EACCES;
diff --git a/security/integrity/ima/ima_policy.c b/security/integrity/ima/ima_policy.c
index 95209a5f8595..ee4613fa5840 100644
--- a/security/integrity/ima/ima_policy.c
+++ b/security/integrity/ima/ima_policy.c
@@ -196,9 +196,9 @@ static int __init policy_setup(char *str)
196 if ((strcmp(p, "tcb") == 0) && !ima_policy) 196 if ((strcmp(p, "tcb") == 0) && !ima_policy)
197 ima_policy = DEFAULT_TCB; 197 ima_policy = DEFAULT_TCB;
198 else if (strcmp(p, "appraise_tcb") == 0) 198 else if (strcmp(p, "appraise_tcb") == 0)
199 ima_use_appraise_tcb = 1; 199 ima_use_appraise_tcb = true;
200 else if (strcmp(p, "secure_boot") == 0) 200 else if (strcmp(p, "secure_boot") == 0)
201 ima_use_secure_boot = 1; 201 ima_use_secure_boot = true;
202 } 202 }
203 203
204 return 1; 204 return 1;
@@ -207,7 +207,7 @@ __setup("ima_policy=", policy_setup);
207 207
208static int __init default_appraise_policy_setup(char *str) 208static int __init default_appraise_policy_setup(char *str)
209{ 209{
210 ima_use_appraise_tcb = 1; 210 ima_use_appraise_tcb = true;
211 return 1; 211 return 1;
212} 212}
213__setup("ima_appraise_tcb", default_appraise_policy_setup); 213__setup("ima_appraise_tcb", default_appraise_policy_setup);
diff --git a/security/integrity/integrity.h b/security/integrity/integrity.h
index a53e7e4ab06c..e1bf040fb110 100644
--- a/security/integrity/integrity.h
+++ b/security/integrity/integrity.h
@@ -120,8 +120,6 @@ struct integrity_iint_cache *integrity_iint_find(struct inode *inode);
120int integrity_kernel_read(struct file *file, loff_t offset, 120int integrity_kernel_read(struct file *file, loff_t offset,
121 void *addr, unsigned long count); 121 void *addr, unsigned long count);
122 122
123int __init integrity_read_file(const char *path, char **data);
124
125#define INTEGRITY_KEYRING_EVM 0 123#define INTEGRITY_KEYRING_EVM 0
126#define INTEGRITY_KEYRING_IMA 1 124#define INTEGRITY_KEYRING_IMA 1
127#define INTEGRITY_KEYRING_MODULE 2 125#define INTEGRITY_KEYRING_MODULE 2
diff --git a/security/keys/Kconfig b/security/keys/Kconfig
index a7a23b5541f8..6462e6654ccf 100644
--- a/security/keys/Kconfig
+++ b/security/keys/Kconfig
@@ -45,10 +45,9 @@ config BIG_KEYS
45 bool "Large payload keys" 45 bool "Large payload keys"
46 depends on KEYS 46 depends on KEYS
47 depends on TMPFS 47 depends on TMPFS
48 depends on (CRYPTO_ANSI_CPRNG = y || CRYPTO_DRBG = y) 48 select CRYPTO
49 select CRYPTO_AES 49 select CRYPTO_AES
50 select CRYPTO_ECB 50 select CRYPTO_GCM
51 select CRYPTO_RNG
52 help 51 help
53 This option provides support for holding large keys within the kernel 52 This option provides support for holding large keys within the kernel
54 (for example Kerberos ticket caches). The data may be stored out to 53 (for example Kerberos ticket caches). The data may be stored out to
diff --git a/security/keys/Makefile b/security/keys/Makefile
index 57dff0c15809..ef1581b337a3 100644
--- a/security/keys/Makefile
+++ b/security/keys/Makefile
@@ -1,3 +1,4 @@
1# SPDX-License-Identifier: GPL-2.0
1# 2#
2# Makefile for key management 3# Makefile for key management
3# 4#
diff --git a/security/keys/big_key.c b/security/keys/big_key.c
index 6acb00f6f22c..929e14978c42 100644
--- a/security/keys/big_key.c
+++ b/security/keys/big_key.c
@@ -1,5 +1,6 @@
1/* Large capacity key type 1/* Large capacity key type
2 * 2 *
3 * Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
3 * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved. 4 * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
4 * Written by David Howells (dhowells@redhat.com) 5 * Written by David Howells (dhowells@redhat.com)
5 * 6 *
@@ -16,10 +17,10 @@
16#include <linux/shmem_fs.h> 17#include <linux/shmem_fs.h>
17#include <linux/err.h> 18#include <linux/err.h>
18#include <linux/scatterlist.h> 19#include <linux/scatterlist.h>
20#include <linux/random.h>
19#include <keys/user-type.h> 21#include <keys/user-type.h>
20#include <keys/big_key-type.h> 22#include <keys/big_key-type.h>
21#include <crypto/rng.h> 23#include <crypto/aead.h>
22#include <crypto/skcipher.h>
23 24
24/* 25/*
25 * Layout of key payload words. 26 * Layout of key payload words.
@@ -49,7 +50,12 @@ enum big_key_op {
49/* 50/*
50 * Key size for big_key data encryption 51 * Key size for big_key data encryption
51 */ 52 */
52#define ENC_KEY_SIZE 16 53#define ENC_KEY_SIZE 32
54
55/*
56 * Authentication tag length
57 */
58#define ENC_AUTHTAG_SIZE 16
53 59
54/* 60/*
55 * big_key defined keys take an arbitrary string as the description and an 61 * big_key defined keys take an arbitrary string as the description and an
@@ -64,57 +70,62 @@ struct key_type key_type_big_key = {
64 .destroy = big_key_destroy, 70 .destroy = big_key_destroy,
65 .describe = big_key_describe, 71 .describe = big_key_describe,
66 .read = big_key_read, 72 .read = big_key_read,
73 /* no ->update(); don't add it without changing big_key_crypt() nonce */
67}; 74};
68 75
69/* 76/*
70 * Crypto names for big_key data encryption 77 * Crypto names for big_key data authenticated encryption
71 */ 78 */
72static const char big_key_rng_name[] = "stdrng"; 79static const char big_key_alg_name[] = "gcm(aes)";
73static const char big_key_alg_name[] = "ecb(aes)";
74 80
75/* 81/*
76 * Crypto algorithms for big_key data encryption 82 * Crypto algorithms for big_key data authenticated encryption
77 */ 83 */
78static struct crypto_rng *big_key_rng; 84static struct crypto_aead *big_key_aead;
79static struct crypto_skcipher *big_key_skcipher;
80 85
81/* 86/*
82 * Generate random key to encrypt big_key data 87 * Since changing the key affects the entire object, we need a mutex.
83 */ 88 */
84static inline int big_key_gen_enckey(u8 *key) 89static DEFINE_MUTEX(big_key_aead_lock);
85{
86 return crypto_rng_get_bytes(big_key_rng, key, ENC_KEY_SIZE);
87}
88 90
89/* 91/*
90 * Encrypt/decrypt big_key data 92 * Encrypt/decrypt big_key data
91 */ 93 */
92static int big_key_crypt(enum big_key_op op, u8 *data, size_t datalen, u8 *key) 94static int big_key_crypt(enum big_key_op op, u8 *data, size_t datalen, u8 *key)
93{ 95{
94 int ret = -EINVAL; 96 int ret;
95 struct scatterlist sgio; 97 struct scatterlist sgio;
96 SKCIPHER_REQUEST_ON_STACK(req, big_key_skcipher); 98 struct aead_request *aead_req;
97 99 /* We always use a zero nonce. The reason we can get away with this is
98 if (crypto_skcipher_setkey(big_key_skcipher, key, ENC_KEY_SIZE)) { 100 * because we're using a different randomly generated key for every
101 * different encryption. Notably, too, key_type_big_key doesn't define
102 * an .update function, so there's no chance we'll wind up reusing the
103 * key to encrypt updated data. Simply put: one key, one encryption.
104 */
105 u8 zero_nonce[crypto_aead_ivsize(big_key_aead)];
106
107 aead_req = aead_request_alloc(big_key_aead, GFP_KERNEL);
108 if (!aead_req)
109 return -ENOMEM;
110
111 memset(zero_nonce, 0, sizeof(zero_nonce));
112 sg_init_one(&sgio, data, datalen + (op == BIG_KEY_ENC ? ENC_AUTHTAG_SIZE : 0));
113 aead_request_set_crypt(aead_req, &sgio, &sgio, datalen, zero_nonce);
114 aead_request_set_callback(aead_req, CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL);
115 aead_request_set_ad(aead_req, 0);
116
117 mutex_lock(&big_key_aead_lock);
118 if (crypto_aead_setkey(big_key_aead, key, ENC_KEY_SIZE)) {
99 ret = -EAGAIN; 119 ret = -EAGAIN;
100 goto error; 120 goto error;
101 } 121 }
102
103 skcipher_request_set_tfm(req, big_key_skcipher);
104 skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP,
105 NULL, NULL);
106
107 sg_init_one(&sgio, data, datalen);
108 skcipher_request_set_crypt(req, &sgio, &sgio, datalen, NULL);
109
110 if (op == BIG_KEY_ENC) 122 if (op == BIG_KEY_ENC)
111 ret = crypto_skcipher_encrypt(req); 123 ret = crypto_aead_encrypt(aead_req);
112 else 124 else
113 ret = crypto_skcipher_decrypt(req); 125 ret = crypto_aead_decrypt(aead_req);
114
115 skcipher_request_zero(req);
116
117error: 126error:
127 mutex_unlock(&big_key_aead_lock);
128 aead_request_free(aead_req);
118 return ret; 129 return ret;
119} 130}
120 131
@@ -146,16 +157,13 @@ int big_key_preparse(struct key_preparsed_payload *prep)
146 * 157 *
147 * File content is stored encrypted with randomly generated key. 158 * File content is stored encrypted with randomly generated key.
148 */ 159 */
149 size_t enclen = ALIGN(datalen, crypto_skcipher_blocksize(big_key_skcipher)); 160 size_t enclen = datalen + ENC_AUTHTAG_SIZE;
150 loff_t pos = 0; 161 loff_t pos = 0;
151 162
152 /* prepare aligned data to encrypt */
153 data = kmalloc(enclen, GFP_KERNEL); 163 data = kmalloc(enclen, GFP_KERNEL);
154 if (!data) 164 if (!data)
155 return -ENOMEM; 165 return -ENOMEM;
156
157 memcpy(data, prep->data, datalen); 166 memcpy(data, prep->data, datalen);
158 memset(data + datalen, 0x00, enclen - datalen);
159 167
160 /* generate random key */ 168 /* generate random key */
161 enckey = kmalloc(ENC_KEY_SIZE, GFP_KERNEL); 169 enckey = kmalloc(ENC_KEY_SIZE, GFP_KERNEL);
@@ -163,13 +171,12 @@ int big_key_preparse(struct key_preparsed_payload *prep)
163 ret = -ENOMEM; 171 ret = -ENOMEM;
164 goto error; 172 goto error;
165 } 173 }
166 174 ret = get_random_bytes_wait(enckey, ENC_KEY_SIZE);
167 ret = big_key_gen_enckey(enckey); 175 if (unlikely(ret))
168 if (ret)
169 goto err_enckey; 176 goto err_enckey;
170 177
171 /* encrypt aligned data */ 178 /* encrypt aligned data */
172 ret = big_key_crypt(BIG_KEY_ENC, data, enclen, enckey); 179 ret = big_key_crypt(BIG_KEY_ENC, data, datalen, enckey);
173 if (ret) 180 if (ret)
174 goto err_enckey; 181 goto err_enckey;
175 182
@@ -195,7 +202,7 @@ int big_key_preparse(struct key_preparsed_payload *prep)
195 *path = file->f_path; 202 *path = file->f_path;
196 path_get(path); 203 path_get(path);
197 fput(file); 204 fput(file);
198 kfree(data); 205 kzfree(data);
199 } else { 206 } else {
200 /* Just store the data in a buffer */ 207 /* Just store the data in a buffer */
201 void *data = kmalloc(datalen, GFP_KERNEL); 208 void *data = kmalloc(datalen, GFP_KERNEL);
@@ -211,9 +218,9 @@ int big_key_preparse(struct key_preparsed_payload *prep)
211err_fput: 218err_fput:
212 fput(file); 219 fput(file);
213err_enckey: 220err_enckey:
214 kfree(enckey); 221 kzfree(enckey);
215error: 222error:
216 kfree(data); 223 kzfree(data);
217 return ret; 224 return ret;
218} 225}
219 226
@@ -227,7 +234,7 @@ void big_key_free_preparse(struct key_preparsed_payload *prep)
227 234
228 path_put(path); 235 path_put(path);
229 } 236 }
230 kfree(prep->payload.data[big_key_data]); 237 kzfree(prep->payload.data[big_key_data]);
231} 238}
232 239
233/* 240/*
@@ -240,7 +247,7 @@ void big_key_revoke(struct key *key)
240 247
241 /* clear the quota */ 248 /* clear the quota */
242 key_payload_reserve(key, 0); 249 key_payload_reserve(key, 0);
243 if (key_is_instantiated(key) && 250 if (key_is_positive(key) &&
244 (size_t)key->payload.data[big_key_len] > BIG_KEY_FILE_THRESHOLD) 251 (size_t)key->payload.data[big_key_len] > BIG_KEY_FILE_THRESHOLD)
245 vfs_truncate(path, 0); 252 vfs_truncate(path, 0);
246} 253}
@@ -259,7 +266,7 @@ void big_key_destroy(struct key *key)
259 path->mnt = NULL; 266 path->mnt = NULL;
260 path->dentry = NULL; 267 path->dentry = NULL;
261 } 268 }
262 kfree(key->payload.data[big_key_data]); 269 kzfree(key->payload.data[big_key_data]);
263 key->payload.data[big_key_data] = NULL; 270 key->payload.data[big_key_data] = NULL;
264} 271}
265 272
@@ -272,7 +279,7 @@ void big_key_describe(const struct key *key, struct seq_file *m)
272 279
273 seq_puts(m, key->description); 280 seq_puts(m, key->description);
274 281
275 if (key_is_instantiated(key)) 282 if (key_is_positive(key))
276 seq_printf(m, ": %zu [%s]", 283 seq_printf(m, ": %zu [%s]",
277 datalen, 284 datalen,
278 datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff"); 285 datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff");
@@ -295,7 +302,7 @@ long big_key_read(const struct key *key, char __user *buffer, size_t buflen)
295 struct file *file; 302 struct file *file;
296 u8 *data; 303 u8 *data;
297 u8 *enckey = (u8 *)key->payload.data[big_key_data]; 304 u8 *enckey = (u8 *)key->payload.data[big_key_data];
298 size_t enclen = ALIGN(datalen, crypto_skcipher_blocksize(big_key_skcipher)); 305 size_t enclen = datalen + ENC_AUTHTAG_SIZE;
299 loff_t pos = 0; 306 loff_t pos = 0;
300 307
301 data = kmalloc(enclen, GFP_KERNEL); 308 data = kmalloc(enclen, GFP_KERNEL);
@@ -328,7 +335,7 @@ long big_key_read(const struct key *key, char __user *buffer, size_t buflen)
328err_fput: 335err_fput:
329 fput(file); 336 fput(file);
330error: 337error:
331 kfree(data); 338 kzfree(data);
332 } else { 339 } else {
333 ret = datalen; 340 ret = datalen;
334 if (copy_to_user(buffer, key->payload.data[big_key_data], 341 if (copy_to_user(buffer, key->payload.data[big_key_data],
@@ -344,47 +351,31 @@ error:
344 */ 351 */
345static int __init big_key_init(void) 352static int __init big_key_init(void)
346{ 353{
347 struct crypto_skcipher *cipher;
348 struct crypto_rng *rng;
349 int ret; 354 int ret;
350 355
351 rng = crypto_alloc_rng(big_key_rng_name, 0, 0);
352 if (IS_ERR(rng)) {
353 pr_err("Can't alloc rng: %ld\n", PTR_ERR(rng));
354 return PTR_ERR(rng);
355 }
356
357 big_key_rng = rng;
358
359 /* seed RNG */
360 ret = crypto_rng_reset(rng, NULL, crypto_rng_seedsize(rng));
361 if (ret) {
362 pr_err("Can't reset rng: %d\n", ret);
363 goto error_rng;
364 }
365
366 /* init block cipher */ 356 /* init block cipher */
367 cipher = crypto_alloc_skcipher(big_key_alg_name, 0, CRYPTO_ALG_ASYNC); 357 big_key_aead = crypto_alloc_aead(big_key_alg_name, 0, CRYPTO_ALG_ASYNC);
368 if (IS_ERR(cipher)) { 358 if (IS_ERR(big_key_aead)) {
369 ret = PTR_ERR(cipher); 359 ret = PTR_ERR(big_key_aead);
370 pr_err("Can't alloc crypto: %d\n", ret); 360 pr_err("Can't alloc crypto: %d\n", ret);
371 goto error_rng; 361 return ret;
362 }
363 ret = crypto_aead_setauthsize(big_key_aead, ENC_AUTHTAG_SIZE);
364 if (ret < 0) {
365 pr_err("Can't set crypto auth tag len: %d\n", ret);
366 goto free_aead;
372 } 367 }
373
374 big_key_skcipher = cipher;
375 368
376 ret = register_key_type(&key_type_big_key); 369 ret = register_key_type(&key_type_big_key);
377 if (ret < 0) { 370 if (ret < 0) {
378 pr_err("Can't register type: %d\n", ret); 371 pr_err("Can't register type: %d\n", ret);
379 goto error_cipher; 372 goto free_aead;
380 } 373 }
381 374
382 return 0; 375 return 0;
383 376
384error_cipher: 377free_aead:
385 crypto_free_skcipher(big_key_skcipher); 378 crypto_free_aead(big_key_aead);
386error_rng:
387 crypto_free_rng(big_key_rng);
388 return ret; 379 return ret;
389} 380}
390 381
diff --git a/security/keys/encrypted-keys/Makefile b/security/keys/encrypted-keys/Makefile
index d6f8433250a5..7a44dce6f69d 100644
--- a/security/keys/encrypted-keys/Makefile
+++ b/security/keys/encrypted-keys/Makefile
@@ -1,3 +1,4 @@
1# SPDX-License-Identifier: GPL-2.0
1# 2#
2# Makefile for encrypted keys 3# Makefile for encrypted keys
3# 4#
diff --git a/security/keys/encrypted-keys/encrypted.c b/security/keys/encrypted-keys/encrypted.c
index 69855ba0d3b3..d92cbf9687c3 100644
--- a/security/keys/encrypted-keys/encrypted.c
+++ b/security/keys/encrypted-keys/encrypted.c
@@ -309,6 +309,13 @@ static struct key *request_user_key(const char *master_desc, const u8 **master_k
309 309
310 down_read(&ukey->sem); 310 down_read(&ukey->sem);
311 upayload = user_key_payload_locked(ukey); 311 upayload = user_key_payload_locked(ukey);
312 if (!upayload) {
313 /* key was revoked before we acquired its semaphore */
314 up_read(&ukey->sem);
315 key_put(ukey);
316 ukey = ERR_PTR(-EKEYREVOKED);
317 goto error;
318 }
312 *master_key = upayload->data; 319 *master_key = upayload->data;
313 *master_keylen = upayload->datalen; 320 *master_keylen = upayload->datalen;
314error: 321error:
@@ -847,7 +854,7 @@ static int encrypted_update(struct key *key, struct key_preparsed_payload *prep)
847 size_t datalen = prep->datalen; 854 size_t datalen = prep->datalen;
848 int ret = 0; 855 int ret = 0;
849 856
850 if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) 857 if (key_is_negative(key))
851 return -ENOKEY; 858 return -ENOKEY;
852 if (datalen <= 0 || datalen > 32767 || !prep->data) 859 if (datalen <= 0 || datalen > 32767 || !prep->data)
853 return -EINVAL; 860 return -EINVAL;
diff --git a/security/keys/encrypted-keys/encrypted.h b/security/keys/encrypted-keys/encrypted.h
index 47802c0de735..1809995db452 100644
--- a/security/keys/encrypted-keys/encrypted.h
+++ b/security/keys/encrypted-keys/encrypted.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1#ifndef __ENCRYPTED_KEY_H 2#ifndef __ENCRYPTED_KEY_H
2#define __ENCRYPTED_KEY_H 3#define __ENCRYPTED_KEY_H
3 4
diff --git a/security/keys/gc.c b/security/keys/gc.c
index 87cb260e4890..7207e6094dc1 100644
--- a/security/keys/gc.c
+++ b/security/keys/gc.c
@@ -29,10 +29,10 @@ DECLARE_WORK(key_gc_work, key_garbage_collector);
29/* 29/*
30 * Reaper for links from keyrings to dead keys. 30 * Reaper for links from keyrings to dead keys.
31 */ 31 */
32static void key_gc_timer_func(unsigned long); 32static void key_gc_timer_func(struct timer_list *);
33static DEFINE_TIMER(key_gc_timer, key_gc_timer_func, 0, 0); 33static DEFINE_TIMER(key_gc_timer, key_gc_timer_func);
34 34
35static time_t key_gc_next_run = LONG_MAX; 35static time64_t key_gc_next_run = TIME64_MAX;
36static struct key_type *key_gc_dead_keytype; 36static struct key_type *key_gc_dead_keytype;
37 37
38static unsigned long key_gc_flags; 38static unsigned long key_gc_flags;
@@ -53,12 +53,12 @@ struct key_type key_type_dead = {
53 * Schedule a garbage collection run. 53 * Schedule a garbage collection run.
54 * - time precision isn't particularly important 54 * - time precision isn't particularly important
55 */ 55 */
56void key_schedule_gc(time_t gc_at) 56void key_schedule_gc(time64_t gc_at)
57{ 57{
58 unsigned long expires; 58 unsigned long expires;
59 time_t now = current_kernel_time().tv_sec; 59 time64_t now = ktime_get_real_seconds();
60 60
61 kenter("%ld", gc_at - now); 61 kenter("%lld", gc_at - now);
62 62
63 if (gc_at <= now || test_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags)) { 63 if (gc_at <= now || test_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags)) {
64 kdebug("IMMEDIATE"); 64 kdebug("IMMEDIATE");
@@ -84,10 +84,10 @@ void key_schedule_gc_links(void)
84 * Some key's cleanup time was met after it expired, so we need to get the 84 * Some key's cleanup time was met after it expired, so we need to get the
85 * reaper to go through a cycle finding expired keys. 85 * reaper to go through a cycle finding expired keys.
86 */ 86 */
87static void key_gc_timer_func(unsigned long data) 87static void key_gc_timer_func(struct timer_list *unused)
88{ 88{
89 kenter(""); 89 kenter("");
90 key_gc_next_run = LONG_MAX; 90 key_gc_next_run = TIME64_MAX;
91 key_schedule_gc_links(); 91 key_schedule_gc_links();
92} 92}
93 93
@@ -129,15 +129,15 @@ static noinline void key_gc_unused_keys(struct list_head *keys)
129 while (!list_empty(keys)) { 129 while (!list_empty(keys)) {
130 struct key *key = 130 struct key *key =
131 list_entry(keys->next, struct key, graveyard_link); 131 list_entry(keys->next, struct key, graveyard_link);
132 short state = key->state;
133
132 list_del(&key->graveyard_link); 134 list_del(&key->graveyard_link);
133 135
134 kdebug("- %u", key->serial); 136 kdebug("- %u", key->serial);
135 key_check(key); 137 key_check(key);
136 138
137 /* Throw away the key data if the key is instantiated */ 139 /* Throw away the key data if the key is instantiated */
138 if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags) && 140 if (state == KEY_IS_POSITIVE && key->type->destroy)
139 !test_bit(KEY_FLAG_NEGATIVE, &key->flags) &&
140 key->type->destroy)
141 key->type->destroy(key); 141 key->type->destroy(key);
142 142
143 security_key_free(key); 143 security_key_free(key);
@@ -151,7 +151,7 @@ static noinline void key_gc_unused_keys(struct list_head *keys)
151 } 151 }
152 152
153 atomic_dec(&key->user->nkeys); 153 atomic_dec(&key->user->nkeys);
154 if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) 154 if (state != KEY_IS_UNINSTANTIATED)
155 atomic_dec(&key->user->nikeys); 155 atomic_dec(&key->user->nikeys);
156 156
157 key_user_put(key->user); 157 key_user_put(key->user);
@@ -184,11 +184,11 @@ static void key_garbage_collector(struct work_struct *work)
184 184
185 struct rb_node *cursor; 185 struct rb_node *cursor;
186 struct key *key; 186 struct key *key;
187 time_t new_timer, limit; 187 time64_t new_timer, limit;
188 188
189 kenter("[%lx,%x]", key_gc_flags, gc_state); 189 kenter("[%lx,%x]", key_gc_flags, gc_state);
190 190
191 limit = current_kernel_time().tv_sec; 191 limit = ktime_get_real_seconds();
192 if (limit > key_gc_delay) 192 if (limit > key_gc_delay)
193 limit -= key_gc_delay; 193 limit -= key_gc_delay;
194 else 194 else
@@ -204,7 +204,7 @@ static void key_garbage_collector(struct work_struct *work)
204 gc_state |= KEY_GC_REAPING_DEAD_1; 204 gc_state |= KEY_GC_REAPING_DEAD_1;
205 kdebug("new pass %x", gc_state); 205 kdebug("new pass %x", gc_state);
206 206
207 new_timer = LONG_MAX; 207 new_timer = TIME64_MAX;
208 208
209 /* As only this function is permitted to remove things from the key 209 /* As only this function is permitted to remove things from the key
210 * serial tree, if cursor is non-NULL then it will always point to a 210 * serial tree, if cursor is non-NULL then it will always point to a
@@ -235,7 +235,7 @@ continue_scanning:
235 235
236 if (gc_state & KEY_GC_SET_TIMER) { 236 if (gc_state & KEY_GC_SET_TIMER) {
237 if (key->expiry > limit && key->expiry < new_timer) { 237 if (key->expiry > limit && key->expiry < new_timer) {
238 kdebug("will expire %x in %ld", 238 kdebug("will expire %x in %lld",
239 key_serial(key), key->expiry - limit); 239 key_serial(key), key->expiry - limit);
240 new_timer = key->expiry; 240 new_timer = key->expiry;
241 } 241 }
@@ -276,7 +276,7 @@ maybe_resched:
276 */ 276 */
277 kdebug("pass complete"); 277 kdebug("pass complete");
278 278
279 if (gc_state & KEY_GC_SET_TIMER && new_timer != (time_t)LONG_MAX) { 279 if (gc_state & KEY_GC_SET_TIMER && new_timer != (time64_t)TIME64_MAX) {
280 new_timer += key_gc_delay; 280 new_timer += key_gc_delay;
281 key_schedule_gc(new_timer); 281 key_schedule_gc(new_timer);
282 } 282 }
diff --git a/security/keys/internal.h b/security/keys/internal.h
index 1c02c6547038..9f8208dc0e55 100644
--- a/security/keys/internal.h
+++ b/security/keys/internal.h
@@ -130,7 +130,7 @@ struct keyring_search_context {
130 int skipped_ret; 130 int skipped_ret;
131 bool possessed; 131 bool possessed;
132 key_ref_t result; 132 key_ref_t result;
133 struct timespec now; 133 time64_t now;
134}; 134};
135 135
136extern bool key_default_cmp(const struct key *key, 136extern bool key_default_cmp(const struct key *key,
@@ -141,7 +141,7 @@ extern key_ref_t keyring_search_aux(key_ref_t keyring_ref,
141extern key_ref_t search_my_process_keyrings(struct keyring_search_context *ctx); 141extern key_ref_t search_my_process_keyrings(struct keyring_search_context *ctx);
142extern key_ref_t search_process_keyrings(struct keyring_search_context *ctx); 142extern key_ref_t search_process_keyrings(struct keyring_search_context *ctx);
143 143
144extern struct key *find_keyring_by_name(const char *name, bool skip_perm_check); 144extern struct key *find_keyring_by_name(const char *name, bool uid_keyring);
145 145
146extern int install_user_keyrings(void); 146extern int install_user_keyrings(void);
147extern int install_thread_keyring_to_cred(struct cred *); 147extern int install_thread_keyring_to_cred(struct cred *);
@@ -169,10 +169,10 @@ extern void key_change_session_keyring(struct callback_head *twork);
169 169
170extern struct work_struct key_gc_work; 170extern struct work_struct key_gc_work;
171extern unsigned key_gc_delay; 171extern unsigned key_gc_delay;
172extern void keyring_gc(struct key *keyring, time_t limit); 172extern void keyring_gc(struct key *keyring, time64_t limit);
173extern void keyring_restriction_gc(struct key *keyring, 173extern void keyring_restriction_gc(struct key *keyring,
174 struct key_type *dead_type); 174 struct key_type *dead_type);
175extern void key_schedule_gc(time_t gc_at); 175extern void key_schedule_gc(time64_t gc_at);
176extern void key_schedule_gc_links(void); 176extern void key_schedule_gc_links(void);
177extern void key_gc_keytype(struct key_type *ktype); 177extern void key_gc_keytype(struct key_type *ktype);
178 178
@@ -211,7 +211,7 @@ extern struct key *key_get_instantiation_authkey(key_serial_t target_id);
211/* 211/*
212 * Determine whether a key is dead. 212 * Determine whether a key is dead.
213 */ 213 */
214static inline bool key_is_dead(const struct key *key, time_t limit) 214static inline bool key_is_dead(const struct key *key, time64_t limit)
215{ 215{
216 return 216 return
217 key->flags & ((1 << KEY_FLAG_DEAD) | 217 key->flags & ((1 << KEY_FLAG_DEAD) |
diff --git a/security/keys/key.c b/security/keys/key.c
index 83da68d98b40..d97c9394b5dd 100644
--- a/security/keys/key.c
+++ b/security/keys/key.c
@@ -54,10 +54,10 @@ void __key_check(const struct key *key)
54struct key_user *key_user_lookup(kuid_t uid) 54struct key_user *key_user_lookup(kuid_t uid)
55{ 55{
56 struct key_user *candidate = NULL, *user; 56 struct key_user *candidate = NULL, *user;
57 struct rb_node *parent = NULL; 57 struct rb_node *parent, **p;
58 struct rb_node **p;
59 58
60try_again: 59try_again:
60 parent = NULL;
61 p = &key_user_tree.rb_node; 61 p = &key_user_tree.rb_node;
62 spin_lock(&key_user_lock); 62 spin_lock(&key_user_lock);
63 63
@@ -302,6 +302,8 @@ struct key *key_alloc(struct key_type *type, const char *desc,
302 key->flags |= 1 << KEY_FLAG_IN_QUOTA; 302 key->flags |= 1 << KEY_FLAG_IN_QUOTA;
303 if (flags & KEY_ALLOC_BUILT_IN) 303 if (flags & KEY_ALLOC_BUILT_IN)
304 key->flags |= 1 << KEY_FLAG_BUILTIN; 304 key->flags |= 1 << KEY_FLAG_BUILTIN;
305 if (flags & KEY_ALLOC_UID_KEYRING)
306 key->flags |= 1 << KEY_FLAG_UID_KEYRING;
305 307
306#ifdef KEY_DEBUGGING 308#ifdef KEY_DEBUGGING
307 key->magic = KEY_DEBUG_MAGIC; 309 key->magic = KEY_DEBUG_MAGIC;
@@ -400,6 +402,18 @@ int key_payload_reserve(struct key *key, size_t datalen)
400EXPORT_SYMBOL(key_payload_reserve); 402EXPORT_SYMBOL(key_payload_reserve);
401 403
402/* 404/*
405 * Change the key state to being instantiated.
406 */
407static void mark_key_instantiated(struct key *key, int reject_error)
408{
409 /* Commit the payload before setting the state; barrier versus
410 * key_read_state().
411 */
412 smp_store_release(&key->state,
413 (reject_error < 0) ? reject_error : KEY_IS_POSITIVE);
414}
415
416/*
403 * Instantiate a key and link it into the target keyring atomically. Must be 417 * Instantiate a key and link it into the target keyring atomically. Must be
404 * called with the target keyring's semaphore writelocked. The target key's 418 * called with the target keyring's semaphore writelocked. The target key's
405 * semaphore need not be locked as instantiation is serialised by 419 * semaphore need not be locked as instantiation is serialised by
@@ -422,14 +436,14 @@ static int __key_instantiate_and_link(struct key *key,
422 mutex_lock(&key_construction_mutex); 436 mutex_lock(&key_construction_mutex);
423 437
424 /* can't instantiate twice */ 438 /* can't instantiate twice */
425 if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) { 439 if (key->state == KEY_IS_UNINSTANTIATED) {
426 /* instantiate the key */ 440 /* instantiate the key */
427 ret = key->type->instantiate(key, prep); 441 ret = key->type->instantiate(key, prep);
428 442
429 if (ret == 0) { 443 if (ret == 0) {
430 /* mark the key as being instantiated */ 444 /* mark the key as being instantiated */
431 atomic_inc(&key->user->nikeys); 445 atomic_inc(&key->user->nikeys);
432 set_bit(KEY_FLAG_INSTANTIATED, &key->flags); 446 mark_key_instantiated(key, 0);
433 447
434 if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) 448 if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
435 awaken = 1; 449 awaken = 1;
@@ -446,7 +460,7 @@ static int __key_instantiate_and_link(struct key *key,
446 if (authkey) 460 if (authkey)
447 key_revoke(authkey); 461 key_revoke(authkey);
448 462
449 if (prep->expiry != TIME_T_MAX) { 463 if (prep->expiry != TIME64_MAX) {
450 key->expiry = prep->expiry; 464 key->expiry = prep->expiry;
451 key_schedule_gc(prep->expiry + key_gc_delay); 465 key_schedule_gc(prep->expiry + key_gc_delay);
452 } 466 }
@@ -492,7 +506,7 @@ int key_instantiate_and_link(struct key *key,
492 prep.data = data; 506 prep.data = data;
493 prep.datalen = datalen; 507 prep.datalen = datalen;
494 prep.quotalen = key->type->def_datalen; 508 prep.quotalen = key->type->def_datalen;
495 prep.expiry = TIME_T_MAX; 509 prep.expiry = TIME64_MAX;
496 if (key->type->preparse) { 510 if (key->type->preparse) {
497 ret = key->type->preparse(&prep); 511 ret = key->type->preparse(&prep);
498 if (ret < 0) 512 if (ret < 0)
@@ -556,7 +570,6 @@ int key_reject_and_link(struct key *key,
556 struct key *authkey) 570 struct key *authkey)
557{ 571{
558 struct assoc_array_edit *edit; 572 struct assoc_array_edit *edit;
559 struct timespec now;
560 int ret, awaken, link_ret = 0; 573 int ret, awaken, link_ret = 0;
561 574
562 key_check(key); 575 key_check(key);
@@ -575,15 +588,11 @@ int key_reject_and_link(struct key *key,
575 mutex_lock(&key_construction_mutex); 588 mutex_lock(&key_construction_mutex);
576 589
577 /* can't instantiate twice */ 590 /* can't instantiate twice */
578 if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) { 591 if (key->state == KEY_IS_UNINSTANTIATED) {
579 /* mark the key as being negatively instantiated */ 592 /* mark the key as being negatively instantiated */
580 atomic_inc(&key->user->nikeys); 593 atomic_inc(&key->user->nikeys);
581 key->reject_error = -error; 594 mark_key_instantiated(key, -error);
582 smp_wmb(); 595 key->expiry = ktime_get_real_seconds() + timeout;
583 set_bit(KEY_FLAG_NEGATIVE, &key->flags);
584 set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
585 now = current_kernel_time();
586 key->expiry = now.tv_sec + timeout;
587 key_schedule_gc(key->expiry + key_gc_delay); 596 key_schedule_gc(key->expiry + key_gc_delay);
588 597
589 if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) 598 if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
@@ -699,16 +708,13 @@ found_kernel_type:
699 708
700void key_set_timeout(struct key *key, unsigned timeout) 709void key_set_timeout(struct key *key, unsigned timeout)
701{ 710{
702 struct timespec now; 711 time64_t expiry = 0;
703 time_t expiry = 0;
704 712
705 /* make the changes with the locks held to prevent races */ 713 /* make the changes with the locks held to prevent races */
706 down_write(&key->sem); 714 down_write(&key->sem);
707 715
708 if (timeout > 0) { 716 if (timeout > 0)
709 now = current_kernel_time(); 717 expiry = ktime_get_real_seconds() + timeout;
710 expiry = now.tv_sec + timeout;
711 }
712 718
713 key->expiry = expiry; 719 key->expiry = expiry;
714 key_schedule_gc(key->expiry + key_gc_delay); 720 key_schedule_gc(key->expiry + key_gc_delay);
@@ -750,8 +756,8 @@ static inline key_ref_t __key_update(key_ref_t key_ref,
750 756
751 ret = key->type->update(key, prep); 757 ret = key->type->update(key, prep);
752 if (ret == 0) 758 if (ret == 0)
753 /* updating a negative key instantiates it */ 759 /* Updating a negative key positively instantiates it */
754 clear_bit(KEY_FLAG_NEGATIVE, &key->flags); 760 mark_key_instantiated(key, 0);
755 761
756 up_write(&key->sem); 762 up_write(&key->sem);
757 763
@@ -827,7 +833,6 @@ key_ref_t key_create_or_update(key_ref_t keyring_ref,
827 833
828 key_check(keyring); 834 key_check(keyring);
829 835
830 key_ref = ERR_PTR(-EPERM);
831 if (!(flags & KEY_ALLOC_BYPASS_RESTRICTION)) 836 if (!(flags & KEY_ALLOC_BYPASS_RESTRICTION))
832 restrict_link = keyring->restrict_link; 837 restrict_link = keyring->restrict_link;
833 838
@@ -839,7 +844,7 @@ key_ref_t key_create_or_update(key_ref_t keyring_ref,
839 prep.data = payload; 844 prep.data = payload;
840 prep.datalen = plen; 845 prep.datalen = plen;
841 prep.quotalen = index_key.type->def_datalen; 846 prep.quotalen = index_key.type->def_datalen;
842 prep.expiry = TIME_T_MAX; 847 prep.expiry = TIME64_MAX;
843 if (index_key.type->preparse) { 848 if (index_key.type->preparse) {
844 ret = index_key.type->preparse(&prep); 849 ret = index_key.type->preparse(&prep);
845 if (ret < 0) { 850 if (ret < 0) {
@@ -934,6 +939,16 @@ error:
934 */ 939 */
935 __key_link_end(keyring, &index_key, edit); 940 __key_link_end(keyring, &index_key, edit);
936 941
942 key = key_ref_to_ptr(key_ref);
943 if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) {
944 ret = wait_for_key_construction(key, true);
945 if (ret < 0) {
946 key_ref_put(key_ref);
947 key_ref = ERR_PTR(ret);
948 goto error_free_prep;
949 }
950 }
951
937 key_ref = __key_update(key_ref, &prep); 952 key_ref = __key_update(key_ref, &prep);
938 goto error_free_prep; 953 goto error_free_prep;
939} 954}
@@ -973,7 +988,7 @@ int key_update(key_ref_t key_ref, const void *payload, size_t plen)
973 prep.data = payload; 988 prep.data = payload;
974 prep.datalen = plen; 989 prep.datalen = plen;
975 prep.quotalen = key->type->def_datalen; 990 prep.quotalen = key->type->def_datalen;
976 prep.expiry = TIME_T_MAX; 991 prep.expiry = TIME64_MAX;
977 if (key->type->preparse) { 992 if (key->type->preparse) {
978 ret = key->type->preparse(&prep); 993 ret = key->type->preparse(&prep);
979 if (ret < 0) 994 if (ret < 0)
@@ -984,8 +999,8 @@ int key_update(key_ref_t key_ref, const void *payload, size_t plen)
984 999
985 ret = key->type->update(key, &prep); 1000 ret = key->type->update(key, &prep);
986 if (ret == 0) 1001 if (ret == 0)
987 /* updating a negative key instantiates it */ 1002 /* Updating a negative key positively instantiates it */
988 clear_bit(KEY_FLAG_NEGATIVE, &key->flags); 1003 mark_key_instantiated(key, 0);
989 1004
990 up_write(&key->sem); 1005 up_write(&key->sem);
991 1006
@@ -1007,8 +1022,7 @@ EXPORT_SYMBOL(key_update);
1007 */ 1022 */
1008void key_revoke(struct key *key) 1023void key_revoke(struct key *key)
1009{ 1024{
1010 struct timespec now; 1025 time64_t time;
1011 time_t time;
1012 1026
1013 key_check(key); 1027 key_check(key);
1014 1028
@@ -1023,8 +1037,7 @@ void key_revoke(struct key *key)
1023 key->type->revoke(key); 1037 key->type->revoke(key);
1024 1038
1025 /* set the death time to no more than the expiry time */ 1039 /* set the death time to no more than the expiry time */
1026 now = current_kernel_time(); 1040 time = ktime_get_real_seconds();
1027 time = now.tv_sec;
1028 if (key->revoked_at == 0 || key->revoked_at > time) { 1041 if (key->revoked_at == 0 || key->revoked_at > time) {
1029 key->revoked_at = time; 1042 key->revoked_at = time;
1030 key_schedule_gc(key->revoked_at + key_gc_delay); 1043 key_schedule_gc(key->revoked_at + key_gc_delay);
diff --git a/security/keys/keyctl.c b/security/keys/keyctl.c
index ab0b337c84b4..1ffe60bb2845 100644
--- a/security/keys/keyctl.c
+++ b/security/keys/keyctl.c
@@ -766,12 +766,16 @@ long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
766 766
767 key = key_ref_to_ptr(key_ref); 767 key = key_ref_to_ptr(key_ref);
768 768
769 ret = key_read_state(key);
770 if (ret < 0)
771 goto error2; /* Negatively instantiated */
772
769 /* see if we can read it directly */ 773 /* see if we can read it directly */
770 ret = key_permission(key_ref, KEY_NEED_READ); 774 ret = key_permission(key_ref, KEY_NEED_READ);
771 if (ret == 0) 775 if (ret == 0)
772 goto can_read_key; 776 goto can_read_key;
773 if (ret != -EACCES) 777 if (ret != -EACCES)
774 goto error; 778 goto error2;
775 779
776 /* we can't; see if it's searchable from this process's keyrings 780 /* we can't; see if it's searchable from this process's keyrings
777 * - we automatically take account of the fact that it may be 781 * - we automatically take account of the fact that it may be
@@ -896,7 +900,7 @@ long keyctl_chown_key(key_serial_t id, uid_t user, gid_t group)
896 atomic_dec(&key->user->nkeys); 900 atomic_dec(&key->user->nkeys);
897 atomic_inc(&newowner->nkeys); 901 atomic_inc(&newowner->nkeys);
898 902
899 if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) { 903 if (key->state != KEY_IS_UNINSTANTIATED) {
900 atomic_dec(&key->user->nikeys); 904 atomic_dec(&key->user->nikeys);
901 atomic_inc(&newowner->nikeys); 905 atomic_inc(&newowner->nikeys);
902 } 906 }
@@ -1406,11 +1410,9 @@ long keyctl_assume_authority(key_serial_t id)
1406 } 1410 }
1407 1411
1408 ret = keyctl_change_reqkey_auth(authkey); 1412 ret = keyctl_change_reqkey_auth(authkey);
1409 if (ret < 0) 1413 if (ret == 0)
1410 goto error; 1414 ret = authkey->serial;
1411 key_put(authkey); 1415 key_put(authkey);
1412
1413 ret = authkey->serial;
1414error: 1416error:
1415 return ret; 1417 return ret;
1416} 1418}
@@ -1586,9 +1588,8 @@ error_keyring:
1586 * The caller must have Setattr permission to change keyring restrictions. 1588 * The caller must have Setattr permission to change keyring restrictions.
1587 * 1589 *
1588 * The requested type name may be a NULL pointer to reject all attempts 1590 * The requested type name may be a NULL pointer to reject all attempts
1589 * to link to the keyring. If _type is non-NULL, _restriction can be 1591 * to link to the keyring. In this case, _restriction must also be NULL.
1590 * NULL or a pointer to a string describing the restriction. If _type is 1592 * Otherwise, both _type and _restriction must be non-NULL.
1591 * NULL, _restriction must also be NULL.
1592 * 1593 *
1593 * Returns 0 if successful. 1594 * Returns 0 if successful.
1594 */ 1595 */
@@ -1596,7 +1597,6 @@ long keyctl_restrict_keyring(key_serial_t id, const char __user *_type,
1596 const char __user *_restriction) 1597 const char __user *_restriction)
1597{ 1598{
1598 key_ref_t key_ref; 1599 key_ref_t key_ref;
1599 bool link_reject = !_type;
1600 char type[32]; 1600 char type[32];
1601 char *restriction = NULL; 1601 char *restriction = NULL;
1602 long ret; 1602 long ret;
@@ -1605,31 +1605,29 @@ long keyctl_restrict_keyring(key_serial_t id, const char __user *_type,
1605 if (IS_ERR(key_ref)) 1605 if (IS_ERR(key_ref))
1606 return PTR_ERR(key_ref); 1606 return PTR_ERR(key_ref);
1607 1607
1608 ret = -EINVAL;
1608 if (_type) { 1609 if (_type) {
1610 if (!_restriction)
1611 goto error;
1612
1609 ret = key_get_type_from_user(type, _type, sizeof(type)); 1613 ret = key_get_type_from_user(type, _type, sizeof(type));
1610 if (ret < 0) 1614 if (ret < 0)
1611 goto error; 1615 goto error;
1612 }
1613
1614 if (_restriction) {
1615 if (!_type) {
1616 ret = -EINVAL;
1617 goto error;
1618 }
1619 1616
1620 restriction = strndup_user(_restriction, PAGE_SIZE); 1617 restriction = strndup_user(_restriction, PAGE_SIZE);
1621 if (IS_ERR(restriction)) { 1618 if (IS_ERR(restriction)) {
1622 ret = PTR_ERR(restriction); 1619 ret = PTR_ERR(restriction);
1623 goto error; 1620 goto error;
1624 } 1621 }
1622 } else {
1623 if (_restriction)
1624 goto error;
1625 } 1625 }
1626 1626
1627 ret = keyring_restrict(key_ref, link_reject ? NULL : type, restriction); 1627 ret = keyring_restrict(key_ref, _type ? type : NULL, restriction);
1628 kfree(restriction); 1628 kfree(restriction);
1629
1630error: 1629error:
1631 key_ref_put(key_ref); 1630 key_ref_put(key_ref);
1632
1633 return ret; 1631 return ret;
1634} 1632}
1635 1633
diff --git a/security/keys/keyring.c b/security/keys/keyring.c
index de81793f9920..d0bccebbd3b5 100644
--- a/security/keys/keyring.c
+++ b/security/keys/keyring.c
@@ -414,7 +414,7 @@ static void keyring_describe(const struct key *keyring, struct seq_file *m)
414 else 414 else
415 seq_puts(m, "[anon]"); 415 seq_puts(m, "[anon]");
416 416
417 if (key_is_instantiated(keyring)) { 417 if (key_is_positive(keyring)) {
418 if (keyring->keys.nr_leaves_on_tree != 0) 418 if (keyring->keys.nr_leaves_on_tree != 0)
419 seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree); 419 seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree);
420 else 420 else
@@ -423,7 +423,7 @@ static void keyring_describe(const struct key *keyring, struct seq_file *m)
423} 423}
424 424
425struct keyring_read_iterator_context { 425struct keyring_read_iterator_context {
426 size_t qty; 426 size_t buflen;
427 size_t count; 427 size_t count;
428 key_serial_t __user *buffer; 428 key_serial_t __user *buffer;
429}; 429};
@@ -435,9 +435,9 @@ static int keyring_read_iterator(const void *object, void *data)
435 int ret; 435 int ret;
436 436
437 kenter("{%s,%d},,{%zu/%zu}", 437 kenter("{%s,%d},,{%zu/%zu}",
438 key->type->name, key->serial, ctx->count, ctx->qty); 438 key->type->name, key->serial, ctx->count, ctx->buflen);
439 439
440 if (ctx->count >= ctx->qty) 440 if (ctx->count >= ctx->buflen)
441 return 1; 441 return 1;
442 442
443 ret = put_user(key->serial, ctx->buffer); 443 ret = put_user(key->serial, ctx->buffer);
@@ -459,38 +459,33 @@ static long keyring_read(const struct key *keyring,
459 char __user *buffer, size_t buflen) 459 char __user *buffer, size_t buflen)
460{ 460{
461 struct keyring_read_iterator_context ctx; 461 struct keyring_read_iterator_context ctx;
462 unsigned long nr_keys; 462 long ret;
463 int ret;
464 463
465 kenter("{%d},,%zu", key_serial(keyring), buflen); 464 kenter("{%d},,%zu", key_serial(keyring), buflen);
466 465
467 if (buflen & (sizeof(key_serial_t) - 1)) 466 if (buflen & (sizeof(key_serial_t) - 1))
468 return -EINVAL; 467 return -EINVAL;
469 468
470 nr_keys = keyring->keys.nr_leaves_on_tree; 469 /* Copy as many key IDs as fit into the buffer */
471 if (nr_keys == 0) 470 if (buffer && buflen) {
472 return 0; 471 ctx.buffer = (key_serial_t __user *)buffer;
473 472 ctx.buflen = buflen;
474 /* Calculate how much data we could return */ 473 ctx.count = 0;
475 ctx.qty = nr_keys * sizeof(key_serial_t); 474 ret = assoc_array_iterate(&keyring->keys,
476 475 keyring_read_iterator, &ctx);
477 if (!buffer || !buflen) 476 if (ret < 0) {
478 return ctx.qty; 477 kleave(" = %ld [iterate]", ret);
479 478 return ret;
480 if (buflen > ctx.qty) 479 }
481 ctx.qty = buflen;
482
483 /* Copy the IDs of the subscribed keys into the buffer */
484 ctx.buffer = (key_serial_t __user *)buffer;
485 ctx.count = 0;
486 ret = assoc_array_iterate(&keyring->keys, keyring_read_iterator, &ctx);
487 if (ret < 0) {
488 kleave(" = %d [iterate]", ret);
489 return ret;
490 } 480 }
491 481
492 kleave(" = %zu [ok]", ctx.count); 482 /* Return the size of the buffer needed */
493 return ctx.count; 483 ret = keyring->keys.nr_leaves_on_tree * sizeof(key_serial_t);
484 if (ret <= buflen)
485 kleave("= %ld [ok]", ret);
486 else
487 kleave("= %ld [buffer too small]", ret);
488 return ret;
494} 489}
495 490
496/* 491/*
@@ -557,7 +552,8 @@ static int keyring_search_iterator(const void *object, void *iterator_data)
557{ 552{
558 struct keyring_search_context *ctx = iterator_data; 553 struct keyring_search_context *ctx = iterator_data;
559 const struct key *key = keyring_ptr_to_key(object); 554 const struct key *key = keyring_ptr_to_key(object);
560 unsigned long kflags = key->flags; 555 unsigned long kflags = READ_ONCE(key->flags);
556 short state = READ_ONCE(key->state);
561 557
562 kenter("{%d}", key->serial); 558 kenter("{%d}", key->serial);
563 559
@@ -569,6 +565,8 @@ static int keyring_search_iterator(const void *object, void *iterator_data)
569 565
570 /* skip invalidated, revoked and expired keys */ 566 /* skip invalidated, revoked and expired keys */
571 if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) { 567 if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
568 time64_t expiry = READ_ONCE(key->expiry);
569
572 if (kflags & ((1 << KEY_FLAG_INVALIDATED) | 570 if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
573 (1 << KEY_FLAG_REVOKED))) { 571 (1 << KEY_FLAG_REVOKED))) {
574 ctx->result = ERR_PTR(-EKEYREVOKED); 572 ctx->result = ERR_PTR(-EKEYREVOKED);
@@ -576,7 +574,7 @@ static int keyring_search_iterator(const void *object, void *iterator_data)
576 goto skipped; 574 goto skipped;
577 } 575 }
578 576
579 if (key->expiry && ctx->now.tv_sec >= key->expiry) { 577 if (expiry && ctx->now >= expiry) {
580 if (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED)) 578 if (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED))
581 ctx->result = ERR_PTR(-EKEYEXPIRED); 579 ctx->result = ERR_PTR(-EKEYEXPIRED);
582 kleave(" = %d [expire]", ctx->skipped_ret); 580 kleave(" = %d [expire]", ctx->skipped_ret);
@@ -601,9 +599,8 @@ static int keyring_search_iterator(const void *object, void *iterator_data)
601 599
602 if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) { 600 if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
603 /* we set a different error code if we pass a negative key */ 601 /* we set a different error code if we pass a negative key */
604 if (kflags & (1 << KEY_FLAG_NEGATIVE)) { 602 if (state < 0) {
605 smp_rmb(); 603 ctx->result = ERR_PTR(state);
606 ctx->result = ERR_PTR(key->reject_error);
607 kleave(" = %d [neg]", ctx->skipped_ret); 604 kleave(" = %d [neg]", ctx->skipped_ret);
608 goto skipped; 605 goto skipped;
609 } 606 }
@@ -837,10 +834,10 @@ found:
837 key = key_ref_to_ptr(ctx->result); 834 key = key_ref_to_ptr(ctx->result);
838 key_check(key); 835 key_check(key);
839 if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) { 836 if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) {
840 key->last_used_at = ctx->now.tv_sec; 837 key->last_used_at = ctx->now;
841 keyring->last_used_at = ctx->now.tv_sec; 838 keyring->last_used_at = ctx->now;
842 while (sp > 0) 839 while (sp > 0)
843 stack[--sp].keyring->last_used_at = ctx->now.tv_sec; 840 stack[--sp].keyring->last_used_at = ctx->now;
844 } 841 }
845 kleave(" = true"); 842 kleave(" = true");
846 return true; 843 return true;
@@ -901,7 +898,7 @@ key_ref_t keyring_search_aux(key_ref_t keyring_ref,
901 } 898 }
902 899
903 rcu_read_lock(); 900 rcu_read_lock();
904 ctx->now = current_kernel_time(); 901 ctx->now = ktime_get_real_seconds();
905 if (search_nested_keyrings(keyring, ctx)) 902 if (search_nested_keyrings(keyring, ctx))
906 __key_get(key_ref_to_ptr(ctx->result)); 903 __key_get(key_ref_to_ptr(ctx->result));
907 rcu_read_unlock(); 904 rcu_read_unlock();
@@ -1101,15 +1098,15 @@ found:
1101/* 1098/*
1102 * Find a keyring with the specified name. 1099 * Find a keyring with the specified name.
1103 * 1100 *
1104 * All named keyrings in the current user namespace are searched, provided they 1101 * Only keyrings that have nonzero refcount, are not revoked, and are owned by a
1105 * grant Search permission directly to the caller (unless this check is 1102 * user in the current user namespace are considered. If @uid_keyring is %true,
1106 * skipped). Keyrings whose usage points have reached zero or who have been 1103 * the keyring additionally must have been allocated as a user or user session
1107 * revoked are skipped. 1104 * keyring; otherwise, it must grant Search permission directly to the caller.
1108 * 1105 *
1109 * Returns a pointer to the keyring with the keyring's refcount having being 1106 * Returns a pointer to the keyring with the keyring's refcount having being
1110 * incremented on success. -ENOKEY is returned if a key could not be found. 1107 * incremented on success. -ENOKEY is returned if a key could not be found.
1111 */ 1108 */
1112struct key *find_keyring_by_name(const char *name, bool skip_perm_check) 1109struct key *find_keyring_by_name(const char *name, bool uid_keyring)
1113{ 1110{
1114 struct key *keyring; 1111 struct key *keyring;
1115 int bucket; 1112 int bucket;
@@ -1137,17 +1134,22 @@ struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
1137 if (strcmp(keyring->description, name) != 0) 1134 if (strcmp(keyring->description, name) != 0)
1138 continue; 1135 continue;
1139 1136
1140 if (!skip_perm_check && 1137 if (uid_keyring) {
1141 key_permission(make_key_ref(keyring, 0), 1138 if (!test_bit(KEY_FLAG_UID_KEYRING,
1142 KEY_NEED_SEARCH) < 0) 1139 &keyring->flags))
1143 continue; 1140 continue;
1141 } else {
1142 if (key_permission(make_key_ref(keyring, 0),
1143 KEY_NEED_SEARCH) < 0)
1144 continue;
1145 }
1144 1146
1145 /* we've got a match but we might end up racing with 1147 /* we've got a match but we might end up racing with
1146 * key_cleanup() if the keyring is currently 'dead' 1148 * key_cleanup() if the keyring is currently 'dead'
1147 * (ie. it has a zero usage count) */ 1149 * (ie. it has a zero usage count) */
1148 if (!refcount_inc_not_zero(&keyring->usage)) 1150 if (!refcount_inc_not_zero(&keyring->usage))
1149 continue; 1151 continue;
1150 keyring->last_used_at = current_kernel_time().tv_sec; 1152 keyring->last_used_at = ktime_get_real_seconds();
1151 goto out; 1153 goto out;
1152 } 1154 }
1153 } 1155 }
@@ -1487,7 +1489,7 @@ static void keyring_revoke(struct key *keyring)
1487static bool keyring_gc_select_iterator(void *object, void *iterator_data) 1489static bool keyring_gc_select_iterator(void *object, void *iterator_data)
1488{ 1490{
1489 struct key *key = keyring_ptr_to_key(object); 1491 struct key *key = keyring_ptr_to_key(object);
1490 time_t *limit = iterator_data; 1492 time64_t *limit = iterator_data;
1491 1493
1492 if (key_is_dead(key, *limit)) 1494 if (key_is_dead(key, *limit))
1493 return false; 1495 return false;
@@ -1498,7 +1500,7 @@ static bool keyring_gc_select_iterator(void *object, void *iterator_data)
1498static int keyring_gc_check_iterator(const void *object, void *iterator_data) 1500static int keyring_gc_check_iterator(const void *object, void *iterator_data)
1499{ 1501{
1500 const struct key *key = keyring_ptr_to_key(object); 1502 const struct key *key = keyring_ptr_to_key(object);
1501 time_t *limit = iterator_data; 1503 time64_t *limit = iterator_data;
1502 1504
1503 key_check(key); 1505 key_check(key);
1504 return key_is_dead(key, *limit); 1506 return key_is_dead(key, *limit);
@@ -1510,7 +1512,7 @@ static int keyring_gc_check_iterator(const void *object, void *iterator_data)
1510 * Not called with any locks held. The keyring's key struct will not be 1512 * Not called with any locks held. The keyring's key struct will not be
1511 * deallocated under us as only our caller may deallocate it. 1513 * deallocated under us as only our caller may deallocate it.
1512 */ 1514 */
1513void keyring_gc(struct key *keyring, time_t limit) 1515void keyring_gc(struct key *keyring, time64_t limit)
1514{ 1516{
1515 int result; 1517 int result;
1516 1518
diff --git a/security/keys/permission.c b/security/keys/permission.c
index 732cc0beffdf..f68dc04d614e 100644
--- a/security/keys/permission.c
+++ b/security/keys/permission.c
@@ -88,7 +88,8 @@ EXPORT_SYMBOL(key_task_permission);
88 */ 88 */
89int key_validate(const struct key *key) 89int key_validate(const struct key *key)
90{ 90{
91 unsigned long flags = key->flags; 91 unsigned long flags = READ_ONCE(key->flags);
92 time64_t expiry = READ_ONCE(key->expiry);
92 93
93 if (flags & (1 << KEY_FLAG_INVALIDATED)) 94 if (flags & (1 << KEY_FLAG_INVALIDATED))
94 return -ENOKEY; 95 return -ENOKEY;
@@ -99,9 +100,8 @@ int key_validate(const struct key *key)
99 return -EKEYREVOKED; 100 return -EKEYREVOKED;
100 101
101 /* check it hasn't expired */ 102 /* check it hasn't expired */
102 if (key->expiry) { 103 if (expiry) {
103 struct timespec now = current_kernel_time(); 104 if (ktime_get_real_seconds() >= expiry)
104 if (now.tv_sec >= key->expiry)
105 return -EKEYEXPIRED; 105 return -EKEYEXPIRED;
106 } 106 }
107 107
diff --git a/security/keys/proc.c b/security/keys/proc.c
index bf08d02b6646..fbc4af5c6c9f 100644
--- a/security/keys/proc.c
+++ b/security/keys/proc.c
@@ -178,16 +178,18 @@ static int proc_keys_show(struct seq_file *m, void *v)
178{ 178{
179 struct rb_node *_p = v; 179 struct rb_node *_p = v;
180 struct key *key = rb_entry(_p, struct key, serial_node); 180 struct key *key = rb_entry(_p, struct key, serial_node);
181 struct timespec now; 181 unsigned long flags;
182 unsigned long timo;
183 key_ref_t key_ref, skey_ref; 182 key_ref_t key_ref, skey_ref;
183 time64_t now, expiry;
184 char xbuf[16]; 184 char xbuf[16];
185 short state;
186 u64 timo;
185 int rc; 187 int rc;
186 188
187 struct keyring_search_context ctx = { 189 struct keyring_search_context ctx = {
188 .index_key.type = key->type, 190 .index_key.type = key->type,
189 .index_key.description = key->description, 191 .index_key.description = key->description,
190 .cred = current_cred(), 192 .cred = m->file->f_cred,
191 .match_data.cmp = lookup_user_key_possessed, 193 .match_data.cmp = lookup_user_key_possessed,
192 .match_data.raw_data = key, 194 .match_data.raw_data = key,
193 .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, 195 .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
@@ -207,51 +209,51 @@ static int proc_keys_show(struct seq_file *m, void *v)
207 } 209 }
208 } 210 }
209 211
210 /* check whether the current task is allowed to view the key (assuming 212 /* check whether the current task is allowed to view the key */
211 * non-possession)
212 * - the caller holds a spinlock, and thus the RCU read lock, making our
213 * access to __current_cred() safe
214 */
215 rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW); 213 rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW);
216 if (rc < 0) 214 if (rc < 0)
217 return 0; 215 return 0;
218 216
219 now = current_kernel_time(); 217 now = ktime_get_real_seconds();
220 218
221 rcu_read_lock(); 219 rcu_read_lock();
222 220
223 /* come up with a suitable timeout value */ 221 /* come up with a suitable timeout value */
224 if (key->expiry == 0) { 222 expiry = READ_ONCE(key->expiry);
223 if (expiry == 0) {
225 memcpy(xbuf, "perm", 5); 224 memcpy(xbuf, "perm", 5);
226 } else if (now.tv_sec >= key->expiry) { 225 } else if (now >= expiry) {
227 memcpy(xbuf, "expd", 5); 226 memcpy(xbuf, "expd", 5);
228 } else { 227 } else {
229 timo = key->expiry - now.tv_sec; 228 timo = expiry - now;
230 229
231 if (timo < 60) 230 if (timo < 60)
232 sprintf(xbuf, "%lus", timo); 231 sprintf(xbuf, "%llus", timo);
233 else if (timo < 60*60) 232 else if (timo < 60*60)
234 sprintf(xbuf, "%lum", timo / 60); 233 sprintf(xbuf, "%llum", div_u64(timo, 60));
235 else if (timo < 60*60*24) 234 else if (timo < 60*60*24)
236 sprintf(xbuf, "%luh", timo / (60*60)); 235 sprintf(xbuf, "%lluh", div_u64(timo, 60 * 60));
237 else if (timo < 60*60*24*7) 236 else if (timo < 60*60*24*7)
238 sprintf(xbuf, "%lud", timo / (60*60*24)); 237 sprintf(xbuf, "%llud", div_u64(timo, 60 * 60 * 24));
239 else 238 else
240 sprintf(xbuf, "%luw", timo / (60*60*24*7)); 239 sprintf(xbuf, "%lluw", div_u64(timo, 60 * 60 * 24 * 7));
241 } 240 }
242 241
243#define showflag(KEY, LETTER, FLAG) \ 242 state = key_read_state(key);
244 (test_bit(FLAG, &(KEY)->flags) ? LETTER : '-') 243
244#define showflag(FLAGS, LETTER, FLAG) \
245 ((FLAGS & (1 << FLAG)) ? LETTER : '-')
245 246
247 flags = READ_ONCE(key->flags);
246 seq_printf(m, "%08x %c%c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ", 248 seq_printf(m, "%08x %c%c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ",
247 key->serial, 249 key->serial,
248 showflag(key, 'I', KEY_FLAG_INSTANTIATED), 250 state != KEY_IS_UNINSTANTIATED ? 'I' : '-',
249 showflag(key, 'R', KEY_FLAG_REVOKED), 251 showflag(flags, 'R', KEY_FLAG_REVOKED),
250 showflag(key, 'D', KEY_FLAG_DEAD), 252 showflag(flags, 'D', KEY_FLAG_DEAD),
251 showflag(key, 'Q', KEY_FLAG_IN_QUOTA), 253 showflag(flags, 'Q', KEY_FLAG_IN_QUOTA),
252 showflag(key, 'U', KEY_FLAG_USER_CONSTRUCT), 254 showflag(flags, 'U', KEY_FLAG_USER_CONSTRUCT),
253 showflag(key, 'N', KEY_FLAG_NEGATIVE), 255 state < 0 ? 'N' : '-',
254 showflag(key, 'i', KEY_FLAG_INVALIDATED), 256 showflag(flags, 'i', KEY_FLAG_INVALIDATED),
255 refcount_read(&key->usage), 257 refcount_read(&key->usage),
256 xbuf, 258 xbuf,
257 key->perm, 259 key->perm,
diff --git a/security/keys/process_keys.c b/security/keys/process_keys.c
index 86bced9fdbdf..d5b25e535d3a 100644
--- a/security/keys/process_keys.c
+++ b/security/keys/process_keys.c
@@ -77,7 +77,8 @@ int install_user_keyrings(void)
77 if (IS_ERR(uid_keyring)) { 77 if (IS_ERR(uid_keyring)) {
78 uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID, 78 uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID,
79 cred, user_keyring_perm, 79 cred, user_keyring_perm,
80 KEY_ALLOC_IN_QUOTA, 80 KEY_ALLOC_UID_KEYRING |
81 KEY_ALLOC_IN_QUOTA,
81 NULL, NULL); 82 NULL, NULL);
82 if (IS_ERR(uid_keyring)) { 83 if (IS_ERR(uid_keyring)) {
83 ret = PTR_ERR(uid_keyring); 84 ret = PTR_ERR(uid_keyring);
@@ -94,7 +95,8 @@ int install_user_keyrings(void)
94 session_keyring = 95 session_keyring =
95 keyring_alloc(buf, user->uid, INVALID_GID, 96 keyring_alloc(buf, user->uid, INVALID_GID,
96 cred, user_keyring_perm, 97 cred, user_keyring_perm,
97 KEY_ALLOC_IN_QUOTA, 98 KEY_ALLOC_UID_KEYRING |
99 KEY_ALLOC_IN_QUOTA,
98 NULL, NULL); 100 NULL, NULL);
99 if (IS_ERR(session_keyring)) { 101 if (IS_ERR(session_keyring)) {
100 ret = PTR_ERR(session_keyring); 102 ret = PTR_ERR(session_keyring);
@@ -728,7 +730,7 @@ try_again:
728 730
729 ret = -EIO; 731 ret = -EIO;
730 if (!(lflags & KEY_LOOKUP_PARTIAL) && 732 if (!(lflags & KEY_LOOKUP_PARTIAL) &&
731 !test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) 733 key_read_state(key) == KEY_IS_UNINSTANTIATED)
732 goto invalid_key; 734 goto invalid_key;
733 735
734 /* check the permissions */ 736 /* check the permissions */
@@ -736,7 +738,7 @@ try_again:
736 if (ret < 0) 738 if (ret < 0)
737 goto invalid_key; 739 goto invalid_key;
738 740
739 key->last_used_at = current_kernel_time().tv_sec; 741 key->last_used_at = ktime_get_real_seconds();
740 742
741error: 743error:
742 put_cred(ctx.cred); 744 put_cred(ctx.cred);
diff --git a/security/keys/request_key.c b/security/keys/request_key.c
index 63e63a42db3c..114f7408feee 100644
--- a/security/keys/request_key.c
+++ b/security/keys/request_key.c
@@ -251,11 +251,12 @@ static int construct_key(struct key *key, const void *callout_info,
251 * The keyring selected is returned with an extra reference upon it which the 251 * The keyring selected is returned with an extra reference upon it which the
252 * caller must release. 252 * caller must release.
253 */ 253 */
254static void construct_get_dest_keyring(struct key **_dest_keyring) 254static int construct_get_dest_keyring(struct key **_dest_keyring)
255{ 255{
256 struct request_key_auth *rka; 256 struct request_key_auth *rka;
257 const struct cred *cred = current_cred(); 257 const struct cred *cred = current_cred();
258 struct key *dest_keyring = *_dest_keyring, *authkey; 258 struct key *dest_keyring = *_dest_keyring, *authkey;
259 int ret;
259 260
260 kenter("%p", dest_keyring); 261 kenter("%p", dest_keyring);
261 262
@@ -264,6 +265,8 @@ static void construct_get_dest_keyring(struct key **_dest_keyring)
264 /* the caller supplied one */ 265 /* the caller supplied one */
265 key_get(dest_keyring); 266 key_get(dest_keyring);
266 } else { 267 } else {
268 bool do_perm_check = true;
269
267 /* use a default keyring; falling through the cases until we 270 /* use a default keyring; falling through the cases until we
268 * find one that we actually have */ 271 * find one that we actually have */
269 switch (cred->jit_keyring) { 272 switch (cred->jit_keyring) {
@@ -278,8 +281,10 @@ static void construct_get_dest_keyring(struct key **_dest_keyring)
278 dest_keyring = 281 dest_keyring =
279 key_get(rka->dest_keyring); 282 key_get(rka->dest_keyring);
280 up_read(&authkey->sem); 283 up_read(&authkey->sem);
281 if (dest_keyring) 284 if (dest_keyring) {
285 do_perm_check = false;
282 break; 286 break;
287 }
283 } 288 }
284 289
285 case KEY_REQKEY_DEFL_THREAD_KEYRING: 290 case KEY_REQKEY_DEFL_THREAD_KEYRING:
@@ -314,11 +319,29 @@ static void construct_get_dest_keyring(struct key **_dest_keyring)
314 default: 319 default:
315 BUG(); 320 BUG();
316 } 321 }
322
323 /*
324 * Require Write permission on the keyring. This is essential
325 * because the default keyring may be the session keyring, and
326 * joining a keyring only requires Search permission.
327 *
328 * However, this check is skipped for the "requestor keyring" so
329 * that /sbin/request-key can itself use request_key() to add
330 * keys to the original requestor's destination keyring.
331 */
332 if (dest_keyring && do_perm_check) {
333 ret = key_permission(make_key_ref(dest_keyring, 1),
334 KEY_NEED_WRITE);
335 if (ret) {
336 key_put(dest_keyring);
337 return ret;
338 }
339 }
317 } 340 }
318 341
319 *_dest_keyring = dest_keyring; 342 *_dest_keyring = dest_keyring;
320 kleave(" [dk %d]", key_serial(dest_keyring)); 343 kleave(" [dk %d]", key_serial(dest_keyring));
321 return; 344 return 0;
322} 345}
323 346
324/* 347/*
@@ -444,11 +467,15 @@ static struct key *construct_key_and_link(struct keyring_search_context *ctx,
444 if (ctx->index_key.type == &key_type_keyring) 467 if (ctx->index_key.type == &key_type_keyring)
445 return ERR_PTR(-EPERM); 468 return ERR_PTR(-EPERM);
446 469
447 user = key_user_lookup(current_fsuid()); 470 ret = construct_get_dest_keyring(&dest_keyring);
448 if (!user) 471 if (ret)
449 return ERR_PTR(-ENOMEM); 472 goto error;
450 473
451 construct_get_dest_keyring(&dest_keyring); 474 user = key_user_lookup(current_fsuid());
475 if (!user) {
476 ret = -ENOMEM;
477 goto error_put_dest_keyring;
478 }
452 479
453 ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); 480 ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);
454 key_user_put(user); 481 key_user_put(user);
@@ -463,7 +490,7 @@ static struct key *construct_key_and_link(struct keyring_search_context *ctx,
463 } else if (ret == -EINPROGRESS) { 490 } else if (ret == -EINPROGRESS) {
464 ret = 0; 491 ret = 0;
465 } else { 492 } else {
466 goto couldnt_alloc_key; 493 goto error_put_dest_keyring;
467 } 494 }
468 495
469 key_put(dest_keyring); 496 key_put(dest_keyring);
@@ -473,8 +500,9 @@ static struct key *construct_key_and_link(struct keyring_search_context *ctx,
473construction_failed: 500construction_failed:
474 key_negate_and_link(key, key_negative_timeout, NULL, NULL); 501 key_negate_and_link(key, key_negative_timeout, NULL, NULL);
475 key_put(key); 502 key_put(key);
476couldnt_alloc_key: 503error_put_dest_keyring:
477 key_put(dest_keyring); 504 key_put(dest_keyring);
505error:
478 kleave(" = %d", ret); 506 kleave(" = %d", ret);
479 return ERR_PTR(ret); 507 return ERR_PTR(ret);
480} 508}
@@ -546,9 +574,7 @@ struct key *request_key_and_link(struct key_type *type,
546 if (!IS_ERR(key_ref)) { 574 if (!IS_ERR(key_ref)) {
547 key = key_ref_to_ptr(key_ref); 575 key = key_ref_to_ptr(key_ref);
548 if (dest_keyring) { 576 if (dest_keyring) {
549 construct_get_dest_keyring(&dest_keyring);
550 ret = key_link(dest_keyring, key); 577 ret = key_link(dest_keyring, key);
551 key_put(dest_keyring);
552 if (ret < 0) { 578 if (ret < 0) {
553 key_put(key); 579 key_put(key);
554 key = ERR_PTR(ret); 580 key = ERR_PTR(ret);
@@ -595,10 +621,9 @@ int wait_for_key_construction(struct key *key, bool intr)
595 intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); 621 intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
596 if (ret) 622 if (ret)
597 return -ERESTARTSYS; 623 return -ERESTARTSYS;
598 if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) { 624 ret = key_read_state(key);
599 smp_rmb(); 625 if (ret < 0)
600 return key->reject_error; 626 return ret;
601 }
602 return key_validate(key); 627 return key_validate(key);
603} 628}
604EXPORT_SYMBOL(wait_for_key_construction); 629EXPORT_SYMBOL(wait_for_key_construction);
diff --git a/security/keys/request_key_auth.c b/security/keys/request_key_auth.c
index afe9d22ab361..424e1d90412e 100644
--- a/security/keys/request_key_auth.c
+++ b/security/keys/request_key_auth.c
@@ -73,7 +73,7 @@ static void request_key_auth_describe(const struct key *key,
73 73
74 seq_puts(m, "key:"); 74 seq_puts(m, "key:");
75 seq_puts(m, key->description); 75 seq_puts(m, key->description);
76 if (key_is_instantiated(key)) 76 if (key_is_positive(key))
77 seq_printf(m, " pid:%d ci:%zu", rka->pid, rka->callout_len); 77 seq_printf(m, " pid:%d ci:%zu", rka->pid, rka->callout_len);
78} 78}
79 79
@@ -120,6 +120,18 @@ static void request_key_auth_revoke(struct key *key)
120 } 120 }
121} 121}
122 122
123static void free_request_key_auth(struct request_key_auth *rka)
124{
125 if (!rka)
126 return;
127 key_put(rka->target_key);
128 key_put(rka->dest_keyring);
129 if (rka->cred)
130 put_cred(rka->cred);
131 kfree(rka->callout_info);
132 kfree(rka);
133}
134
123/* 135/*
124 * Destroy an instantiation authorisation token key. 136 * Destroy an instantiation authorisation token key.
125 */ 137 */
@@ -129,15 +141,7 @@ static void request_key_auth_destroy(struct key *key)
129 141
130 kenter("{%d}", key->serial); 142 kenter("{%d}", key->serial);
131 143
132 if (rka->cred) { 144 free_request_key_auth(rka);
133 put_cred(rka->cred);
134 rka->cred = NULL;
135 }
136
137 key_put(rka->target_key);
138 key_put(rka->dest_keyring);
139 kfree(rka->callout_info);
140 kfree(rka);
141} 145}
142 146
143/* 147/*
@@ -151,22 +155,18 @@ struct key *request_key_auth_new(struct key *target, const void *callout_info,
151 const struct cred *cred = current->cred; 155 const struct cred *cred = current->cred;
152 struct key *authkey = NULL; 156 struct key *authkey = NULL;
153 char desc[20]; 157 char desc[20];
154 int ret; 158 int ret = -ENOMEM;
155 159
156 kenter("%d,", target->serial); 160 kenter("%d,", target->serial);
157 161
158 /* allocate a auth record */ 162 /* allocate a auth record */
159 rka = kmalloc(sizeof(*rka), GFP_KERNEL); 163 rka = kzalloc(sizeof(*rka), GFP_KERNEL);
160 if (!rka) { 164 if (!rka)
161 kleave(" = -ENOMEM"); 165 goto error;
162 return ERR_PTR(-ENOMEM); 166 rka->callout_info = kmemdup(callout_info, callout_len, GFP_KERNEL);
163 } 167 if (!rka->callout_info)
164 rka->callout_info = kmalloc(callout_len, GFP_KERNEL); 168 goto error_free_rka;
165 if (!rka->callout_info) { 169 rka->callout_len = callout_len;
166 kleave(" = -ENOMEM");
167 kfree(rka);
168 return ERR_PTR(-ENOMEM);
169 }
170 170
171 /* see if the calling process is already servicing the key request of 171 /* see if the calling process is already servicing the key request of
172 * another process */ 172 * another process */
@@ -176,8 +176,12 @@ struct key *request_key_auth_new(struct key *target, const void *callout_info,
176 176
177 /* if the auth key has been revoked, then the key we're 177 /* if the auth key has been revoked, then the key we're
178 * servicing is already instantiated */ 178 * servicing is already instantiated */
179 if (test_bit(KEY_FLAG_REVOKED, &cred->request_key_auth->flags)) 179 if (test_bit(KEY_FLAG_REVOKED,
180 goto auth_key_revoked; 180 &cred->request_key_auth->flags)) {
181 up_read(&cred->request_key_auth->sem);
182 ret = -EKEYREVOKED;
183 goto error_free_rka;
184 }
181 185
182 irka = cred->request_key_auth->payload.data[0]; 186 irka = cred->request_key_auth->payload.data[0];
183 rka->cred = get_cred(irka->cred); 187 rka->cred = get_cred(irka->cred);
@@ -193,8 +197,6 @@ struct key *request_key_auth_new(struct key *target, const void *callout_info,
193 197
194 rka->target_key = key_get(target); 198 rka->target_key = key_get(target);
195 rka->dest_keyring = key_get(dest_keyring); 199 rka->dest_keyring = key_get(dest_keyring);
196 memcpy(rka->callout_info, callout_info, callout_len);
197 rka->callout_len = callout_len;
198 200
199 /* allocate the auth key */ 201 /* allocate the auth key */
200 sprintf(desc, "%x", target->serial); 202 sprintf(desc, "%x", target->serial);
@@ -205,32 +207,22 @@ struct key *request_key_auth_new(struct key *target, const void *callout_info,
205 KEY_USR_VIEW, KEY_ALLOC_NOT_IN_QUOTA, NULL); 207 KEY_USR_VIEW, KEY_ALLOC_NOT_IN_QUOTA, NULL);
206 if (IS_ERR(authkey)) { 208 if (IS_ERR(authkey)) {
207 ret = PTR_ERR(authkey); 209 ret = PTR_ERR(authkey);
208 goto error_alloc; 210 goto error_free_rka;
209 } 211 }
210 212
211 /* construct the auth key */ 213 /* construct the auth key */
212 ret = key_instantiate_and_link(authkey, rka, 0, NULL, NULL); 214 ret = key_instantiate_and_link(authkey, rka, 0, NULL, NULL);
213 if (ret < 0) 215 if (ret < 0)
214 goto error_inst; 216 goto error_put_authkey;
215 217
216 kleave(" = {%d,%d}", authkey->serial, refcount_read(&authkey->usage)); 218 kleave(" = {%d,%d}", authkey->serial, refcount_read(&authkey->usage));
217 return authkey; 219 return authkey;
218 220
219auth_key_revoked: 221error_put_authkey:
220 up_read(&cred->request_key_auth->sem);
221 kfree(rka->callout_info);
222 kfree(rka);
223 kleave("= -EKEYREVOKED");
224 return ERR_PTR(-EKEYREVOKED);
225
226error_inst:
227 key_revoke(authkey);
228 key_put(authkey); 222 key_put(authkey);
229error_alloc: 223error_free_rka:
230 key_put(rka->target_key); 224 free_request_key_auth(rka);
231 key_put(rka->dest_keyring); 225error:
232 kfree(rka->callout_info);
233 kfree(rka);
234 kleave("= %d", ret); 226 kleave("= %d", ret);
235 return ERR_PTR(ret); 227 return ERR_PTR(ret);
236} 228}
diff --git a/security/keys/trusted.c b/security/keys/trusted.c
index ddfaebf60fc8..98aa89ff7bfd 100644
--- a/security/keys/trusted.c
+++ b/security/keys/trusted.c
@@ -1066,7 +1066,7 @@ static int trusted_update(struct key *key, struct key_preparsed_payload *prep)
1066 char *datablob; 1066 char *datablob;
1067 int ret = 0; 1067 int ret = 0;
1068 1068
1069 if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) 1069 if (key_is_negative(key))
1070 return -ENOKEY; 1070 return -ENOKEY;
1071 p = key->payload.data[0]; 1071 p = key->payload.data[0];
1072 if (!p->migratable) 1072 if (!p->migratable)
@@ -1147,20 +1147,21 @@ static long trusted_read(const struct key *key, char __user *buffer,
1147 p = dereference_key_locked(key); 1147 p = dereference_key_locked(key);
1148 if (!p) 1148 if (!p)
1149 return -EINVAL; 1149 return -EINVAL;
1150 if (!buffer || buflen <= 0)
1151 return 2 * p->blob_len;
1152 ascii_buf = kmalloc(2 * p->blob_len, GFP_KERNEL);
1153 if (!ascii_buf)
1154 return -ENOMEM;
1155 1150
1156 bufp = ascii_buf; 1151 if (buffer && buflen >= 2 * p->blob_len) {
1157 for (i = 0; i < p->blob_len; i++) 1152 ascii_buf = kmalloc(2 * p->blob_len, GFP_KERNEL);
1158 bufp = hex_byte_pack(bufp, p->blob[i]); 1153 if (!ascii_buf)
1159 if ((copy_to_user(buffer, ascii_buf, 2 * p->blob_len)) != 0) { 1154 return -ENOMEM;
1155
1156 bufp = ascii_buf;
1157 for (i = 0; i < p->blob_len; i++)
1158 bufp = hex_byte_pack(bufp, p->blob[i]);
1159 if (copy_to_user(buffer, ascii_buf, 2 * p->blob_len) != 0) {
1160 kzfree(ascii_buf);
1161 return -EFAULT;
1162 }
1160 kzfree(ascii_buf); 1163 kzfree(ascii_buf);
1161 return -EFAULT;
1162 } 1164 }
1163 kzfree(ascii_buf);
1164 return 2 * p->blob_len; 1165 return 2 * p->blob_len;
1165} 1166}
1166 1167
diff --git a/security/keys/trusted.h b/security/keys/trusted.h
index ff001a5dcb24..8d5fe9eafb22 100644
--- a/security/keys/trusted.h
+++ b/security/keys/trusted.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1#ifndef __TRUSTED_KEY_H 2#ifndef __TRUSTED_KEY_H
2#define __TRUSTED_KEY_H 3#define __TRUSTED_KEY_H
3 4
diff --git a/security/keys/user_defined.c b/security/keys/user_defined.c
index 3d8c68eba516..9f558bedba23 100644
--- a/security/keys/user_defined.c
+++ b/security/keys/user_defined.c
@@ -114,7 +114,7 @@ int user_update(struct key *key, struct key_preparsed_payload *prep)
114 114
115 /* attach the new data, displacing the old */ 115 /* attach the new data, displacing the old */
116 key->expiry = prep->expiry; 116 key->expiry = prep->expiry;
117 if (!test_bit(KEY_FLAG_NEGATIVE, &key->flags)) 117 if (key_is_positive(key))
118 zap = dereference_key_locked(key); 118 zap = dereference_key_locked(key);
119 rcu_assign_keypointer(key, prep->payload.data[0]); 119 rcu_assign_keypointer(key, prep->payload.data[0]);
120 prep->payload.data[0] = NULL; 120 prep->payload.data[0] = NULL;
@@ -162,7 +162,7 @@ EXPORT_SYMBOL_GPL(user_destroy);
162void user_describe(const struct key *key, struct seq_file *m) 162void user_describe(const struct key *key, struct seq_file *m)
163{ 163{
164 seq_puts(m, key->description); 164 seq_puts(m, key->description);
165 if (key_is_instantiated(key)) 165 if (key_is_positive(key))
166 seq_printf(m, ": %u", key->datalen); 166 seq_printf(m, ": %u", key->datalen);
167} 167}
168 168
diff --git a/security/min_addr.c b/security/min_addr.c
index f728728f193b..94d2b0cf0e7b 100644
--- a/security/min_addr.c
+++ b/security/min_addr.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1#include <linux/init.h> 2#include <linux/init.h>
2#include <linux/mm.h> 3#include <linux/mm.h>
3#include <linux/security.h> 4#include <linux/security.h>
diff --git a/security/security.c b/security/security.c
index 4bf0f571b4ef..1cd8526cb0b7 100644
--- a/security/security.c
+++ b/security/security.c
@@ -12,6 +12,7 @@
12 * (at your option) any later version. 12 * (at your option) any later version.
13 */ 13 */
14 14
15#include <linux/bpf.h>
15#include <linux/capability.h> 16#include <linux/capability.h>
16#include <linux/dcache.h> 17#include <linux/dcache.h>
17#include <linux/module.h> 18#include <linux/module.h>
@@ -1703,3 +1704,34 @@ int security_audit_rule_match(u32 secid, u32 field, u32 op, void *lsmrule,
1703 actx); 1704 actx);
1704} 1705}
1705#endif /* CONFIG_AUDIT */ 1706#endif /* CONFIG_AUDIT */
1707
1708#ifdef CONFIG_BPF_SYSCALL
1709int security_bpf(int cmd, union bpf_attr *attr, unsigned int size)
1710{
1711 return call_int_hook(bpf, 0, cmd, attr, size);
1712}
1713int security_bpf_map(struct bpf_map *map, fmode_t fmode)
1714{
1715 return call_int_hook(bpf_map, 0, map, fmode);
1716}
1717int security_bpf_prog(struct bpf_prog *prog)
1718{
1719 return call_int_hook(bpf_prog, 0, prog);
1720}
1721int security_bpf_map_alloc(struct bpf_map *map)
1722{
1723 return call_int_hook(bpf_map_alloc_security, 0, map);
1724}
1725int security_bpf_prog_alloc(struct bpf_prog_aux *aux)
1726{
1727 return call_int_hook(bpf_prog_alloc_security, 0, aux);
1728}
1729void security_bpf_map_free(struct bpf_map *map)
1730{
1731 call_void_hook(bpf_map_free_security, map);
1732}
1733void security_bpf_prog_free(struct bpf_prog_aux *aux)
1734{
1735 call_void_hook(bpf_prog_free_security, aux);
1736}
1737#endif /* CONFIG_BPF_SYSCALL */
diff --git a/security/selinux/Makefile b/security/selinux/Makefile
index ff5895ede96f..c7161f8792b2 100644
--- a/security/selinux/Makefile
+++ b/security/selinux/Makefile
@@ -1,3 +1,4 @@
1# SPDX-License-Identifier: GPL-2.0
1# 2#
2# Makefile for building the SELinux module as part of the kernel tree. 3# Makefile for building the SELinux module as part of the kernel tree.
3# 4#
diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index f5d304736852..8644d864e3c1 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -85,6 +85,7 @@
85#include <linux/export.h> 85#include <linux/export.h>
86#include <linux/msg.h> 86#include <linux/msg.h>
87#include <linux/shm.h> 87#include <linux/shm.h>
88#include <linux/bpf.h>
88 89
89#include "avc.h" 90#include "avc.h"
90#include "objsec.h" 91#include "objsec.h"
@@ -1814,6 +1815,10 @@ static inline int file_path_has_perm(const struct cred *cred,
1814 return inode_has_perm(cred, file_inode(file), av, &ad); 1815 return inode_has_perm(cred, file_inode(file), av, &ad);
1815} 1816}
1816 1817
1818#ifdef CONFIG_BPF_SYSCALL
1819static int bpf_fd_pass(struct file *file, u32 sid);
1820#endif
1821
1817/* Check whether a task can use an open file descriptor to 1822/* Check whether a task can use an open file descriptor to
1818 access an inode in a given way. Check access to the 1823 access an inode in a given way. Check access to the
1819 descriptor itself, and then use dentry_has_perm to 1824 descriptor itself, and then use dentry_has_perm to
@@ -1844,6 +1849,12 @@ static int file_has_perm(const struct cred *cred,
1844 goto out; 1849 goto out;
1845 } 1850 }
1846 1851
1852#ifdef CONFIG_BPF_SYSCALL
1853 rc = bpf_fd_pass(file, cred_sid(cred));
1854 if (rc)
1855 return rc;
1856#endif
1857
1847 /* av is zero if only checking access to the descriptor. */ 1858 /* av is zero if only checking access to the descriptor. */
1848 rc = 0; 1859 rc = 0;
1849 if (av) 1860 if (av)
@@ -2164,6 +2175,12 @@ static int selinux_binder_transfer_file(struct task_struct *from,
2164 return rc; 2175 return rc;
2165 } 2176 }
2166 2177
2178#ifdef CONFIG_BPF_SYSCALL
2179 rc = bpf_fd_pass(file, sid);
2180 if (rc)
2181 return rc;
2182#endif
2183
2167 if (unlikely(IS_PRIVATE(d_backing_inode(dentry)))) 2184 if (unlikely(IS_PRIVATE(d_backing_inode(dentry))))
2168 return 0; 2185 return 0;
2169 2186
@@ -2918,13 +2935,12 @@ static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2918{ 2935{
2919 const struct task_security_struct *tsec = current_security(); 2936 const struct task_security_struct *tsec = current_security();
2920 struct superblock_security_struct *sbsec; 2937 struct superblock_security_struct *sbsec;
2921 u32 sid, newsid, clen; 2938 u32 newsid, clen;
2922 int rc; 2939 int rc;
2923 char *context; 2940 char *context;
2924 2941
2925 sbsec = dir->i_sb->s_security; 2942 sbsec = dir->i_sb->s_security;
2926 2943
2927 sid = tsec->sid;
2928 newsid = tsec->create_sid; 2944 newsid = tsec->create_sid;
2929 2945
2930 rc = selinux_determine_inode_label(current_security(), 2946 rc = selinux_determine_inode_label(current_security(),
@@ -3124,27 +3140,6 @@ static int selinux_inode_getattr(const struct path *path)
3124 return path_has_perm(current_cred(), path, FILE__GETATTR); 3140 return path_has_perm(current_cred(), path, FILE__GETATTR);
3125} 3141}
3126 3142
3127static int selinux_inode_setotherxattr(struct dentry *dentry, const char *name)
3128{
3129 const struct cred *cred = current_cred();
3130
3131 if (!strncmp(name, XATTR_SECURITY_PREFIX,
3132 sizeof XATTR_SECURITY_PREFIX - 1)) {
3133 if (!strcmp(name, XATTR_NAME_CAPS)) {
3134 if (!capable(CAP_SETFCAP))
3135 return -EPERM;
3136 } else if (!capable(CAP_SYS_ADMIN)) {
3137 /* A different attribute in the security namespace.
3138 Restrict to administrator. */
3139 return -EPERM;
3140 }
3141 }
3142
3143 /* Not an attribute we recognize, so just check the
3144 ordinary setattr permission. */
3145 return dentry_has_perm(cred, dentry, FILE__SETATTR);
3146}
3147
3148static bool has_cap_mac_admin(bool audit) 3143static bool has_cap_mac_admin(bool audit)
3149{ 3144{
3150 const struct cred *cred = current_cred(); 3145 const struct cred *cred = current_cred();
@@ -3167,8 +3162,15 @@ static int selinux_inode_setxattr(struct dentry *dentry, const char *name,
3167 u32 newsid, sid = current_sid(); 3162 u32 newsid, sid = current_sid();
3168 int rc = 0; 3163 int rc = 0;
3169 3164
3170 if (strcmp(name, XATTR_NAME_SELINUX)) 3165 if (strcmp(name, XATTR_NAME_SELINUX)) {
3171 return selinux_inode_setotherxattr(dentry, name); 3166 rc = cap_inode_setxattr(dentry, name, value, size, flags);
3167 if (rc)
3168 return rc;
3169
3170 /* Not an attribute we recognize, so just check the
3171 ordinary setattr permission. */
3172 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3173 }
3172 3174
3173 sbsec = inode->i_sb->s_security; 3175 sbsec = inode->i_sb->s_security;
3174 if (!(sbsec->flags & SBLABEL_MNT)) 3176 if (!(sbsec->flags & SBLABEL_MNT))
@@ -3191,18 +3193,17 @@ static int selinux_inode_setxattr(struct dentry *dentry, const char *name,
3191 if (!has_cap_mac_admin(true)) { 3193 if (!has_cap_mac_admin(true)) {
3192 struct audit_buffer *ab; 3194 struct audit_buffer *ab;
3193 size_t audit_size; 3195 size_t audit_size;
3194 const char *str;
3195 3196
3196 /* We strip a nul only if it is at the end, otherwise the 3197 /* We strip a nul only if it is at the end, otherwise the
3197 * context contains a nul and we should audit that */ 3198 * context contains a nul and we should audit that */
3198 if (value) { 3199 if (value) {
3199 str = value; 3200 const char *str = value;
3201
3200 if (str[size - 1] == '\0') 3202 if (str[size - 1] == '\0')
3201 audit_size = size - 1; 3203 audit_size = size - 1;
3202 else 3204 else
3203 audit_size = size; 3205 audit_size = size;
3204 } else { 3206 } else {
3205 str = "";
3206 audit_size = 0; 3207 audit_size = 0;
3207 } 3208 }
3208 ab = audit_log_start(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR); 3209 ab = audit_log_start(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR);
@@ -3282,8 +3283,15 @@ static int selinux_inode_listxattr(struct dentry *dentry)
3282 3283
3283static int selinux_inode_removexattr(struct dentry *dentry, const char *name) 3284static int selinux_inode_removexattr(struct dentry *dentry, const char *name)
3284{ 3285{
3285 if (strcmp(name, XATTR_NAME_SELINUX)) 3286 if (strcmp(name, XATTR_NAME_SELINUX)) {
3286 return selinux_inode_setotherxattr(dentry, name); 3287 int rc = cap_inode_removexattr(dentry, name);
3288 if (rc)
3289 return rc;
3290
3291 /* Not an attribute we recognize, so just check the
3292 ordinary setattr permission. */
3293 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3294 }
3287 3295
3288 /* No one is allowed to remove a SELinux security label. 3296 /* No one is allowed to remove a SELinux security label.
3289 You can change the label, but all data must be labeled. */ 3297 You can change the label, but all data must be labeled. */
@@ -3978,8 +3986,8 @@ static int selinux_task_getioprio(struct task_struct *p)
3978 PROCESS__GETSCHED, NULL); 3986 PROCESS__GETSCHED, NULL);
3979} 3987}
3980 3988
3981int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred, 3989static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
3982 unsigned int flags) 3990 unsigned int flags)
3983{ 3991{
3984 u32 av = 0; 3992 u32 av = 0;
3985 3993
@@ -6252,6 +6260,139 @@ static void selinux_ib_free_security(void *ib_sec)
6252} 6260}
6253#endif 6261#endif
6254 6262
6263#ifdef CONFIG_BPF_SYSCALL
6264static int selinux_bpf(int cmd, union bpf_attr *attr,
6265 unsigned int size)
6266{
6267 u32 sid = current_sid();
6268 int ret;
6269
6270 switch (cmd) {
6271 case BPF_MAP_CREATE:
6272 ret = avc_has_perm(sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
6273 NULL);
6274 break;
6275 case BPF_PROG_LOAD:
6276 ret = avc_has_perm(sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
6277 NULL);
6278 break;
6279 default:
6280 ret = 0;
6281 break;
6282 }
6283
6284 return ret;
6285}
6286
6287static u32 bpf_map_fmode_to_av(fmode_t fmode)
6288{
6289 u32 av = 0;
6290
6291 if (fmode & FMODE_READ)
6292 av |= BPF__MAP_READ;
6293 if (fmode & FMODE_WRITE)
6294 av |= BPF__MAP_WRITE;
6295 return av;
6296}
6297
6298/* This function will check the file pass through unix socket or binder to see
6299 * if it is a bpf related object. And apply correspinding checks on the bpf
6300 * object based on the type. The bpf maps and programs, not like other files and
6301 * socket, are using a shared anonymous inode inside the kernel as their inode.
6302 * So checking that inode cannot identify if the process have privilege to
6303 * access the bpf object and that's why we have to add this additional check in
6304 * selinux_file_receive and selinux_binder_transfer_files.
6305 */
6306static int bpf_fd_pass(struct file *file, u32 sid)
6307{
6308 struct bpf_security_struct *bpfsec;
6309 struct bpf_prog *prog;
6310 struct bpf_map *map;
6311 int ret;
6312
6313 if (file->f_op == &bpf_map_fops) {
6314 map = file->private_data;
6315 bpfsec = map->security;
6316 ret = avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
6317 bpf_map_fmode_to_av(file->f_mode), NULL);
6318 if (ret)
6319 return ret;
6320 } else if (file->f_op == &bpf_prog_fops) {
6321 prog = file->private_data;
6322 bpfsec = prog->aux->security;
6323 ret = avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
6324 BPF__PROG_RUN, NULL);
6325 if (ret)
6326 return ret;
6327 }
6328 return 0;
6329}
6330
6331static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
6332{
6333 u32 sid = current_sid();
6334 struct bpf_security_struct *bpfsec;
6335
6336 bpfsec = map->security;
6337 return avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
6338 bpf_map_fmode_to_av(fmode), NULL);
6339}
6340
6341static int selinux_bpf_prog(struct bpf_prog *prog)
6342{
6343 u32 sid = current_sid();
6344 struct bpf_security_struct *bpfsec;
6345
6346 bpfsec = prog->aux->security;
6347 return avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
6348 BPF__PROG_RUN, NULL);
6349}
6350
6351static int selinux_bpf_map_alloc(struct bpf_map *map)
6352{
6353 struct bpf_security_struct *bpfsec;
6354
6355 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6356 if (!bpfsec)
6357 return -ENOMEM;
6358
6359 bpfsec->sid = current_sid();
6360 map->security = bpfsec;
6361
6362 return 0;
6363}
6364
6365static void selinux_bpf_map_free(struct bpf_map *map)
6366{
6367 struct bpf_security_struct *bpfsec = map->security;
6368
6369 map->security = NULL;
6370 kfree(bpfsec);
6371}
6372
6373static int selinux_bpf_prog_alloc(struct bpf_prog_aux *aux)
6374{
6375 struct bpf_security_struct *bpfsec;
6376
6377 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6378 if (!bpfsec)
6379 return -ENOMEM;
6380
6381 bpfsec->sid = current_sid();
6382 aux->security = bpfsec;
6383
6384 return 0;
6385}
6386
6387static void selinux_bpf_prog_free(struct bpf_prog_aux *aux)
6388{
6389 struct bpf_security_struct *bpfsec = aux->security;
6390
6391 aux->security = NULL;
6392 kfree(bpfsec);
6393}
6394#endif
6395
6255static struct security_hook_list selinux_hooks[] __lsm_ro_after_init = { 6396static struct security_hook_list selinux_hooks[] __lsm_ro_after_init = {
6256 LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr), 6397 LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
6257 LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction), 6398 LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
@@ -6471,6 +6612,16 @@ static struct security_hook_list selinux_hooks[] __lsm_ro_after_init = {
6471 LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match), 6612 LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
6472 LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free), 6613 LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
6473#endif 6614#endif
6615
6616#ifdef CONFIG_BPF_SYSCALL
6617 LSM_HOOK_INIT(bpf, selinux_bpf),
6618 LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
6619 LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
6620 LSM_HOOK_INIT(bpf_map_alloc_security, selinux_bpf_map_alloc),
6621 LSM_HOOK_INIT(bpf_prog_alloc_security, selinux_bpf_prog_alloc),
6622 LSM_HOOK_INIT(bpf_map_free_security, selinux_bpf_map_free),
6623 LSM_HOOK_INIT(bpf_prog_free_security, selinux_bpf_prog_free),
6624#endif
6474}; 6625};
6475 6626
6476static __init int selinux_init(void) 6627static __init int selinux_init(void)
diff --git a/security/selinux/include/avc.h b/security/selinux/include/avc.h
index a5004e9de11a..57d61cf36500 100644
--- a/security/selinux/include/avc.h
+++ b/security/selinux/include/avc.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * Access vector cache interface for object managers. 3 * Access vector cache interface for object managers.
3 * 4 *
diff --git a/security/selinux/include/avc_ss.h b/security/selinux/include/avc_ss.h
index 37d57dadd476..3bcc72769b87 100644
--- a/security/selinux/include/avc_ss.h
+++ b/security/selinux/include/avc_ss.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * Access vector cache interface for the security server. 3 * Access vector cache interface for the security server.
3 * 4 *
diff --git a/security/selinux/include/classmap.h b/security/selinux/include/classmap.h
index 35ffb29a69cb..acdee7795297 100644
--- a/security/selinux/include/classmap.h
+++ b/security/selinux/include/classmap.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1#include <linux/capability.h> 2#include <linux/capability.h>
2 3
3#define COMMON_FILE_SOCK_PERMS "ioctl", "read", "write", "create", \ 4#define COMMON_FILE_SOCK_PERMS "ioctl", "read", "write", "create", \
@@ -237,6 +238,8 @@ struct security_class_mapping secclass_map[] = {
237 { "access", NULL } }, 238 { "access", NULL } },
238 { "infiniband_endport", 239 { "infiniband_endport",
239 { "manage_subnet", NULL } }, 240 { "manage_subnet", NULL } },
241 { "bpf",
242 {"map_create", "map_read", "map_write", "prog_load", "prog_run"} },
240 { NULL } 243 { NULL }
241 }; 244 };
242 245
diff --git a/security/selinux/include/initial_sid_to_string.h b/security/selinux/include/initial_sid_to_string.h
index a59b64e3fd02..4f93f697f71c 100644
--- a/security/selinux/include/initial_sid_to_string.h
+++ b/security/selinux/include/initial_sid_to_string.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* This file is automatically generated. Do not edit. */ 2/* This file is automatically generated. Do not edit. */
2static const char *initial_sid_to_string[] = 3static const char *initial_sid_to_string[] =
3{ 4{
diff --git a/security/selinux/include/objsec.h b/security/selinux/include/objsec.h
index 1649cd18eb0b..3d54468ce334 100644
--- a/security/selinux/include/objsec.h
+++ b/security/selinux/include/objsec.h
@@ -150,6 +150,10 @@ struct pkey_security_struct {
150 u32 sid; /* SID of pkey */ 150 u32 sid; /* SID of pkey */
151}; 151};
152 152
153struct bpf_security_struct {
154 u32 sid; /*SID of bpf obj creater*/
155};
156
153extern unsigned int selinux_checkreqprot; 157extern unsigned int selinux_checkreqprot;
154 158
155#endif /* _SELINUX_OBJSEC_H_ */ 159#endif /* _SELINUX_OBJSEC_H_ */
diff --git a/security/selinux/include/security.h b/security/selinux/include/security.h
index 28dfb2f93e4d..02f0412d42f2 100644
--- a/security/selinux/include/security.h
+++ b/security/selinux/include/security.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * Security server interface. 3 * Security server interface.
3 * 4 *
diff --git a/security/selinux/include/xfrm.h b/security/selinux/include/xfrm.h
index 36a7ce9e11ff..1f173a7a4daa 100644
--- a/security/selinux/include/xfrm.h
+++ b/security/selinux/include/xfrm.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * SELinux support for the XFRM LSM hooks 3 * SELinux support for the XFRM LSM hooks
3 * 4 *
diff --git a/security/selinux/ss/conditional.c b/security/selinux/ss/conditional.c
index 771c96afe1d5..c91543a617ac 100644
--- a/security/selinux/ss/conditional.c
+++ b/security/selinux/ss/conditional.c
@@ -361,7 +361,6 @@ static int cond_read_av_list(struct policydb *p, void *fp, struct cond_av_list *
361 361
362 *ret_list = NULL; 362 *ret_list = NULL;
363 363
364 len = 0;
365 rc = next_entry(buf, fp, sizeof(u32)); 364 rc = next_entry(buf, fp, sizeof(u32));
366 if (rc) 365 if (rc)
367 return rc; 366 return rc;
diff --git a/security/selinux/ss/constraint.h b/security/selinux/ss/constraint.h
index 33ae2aec4f36..4e563be9ef5f 100644
--- a/security/selinux/ss/constraint.h
+++ b/security/selinux/ss/constraint.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * A constraint is a condition that must be satisfied in 3 * A constraint is a condition that must be satisfied in
3 * order for one or more permissions to be granted. 4 * order for one or more permissions to be granted.
diff --git a/security/selinux/ss/context.h b/security/selinux/ss/context.h
index a2c0f37c42ae..2260c44a568c 100644
--- a/security/selinux/ss/context.h
+++ b/security/selinux/ss/context.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * A security context is a set of security attributes 3 * A security context is a set of security attributes
3 * associated with each subject and object controlled 4 * associated with each subject and object controlled
diff --git a/security/selinux/ss/ebitmap.c b/security/selinux/ss/ebitmap.c
index fc28149a4f2e..b6a78b09235c 100644
--- a/security/selinux/ss/ebitmap.c
+++ b/security/selinux/ss/ebitmap.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * Implementation of the extensible bitmap type. 3 * Implementation of the extensible bitmap type.
3 * 4 *
diff --git a/security/selinux/ss/ebitmap.h b/security/selinux/ss/ebitmap.h
index da1325dda550..edf4fa39c60a 100644
--- a/security/selinux/ss/ebitmap.h
+++ b/security/selinux/ss/ebitmap.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * An extensible bitmap is a bitmap that supports an 3 * An extensible bitmap is a bitmap that supports an
3 * arbitrary number of bits. Extensible bitmaps are 4 * arbitrary number of bits. Extensible bitmaps are
diff --git a/security/selinux/ss/hashtab.c b/security/selinux/ss/hashtab.c
index 686c3917064c..fe25b3fb2154 100644
--- a/security/selinux/ss/hashtab.c
+++ b/security/selinux/ss/hashtab.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * Implementation of the hash table type. 3 * Implementation of the hash table type.
3 * 4 *
@@ -9,6 +10,8 @@
9#include <linux/sched.h> 10#include <linux/sched.h>
10#include "hashtab.h" 11#include "hashtab.h"
11 12
13static struct kmem_cache *hashtab_node_cachep;
14
12struct hashtab *hashtab_create(u32 (*hash_value)(struct hashtab *h, const void *key), 15struct hashtab *hashtab_create(u32 (*hash_value)(struct hashtab *h, const void *key),
13 int (*keycmp)(struct hashtab *h, const void *key1, const void *key2), 16 int (*keycmp)(struct hashtab *h, const void *key1, const void *key2),
14 u32 size) 17 u32 size)
@@ -57,7 +60,7 @@ int hashtab_insert(struct hashtab *h, void *key, void *datum)
57 if (cur && (h->keycmp(h, key, cur->key) == 0)) 60 if (cur && (h->keycmp(h, key, cur->key) == 0))
58 return -EEXIST; 61 return -EEXIST;
59 62
60 newnode = kzalloc(sizeof(*newnode), GFP_KERNEL); 63 newnode = kmem_cache_zalloc(hashtab_node_cachep, GFP_KERNEL);
61 if (!newnode) 64 if (!newnode)
62 return -ENOMEM; 65 return -ENOMEM;
63 newnode->key = key; 66 newnode->key = key;
@@ -106,7 +109,7 @@ void hashtab_destroy(struct hashtab *h)
106 while (cur) { 109 while (cur) {
107 temp = cur; 110 temp = cur;
108 cur = cur->next; 111 cur = cur->next;
109 kfree(temp); 112 kmem_cache_free(hashtab_node_cachep, temp);
110 } 113 }
111 h->htable[i] = NULL; 114 h->htable[i] = NULL;
112 } 115 }
@@ -148,7 +151,7 @@ void hashtab_stat(struct hashtab *h, struct hashtab_info *info)
148 151
149 slots_used = 0; 152 slots_used = 0;
150 max_chain_len = 0; 153 max_chain_len = 0;
151 for (slots_used = max_chain_len = i = 0; i < h->size; i++) { 154 for (i = 0; i < h->size; i++) {
152 cur = h->htable[i]; 155 cur = h->htable[i];
153 if (cur) { 156 if (cur) {
154 slots_used++; 157 slots_used++;
@@ -166,3 +169,14 @@ void hashtab_stat(struct hashtab *h, struct hashtab_info *info)
166 info->slots_used = slots_used; 169 info->slots_used = slots_used;
167 info->max_chain_len = max_chain_len; 170 info->max_chain_len = max_chain_len;
168} 171}
172void hashtab_cache_init(void)
173{
174 hashtab_node_cachep = kmem_cache_create("hashtab_node",
175 sizeof(struct hashtab_node),
176 0, SLAB_PANIC, NULL);
177}
178
179void hashtab_cache_destroy(void)
180{
181 kmem_cache_destroy(hashtab_node_cachep);
182}
diff --git a/security/selinux/ss/hashtab.h b/security/selinux/ss/hashtab.h
index 009fb5e06172..6183ee2a2e7a 100644
--- a/security/selinux/ss/hashtab.h
+++ b/security/selinux/ss/hashtab.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * A hash table (hashtab) maintains associations between 3 * A hash table (hashtab) maintains associations between
3 * key values and datum values. The type of the key values 4 * key values and datum values. The type of the key values
@@ -84,4 +85,8 @@ int hashtab_map(struct hashtab *h,
84/* Fill info with some hash table statistics */ 85/* Fill info with some hash table statistics */
85void hashtab_stat(struct hashtab *h, struct hashtab_info *info); 86void hashtab_stat(struct hashtab *h, struct hashtab_info *info);
86 87
88/* Use kmem_cache for hashtab_node */
89void hashtab_cache_init(void);
90void hashtab_cache_destroy(void);
91
87#endif /* _SS_HASHTAB_H */ 92#endif /* _SS_HASHTAB_H */
diff --git a/security/selinux/ss/mls.c b/security/selinux/ss/mls.c
index d9dc34f4fade..ad982ce8bfa4 100644
--- a/security/selinux/ss/mls.c
+++ b/security/selinux/ss/mls.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * Implementation of the multi-level security (MLS) policy. 3 * Implementation of the multi-level security (MLS) policy.
3 * 4 *
diff --git a/security/selinux/ss/mls.h b/security/selinux/ss/mls.h
index 0f0a1d65b2ce..131d76266ea5 100644
--- a/security/selinux/ss/mls.h
+++ b/security/selinux/ss/mls.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * Multi-level security (MLS) policy operations. 3 * Multi-level security (MLS) policy operations.
3 * 4 *
diff --git a/security/selinux/ss/mls_types.h b/security/selinux/ss/mls_types.h
index 47f3702cd596..068e0d7809db 100644
--- a/security/selinux/ss/mls_types.h
+++ b/security/selinux/ss/mls_types.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * Type definitions for the multi-level security (MLS) policy. 3 * Type definitions for the multi-level security (MLS) policy.
3 * 4 *
diff --git a/security/selinux/ss/services.c b/security/selinux/ss/services.c
index e4a1c0dc561a..33cfe5d3d6cb 100644
--- a/security/selinux/ss/services.c
+++ b/security/selinux/ss/services.c
@@ -2060,10 +2060,12 @@ int security_load_policy(void *data, size_t len)
2060 if (!ss_initialized) { 2060 if (!ss_initialized) {
2061 avtab_cache_init(); 2061 avtab_cache_init();
2062 ebitmap_cache_init(); 2062 ebitmap_cache_init();
2063 hashtab_cache_init();
2063 rc = policydb_read(&policydb, fp); 2064 rc = policydb_read(&policydb, fp);
2064 if (rc) { 2065 if (rc) {
2065 avtab_cache_destroy(); 2066 avtab_cache_destroy();
2066 ebitmap_cache_destroy(); 2067 ebitmap_cache_destroy();
2068 hashtab_cache_destroy();
2067 goto out; 2069 goto out;
2068 } 2070 }
2069 2071
@@ -2075,6 +2077,7 @@ int security_load_policy(void *data, size_t len)
2075 policydb_destroy(&policydb); 2077 policydb_destroy(&policydb);
2076 avtab_cache_destroy(); 2078 avtab_cache_destroy();
2077 ebitmap_cache_destroy(); 2079 ebitmap_cache_destroy();
2080 hashtab_cache_destroy();
2078 goto out; 2081 goto out;
2079 } 2082 }
2080 2083
@@ -2083,6 +2086,7 @@ int security_load_policy(void *data, size_t len)
2083 policydb_destroy(&policydb); 2086 policydb_destroy(&policydb);
2084 avtab_cache_destroy(); 2087 avtab_cache_destroy();
2085 ebitmap_cache_destroy(); 2088 ebitmap_cache_destroy();
2089 hashtab_cache_destroy();
2086 goto out; 2090 goto out;
2087 } 2091 }
2088 2092
diff --git a/security/selinux/ss/services.h b/security/selinux/ss/services.h
index 3d9fa9556b4f..356bdd36cf6d 100644
--- a/security/selinux/ss/services.h
+++ b/security/selinux/ss/services.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * Implementation of the security services. 3 * Implementation of the security services.
3 * 4 *
diff --git a/security/selinux/ss/sidtab.c b/security/selinux/ss/sidtab.c
index 6ae08efc5ae7..5be31b7af225 100644
--- a/security/selinux/ss/sidtab.c
+++ b/security/selinux/ss/sidtab.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * Implementation of the SID table type. 3 * Implementation of the SID table type.
3 * 4 *
diff --git a/security/selinux/ss/sidtab.h b/security/selinux/ss/sidtab.h
index de5d0ea583d2..a1a1d2617b6f 100644
--- a/security/selinux/ss/sidtab.h
+++ b/security/selinux/ss/sidtab.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * A security identifier table (sidtab) is a hash table 3 * A security identifier table (sidtab) is a hash table
3 * of security context structures indexed by SID value. 4 * of security context structures indexed by SID value.
diff --git a/security/selinux/ss/symtab.c b/security/selinux/ss/symtab.c
index d1a6745849a7..dc2ce94165d3 100644
--- a/security/selinux/ss/symtab.c
+++ b/security/selinux/ss/symtab.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * Implementation of the symbol table type. 3 * Implementation of the symbol table type.
3 * 4 *
diff --git a/security/selinux/ss/symtab.h b/security/selinux/ss/symtab.h
index 0bc12d587d3a..d75fcafe7281 100644
--- a/security/selinux/ss/symtab.h
+++ b/security/selinux/ss/symtab.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * A symbol table (symtab) maintains associations between symbol 3 * A symbol table (symtab) maintains associations between symbol
3 * strings and datum values. The type of the datum values 4 * strings and datum values. The type of the datum values
diff --git a/security/smack/smack_lsm.c b/security/smack/smack_lsm.c
index 569f28034116..14cc7940b36d 100644
--- a/security/smack/smack_lsm.c
+++ b/security/smack/smack_lsm.c
@@ -1473,7 +1473,7 @@ static int smack_inode_removexattr(struct dentry *dentry, const char *name)
1473 * @inode: the object 1473 * @inode: the object
1474 * @name: attribute name 1474 * @name: attribute name
1475 * @buffer: where to put the result 1475 * @buffer: where to put the result
1476 * @alloc: unused 1476 * @alloc: duplicate memory
1477 * 1477 *
1478 * Returns the size of the attribute or an error code 1478 * Returns the size of the attribute or an error code
1479 */ 1479 */
@@ -1486,43 +1486,38 @@ static int smack_inode_getsecurity(struct inode *inode,
1486 struct super_block *sbp; 1486 struct super_block *sbp;
1487 struct inode *ip = (struct inode *)inode; 1487 struct inode *ip = (struct inode *)inode;
1488 struct smack_known *isp; 1488 struct smack_known *isp;
1489 int ilen;
1490 int rc = 0;
1491 1489
1492 if (strcmp(name, XATTR_SMACK_SUFFIX) == 0) { 1490 if (strcmp(name, XATTR_SMACK_SUFFIX) == 0)
1493 isp = smk_of_inode(inode); 1491 isp = smk_of_inode(inode);
1494 ilen = strlen(isp->smk_known); 1492 else {
1495 *buffer = isp->smk_known; 1493 /*
1496 return ilen; 1494 * The rest of the Smack xattrs are only on sockets.
1497 } 1495 */
1496 sbp = ip->i_sb;
1497 if (sbp->s_magic != SOCKFS_MAGIC)
1498 return -EOPNOTSUPP;
1498 1499
1499 /* 1500 sock = SOCKET_I(ip);
1500 * The rest of the Smack xattrs are only on sockets. 1501 if (sock == NULL || sock->sk == NULL)
1501 */ 1502 return -EOPNOTSUPP;
1502 sbp = ip->i_sb;
1503 if (sbp->s_magic != SOCKFS_MAGIC)
1504 return -EOPNOTSUPP;
1505 1503
1506 sock = SOCKET_I(ip); 1504 ssp = sock->sk->sk_security;
1507 if (sock == NULL || sock->sk == NULL)
1508 return -EOPNOTSUPP;
1509
1510 ssp = sock->sk->sk_security;
1511 1505
1512 if (strcmp(name, XATTR_SMACK_IPIN) == 0) 1506 if (strcmp(name, XATTR_SMACK_IPIN) == 0)
1513 isp = ssp->smk_in; 1507 isp = ssp->smk_in;
1514 else if (strcmp(name, XATTR_SMACK_IPOUT) == 0) 1508 else if (strcmp(name, XATTR_SMACK_IPOUT) == 0)
1515 isp = ssp->smk_out; 1509 isp = ssp->smk_out;
1516 else 1510 else
1517 return -EOPNOTSUPP; 1511 return -EOPNOTSUPP;
1512 }
1518 1513
1519 ilen = strlen(isp->smk_known); 1514 if (alloc) {
1520 if (rc == 0) { 1515 *buffer = kstrdup(isp->smk_known, GFP_KERNEL);
1521 *buffer = isp->smk_known; 1516 if (*buffer == NULL)
1522 rc = ilen; 1517 return -ENOMEM;
1523 } 1518 }
1524 1519
1525 return rc; 1520 return strlen(isp->smk_known);
1526} 1521}
1527 1522
1528 1523
diff --git a/security/tomoyo/Makefile b/security/tomoyo/Makefile
index 65dbcb2fd850..b7c6a7ffc058 100644
--- a/security/tomoyo/Makefile
+++ b/security/tomoyo/Makefile
@@ -1,3 +1,4 @@
1# SPDX-License-Identifier: GPL-2.0
1obj-y = audit.o common.o condition.o domain.o environ.o file.o gc.o group.o load_policy.o memory.o mount.o network.o realpath.o securityfs_if.o tomoyo.o util.o 2obj-y = audit.o common.o condition.o domain.o environ.o file.o gc.o group.o load_policy.o memory.o mount.o network.o realpath.o securityfs_if.o tomoyo.o util.o
2 3
3targets += builtin-policy.h 4targets += builtin-policy.h
diff --git a/security/tomoyo/audit.c b/security/tomoyo/audit.c
index a51edfbe593b..0f73fe30e37a 100644
--- a/security/tomoyo/audit.c
+++ b/security/tomoyo/audit.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/audit.c 3 * security/tomoyo/audit.c
3 * 4 *
diff --git a/security/tomoyo/common.c b/security/tomoyo/common.c
index c19970db89c4..25eed4b0b0e8 100644
--- a/security/tomoyo/common.c
+++ b/security/tomoyo/common.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/common.c 3 * security/tomoyo/common.c
3 * 4 *
diff --git a/security/tomoyo/common.h b/security/tomoyo/common.h
index d9628d1635b2..7adccdd8e36d 100644
--- a/security/tomoyo/common.h
+++ b/security/tomoyo/common.h
@@ -1,3 +1,4 @@
1/* SPDX-License-Identifier: GPL-2.0 */
1/* 2/*
2 * security/tomoyo/common.h 3 * security/tomoyo/common.h
3 * 4 *
diff --git a/security/tomoyo/condition.c b/security/tomoyo/condition.c
index 6c4528d4b48f..8d0e1b9c9c57 100644
--- a/security/tomoyo/condition.c
+++ b/security/tomoyo/condition.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/condition.c 3 * security/tomoyo/condition.c
3 * 4 *
diff --git a/security/tomoyo/domain.c b/security/tomoyo/domain.c
index 00d223e9fb37..f6758dad981f 100644
--- a/security/tomoyo/domain.c
+++ b/security/tomoyo/domain.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/domain.c 3 * security/tomoyo/domain.c
3 * 4 *
diff --git a/security/tomoyo/environ.c b/security/tomoyo/environ.c
index ad4c6e18a437..7f0a471f19b2 100644
--- a/security/tomoyo/environ.c
+++ b/security/tomoyo/environ.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/environ.c 3 * security/tomoyo/environ.c
3 * 4 *
diff --git a/security/tomoyo/file.c b/security/tomoyo/file.c
index 223f21ffa632..2a374b4da8f5 100644
--- a/security/tomoyo/file.c
+++ b/security/tomoyo/file.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/file.c 3 * security/tomoyo/file.c
3 * 4 *
diff --git a/security/tomoyo/gc.c b/security/tomoyo/gc.c
index 540bc29e1b5a..e22bea811c57 100644
--- a/security/tomoyo/gc.c
+++ b/security/tomoyo/gc.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/gc.c 3 * security/tomoyo/gc.c
3 * 4 *
diff --git a/security/tomoyo/group.c b/security/tomoyo/group.c
index 944ad77d8fba..21b0cc3a7e1a 100644
--- a/security/tomoyo/group.c
+++ b/security/tomoyo/group.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/group.c 3 * security/tomoyo/group.c
3 * 4 *
diff --git a/security/tomoyo/load_policy.c b/security/tomoyo/load_policy.c
index 078fac0bb4c5..81b951652051 100644
--- a/security/tomoyo/load_policy.c
+++ b/security/tomoyo/load_policy.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/load_policy.c 3 * security/tomoyo/load_policy.c
3 * 4 *
diff --git a/security/tomoyo/memory.c b/security/tomoyo/memory.c
index 1598b559ac42..12477e0b0a11 100644
--- a/security/tomoyo/memory.c
+++ b/security/tomoyo/memory.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/memory.c 3 * security/tomoyo/memory.c
3 * 4 *
diff --git a/security/tomoyo/mount.c b/security/tomoyo/mount.c
index 14b53fb2a0cf..807fd91dbb54 100644
--- a/security/tomoyo/mount.c
+++ b/security/tomoyo/mount.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/mount.c 3 * security/tomoyo/mount.c
3 * 4 *
diff --git a/security/tomoyo/network.c b/security/tomoyo/network.c
index 6c02ac478247..cd6932e5225c 100644
--- a/security/tomoyo/network.c
+++ b/security/tomoyo/network.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/network.c 3 * security/tomoyo/network.c
3 * 4 *
diff --git a/security/tomoyo/realpath.c b/security/tomoyo/realpath.c
index a97b275ca3af..6ff8c21e4fff 100644
--- a/security/tomoyo/realpath.c
+++ b/security/tomoyo/realpath.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/realpath.c 3 * security/tomoyo/realpath.c
3 * 4 *
diff --git a/security/tomoyo/securityfs_if.c b/security/tomoyo/securityfs_if.c
index 06ab41b1ff28..49393c2a3f8b 100644
--- a/security/tomoyo/securityfs_if.c
+++ b/security/tomoyo/securityfs_if.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/securityfs_if.c 3 * security/tomoyo/securityfs_if.c
3 * 4 *
diff --git a/security/tomoyo/tomoyo.c b/security/tomoyo/tomoyo.c
index d25b705360e0..213b8c593668 100644
--- a/security/tomoyo/tomoyo.c
+++ b/security/tomoyo/tomoyo.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/tomoyo.c 3 * security/tomoyo/tomoyo.c
3 * 4 *
diff --git a/security/tomoyo/util.c b/security/tomoyo/util.c
index cac431d381d2..d3d9d9f1edb0 100644
--- a/security/tomoyo/util.c
+++ b/security/tomoyo/util.c
@@ -1,3 +1,4 @@
1// SPDX-License-Identifier: GPL-2.0
1/* 2/*
2 * security/tomoyo/util.c 3 * security/tomoyo/util.c
3 * 4 *